diff --git a/.agents/WORKFLOWS.md b/.agents/WORKFLOWS.md new file mode 100644 index 000000000000..0352ad7e2e17 --- /dev/null +++ b/.agents/WORKFLOWS.md @@ -0,0 +1,14 @@ +# Workflows Menu + +This document lists the available high-level workflows in this repository and the rules governing them. To use one, the user must explicitly invoke it. + +## Rules of Engagement (Active in Workflow Mode) +1. **No Blind Fixes:** Never modify YAML or Go files without presenting an implementation plan and receiving approval. +2. **Source of Truth:** `magic-modules` contains YAML schema definitions in `mmv1/` and templates. Code is generated into downstream providers. +3. **Use Skills:** Discover and leverage `.agents/skills/` to perform complex tasks. + +## Available Workflows: + +* **Default Workflow** (`.agents/skills/workflows/default/SKILL.md`): For tasks that do not involve creating a new resource (fallback for general tasks). +* **New Resource Workflow** (`.agents/skills/workflows/new_resource/SKILL.md`): Specifically for creating a new resource, supporting both autogen and manual generation. +* *(Future workflows can be added here)* diff --git a/.agents/agents/autogen/agent.json b/.agents/agents/autogen/agent.json new file mode 100644 index 000000000000..f2f191017d15 --- /dev/null +++ b/.agents/agents/autogen/agent.json @@ -0,0 +1,6 @@ +{ + "name": "autogen", + "configPath": { + "relativePathToConfig": "config.yaml" + } +} diff --git a/.agents/agents/autogen/config.yaml b/.agents/agents/autogen/config.yaml new file mode 100644 index 000000000000..afe8dd8a624b --- /dev/null +++ b/.agents/agents/autogen/config.yaml @@ -0,0 +1,33 @@ +custom_agent: + system_prompt_sections: + - title: "Role & Persona" + content: "You are a Software Engineer working on the Magic Modules project to produce new Terraform resources." + - title: "Core Instructions" + content: | + Your task is to generate new Terraform resources based on OpenAPI specifications. + + Follow these steps: + 1. Identify the resources to be generated from the OpenAPI specification. + 2. Identify the OpenAPI specification file to use and verify it is in the correct folder + 3. Use the autogen tool to generate resources. The invocation is: `go run . --openapi-generate` from within the mmv1 directory + 4. Remove any other resources that were generated + 5. Using any guides provided by the user, identify key use cases and write acceptance tests for them in the samples format used in Magic Modules. + - Find information on the samples format in `docs/content/test/test.md`. + - Include update steps if the resource is mutable. + 6. If there are other resources already implemented in this product, seek consistency with them. + - Prefer the existing patterns in the product over the generic patterns in the mmv1 templates. + - Things to check are URL patterns, operation handling, how to name region or location fields and whether they inherit from provider defaults. Region zone and project are special in that they may not need to be required if they can inherit from the provider. + 7. Check if the resource should go in the beta or GA provider based on the OpenAPI spec and any other guides you can find + 8. Generate the downstream provider + 9. Verify that the new resources and tests are present + 10. Run the acceptance tests and verify that they pass + + - title: "Report Format" + content: "You must return a clear, human-readable Markdown report explaining whether resource generation and testing succeeded or failed, and if it failed, what discrepancy was found." + + tool_names: + - view_file + - run_command + - grep_search + +command_execution_policy: "eager" diff --git a/.agents/agents/qa-test-runner/agent.json b/.agents/agents/qa-test-runner/agent.json new file mode 100644 index 000000000000..45ac682fbe40 --- /dev/null +++ b/.agents/agents/qa-test-runner/agent.json @@ -0,0 +1,6 @@ +{ + "name": "qa-test-runner", + "configPath": { + "relativePathToConfig": "config.yaml" + } +} diff --git a/.agents/agents/qa-test-runner/config.yaml b/.agents/agents/qa-test-runner/config.yaml new file mode 100644 index 000000000000..ff1bebafd9bf --- /dev/null +++ b/.agents/agents/qa-test-runner/config.yaml @@ -0,0 +1,30 @@ +custom_agent: + system_prompt_sections: + - title: "Role & Persona" + content: "You are a Staff QA Engineer reproducing test failures and isolating API discrepancies." + - title: "Core Instructions" + content: | + Your task is to run an acceptance test and explain why it failed. Do NOT modify source files. Do NOT guess the fix. + + To execute this work, you must use the `run-acctests` skill (to run the test) and the `parse-debug-logs` skill (to parse the output). + + Follow these steps: + 1. **Skill Location:** Read the `SKILL.md` located in the `magic-modules` workspace under `.agents/skills/utils/run-acctests/` and `.agents/skills/utils/parse-debug-logs/`. Do not look for skills in the downstream repository. + 2. **Environment (macOS):** Prepend `/usr/local/go/bin` to your `PATH` and ensure Go is available. + 3. **Credentials:** If standard acceptance test environment variables (like `GOOGLE_CREDENTIALS`, `GOOGLE_PROJECT`) are missing, check if they are defined in `.bash_profile` or ask the user. + 4. **Verify Workspace:** Ensure you are in the downstream provider repository. Do not verify the upstream magic-modules directory state. + 5. **Run Test:** Use the `run-acctests` skill to run the target test. + 6. **Evaluate:** + - If it passes, stop and report success. + - If it fails, proceed to parsing. + 7. **Parse Logs:** Use the `parse-debug-logs` skill to parse output. You should use the output directory specified in your task prompt (e.g., a `debug_output` folder in `magic-modules`). Read the generated `outline.txt` and JSON payloads from that directory. + 8. **Interpret failure:** Explain *what* happened (e.g. "The API rejected the request because X field was missing"). Compare the expected Terraform state against the actual API JSON payload found in the output directory. + - title: "Report Format" + content: "You must return a clear, human-readable Markdown report explaining whether the test succeeded or failed, and if it failed, what discrepancy was found." + + tool_names: + - view_file + - run_command + - grep_search + +command_execution_policy: "eager" \ No newline at end of file diff --git a/.agents/agents/repo-sync/agent.json b/.agents/agents/repo-sync/agent.json new file mode 100644 index 000000000000..1bd380b32feb --- /dev/null +++ b/.agents/agents/repo-sync/agent.json @@ -0,0 +1,6 @@ +{ + "name": "repo-sync", + "configPath": { + "relativePathToConfig": "config.yaml" + } +} diff --git a/.agents/agents/repo-sync/config.yaml b/.agents/agents/repo-sync/config.yaml new file mode 100644 index 000000000000..a1e59bcb657b --- /dev/null +++ b/.agents/agents/repo-sync/config.yaml @@ -0,0 +1,17 @@ +custom_agent: + system_prompt_sections: + - title: "Role & Persona" + content: "You are a Workspace Initialization Engineer. You verify parity and readiness." + - title: "Core Instructions" + content: | + Your task is to verify if the user's workspace is ready to work in. + + 1. **Target downstream:** You will receive the explicit, absolute path to the downstream repo in your initial task prompt. You MUST operate within that exact path. Do not attempt to guess the path. + 2. **Skill Location:** Read the `SKILL.md` located in the `magic-modules` workspace (the "Source of Truth") under `.agents/skills/utils/sync-provider/` and follow its instructions EXACTLY. Do not look for skills in the downstream repository. + 3. **Environment (macOS):** If Go 1.26+ is not found or standard tools fail, prepend `/opt/homebrew/bin` to your `PATH` and manually export `GOPATH` to ensure the compilation succeeds. + tool_names: + - view_file + - run_command + - grep_search + +command_execution_policy: "eager" \ No newline at end of file diff --git a/.agents/rules/terminology.md b/.agents/rules/terminology.md new file mode 100644 index 000000000000..b1272dc7d179 --- /dev/null +++ b/.agents/rules/terminology.md @@ -0,0 +1,17 @@ +--- +trigger: always_on +description: Vocabulary definitions for standard actions in this repository +--- + +# Terminology Rules + +## 1. Sync +- **Definition:** Aligning the Git histories of `magic-modules` and a downstream provider using the `sync-provider` skill. Setting up a clean baseline for verification. + +## 2. Generate +- **Definition:** Running `make provider` from Magic Modules to generate code into the downstream repository. +- **When to use:** When you have modified local YAML/templates and need to see their output in Go code. + +## 3. Build +- **Definition:** Running `make build` in a downstream provider to compile the Go binary. This could be ambiguous with "generate", so if you are not sure, clarifiy with the user. +- **When to use:** When handwriting Go changes or testing compilation. diff --git a/.agents/scripts/tf_debug_parser.py b/.agents/scripts/tf_debug_parser.py new file mode 100755 index 000000000000..aa225322db85 --- /dev/null +++ b/.agents/scripts/tf_debug_parser.py @@ -0,0 +1,383 @@ +#!/usr/bin/env python3 +import sys +import re +import json +import os +import argparse +import time +from typing import List, Dict, Any, Optional + +class TFDebugParser: + def __init__(self, filepath: str): + self.filepath = filepath + self.events = [] + self.failures = [] + self.diffs = [] + self.outline = [] + self.test_name = "unknown_test" + + # We want an opt-out approach for the outline to preserve unexpected logs by default. + self.outline_exclusions = [ + re.compile(r'\[DEBUG\] sdk\.helper_resource: (?!Starting TestStep:)'), + re.compile(r'\[DEBUG\] sdk\.helper_schema:'), + re.compile(r'\[DEBUG\] Retry Transport:'), + re.compile(r'\[DEBUG\] Waiting for state to become:'), + re.compile(r'Authenticating using configured Google JSON'), + re.compile(r'-- Scopes: \['), + re.compile(r'\[DEBUG\] VCR_PATH'), + re.compile(r'\[DEBUG\] Google API Request Details:'), + re.compile(r'\[DEBUG\] Google API Response Details:'), + re.compile(r'\[DEBUG\]TGC Terraform metadata:'), + re.compile(r'\[DEBUG\]TGC Terraform error:'), + re.compile(r'\[DEBUG\] CaiAssetNames'), + re.compile(r'\[DEBUG\] tgcPayload'), + re.compile(r'\[WARN\] sdk\.helper_schema:'), + re.compile(r'\[DEBUG\] setting computed for'), + re.compile(r'==> Checking that code complies'), + re.compile(r'go vet'), + ] + + self.chunk_separators = [ + re.compile(r'^=== RUN'), + re.compile(r'\[DEBUG\] sdk\.helper_resource: Starting TestStep:'), + re.compile(r'\[DEBUG\] Creating new '), + re.compile(r'\[DEBUG\] Finished creating '), + re.compile(r'\[DEBUG\] Deleting '), + re.compile(r'\[DEBUG\] Finished deleting '), + re.compile(r'\[DEBUG\]test_step_number=\d+ TGC Terraform metadata:'), + re.compile(r'\[ERROR\]'), + re.compile(r'^--- (FAIL|PASS)'), + ] + self.identity_re = re.compile(r'\[INFO\] Terraform is using this identity:') + self.last_was_identity = False + self.identity_seen = False + + def should_include_in_outline(self, line: str) -> bool: + for ex in self.outline_exclusions: + if ex.search(line): + return False + + # Deduplicate identity logs + if self.identity_re.search(line): + if self.identity_seen: + return False + self.identity_seen = True + + return True + + def parse(self): + with open(self.filepath, 'r') as f: + lines = f.readlines() + + current_state = None + current_event: Dict[str, Any] = {} + current_buffer = [] + + diff_state = False + diff_buffer = [] + + # basic regexes for extraction + req_start_re = re.compile(r'---\[ REQUEST \]---') + res_start_re = re.compile(r'---\[ RESPONSE \]---') + end_re = re.compile(r'-----------------------------------------------------') + + # When we are in a payload block, we omit it from the outline, + # and instead inject a marker when the block ends. + in_payload_block = False + + googleapi_error_state = False + warn_error_state = False + + # basic regexes for extraction + req_start_re = re.compile(r'---\[ REQUEST ]---') + res_start_re = re.compile(r'---\[ RESPONSE ]---') + end_re = re.compile(r'-----------------------------------------------------') + + method_url_re = re.compile(r'^(GET|POST|PUT|DELETE|PATCH) (.*) HTTP/\d\.\d') + status_re = re.compile(r'^HTTP/\d\.\d (\d{3} .*)') + fail_re = re.compile(r'(FAIL:|Error:|Step \d+/\d+ error:)') + diff_start_re = re.compile(r'Terraform used the selected providers to generate the following execution|Terraform will perform the following actions|plan. Resource actions are indicated with the following symbols:') + diff_end_re = re.compile(r'Plan: \d+ to add, \d+ to change, \d+ to destroy.') + + for i, line in enumerate(lines): + clean_line = line.strip() + + # 0. Check for Test Name Execution + if "=== RUN TestAcc" in clean_line: + self.test_name = clean_line.split(" ")[-1] + + # 1. Check for Failures/Errors + if fail_re.search(clean_line) and not diff_state and current_state is None: + self.failures.append({"line": i+1, "message": clean_line}) + + # 2. Check for Diff Block + if diff_start_re.search(clean_line) and not diff_state: + diff_state = True + diff_buffer = [clean_line] + continue + + if diff_state: + diff_buffer.append(line.rstrip('\r\n')) + if diff_end_re.search(clean_line): + diff_state = False + diff_text = "\n".join(diff_buffer) + + # Deduplicate consecutive identical diffs (ignoring pipes/whitespace) + raw_current = re.sub(r'[\s\|]', '', diff_text) + is_duplicate = False + if self.diffs and re.sub(r'[\s\|]', '', self.diffs[-1]) == raw_current: + is_duplicate = True + if '|' in self.diffs[-1] and '|' not in diff_text: + self.diffs[-1] = diff_text + if self.events and self.events[-1]["type"] == "diff": + self.events[-1]["content"] = diff_text + + # Find the last diff marker in the outline and replace the subsequent text + # This is a bit complex, so instead of trying to perfectly replace it, + # we'll just let the deduplication prefer the better text in the payloads directory. + # The outline will just contain whatever the first diff was (usually with pipes). + + if not is_duplicate: + self.diffs.append(diff_text) + self.events.append({"type": "diff", "content": diff_text, "line": i+1}) + + # Add diff marker sequence to outline + event_index = len(self.events) + prefix = f"{event_index:02d}_DIFF.txt" + if self.outline and self.outline[-1] != "\n": + self.outline.append("\n") + self.outline.append(f"-> [{prefix}]\n") + self.outline.append(f"{diff_text}\n") + self.last_was_identity = False + continue + + + # 3. Check for Request/Response blocks + if req_start_re.search(clean_line): + current_state = "REQUEST" + in_payload_block = True + current_event = {"type": "request", "line": i+1} + current_buffer = [] + continue + + if res_start_re.search(clean_line): + current_state = "RESPONSE" + in_payload_block = True + current_event = {"type": "response", "line": i+1} + current_buffer = [] + continue + + if end_re.search(clean_line) and current_state is not None: + # Process the buffer we just collected + if current_state == "REQUEST": + # Parse Method and URL + for j, bline in enumerate(current_buffer): + m = method_url_re.search(bline) + if m: + current_event["method"] = m.group(1) + current_event["url"] = m.group(2).split('?')[0] # strip query for cleaner overview + break + elif current_state == "RESPONSE": + # Parse Status Code + for j, bline in enumerate(current_buffer): + m = status_re.search(bline) + if m: + current_event["status"] = m.group(1) + break + + # Try to extract JSON body if it exists + body_start = -1 + for j, bline in enumerate(current_buffer): + if bline.startswith('{') or bline.startswith('['): + body_start = j + break + + if body_start != -1: + raw_body = "\n".join(current_buffer[body_start:]) + try: + current_event["body"] = json.loads(raw_body) + except json.JSONDecodeError: + current_event["body"] = raw_body # fallback to string + + self.events.append(current_event) + + # Add marker to outline + event_index = len(self.events) + prefix = f"{event_index:02d}_{current_event['type'].upper()}" + if current_event["type"] == "request": + filename = f"{prefix}_{current_event.get('method', 'UNKNOWN')}.json" + self.outline.append(f" -> [{filename}]\n") + else: + filename = f"{prefix}_{current_event.get('status', 'UNKNOWN').replace(' ', '_')}.json" + self.outline.append(f" <- [{filename}]\n") + + current_state = None + in_payload_block = False + current_event = {} + self.last_was_identity = False + continue + + if current_state is not None: + current_buffer.append(clean_line) + + # 4. Check for unformatted googleapi HTTP dump noise + if "googleapi: got HTTP response code" in clean_line: + googleapi_error_state = True + continue + if googleapi_error_state: + # The payload is over once we hit a standard log line with a timestamp + if re.match(r'^\d{4}[/-]\d{2}[/-]\d{2}[T\s]', clean_line): + googleapi_error_state = False + else: + continue + + # 5. Check for redundant [WARN] error block + if "[WARN] sdk.helper_resource: Error running Terraform CLI command:" in clean_line: + warn_error_state = True + continue + if warn_error_state: + # The redundant block ends when the actual [ERROR] block starts + if "[ERROR]" in clean_line: + warn_error_state = False + else: + continue + + # 6. Add line to outline if it isn't an exclusion and we aren't inside a raw payload block + if not in_payload_block and not diff_state and self.should_include_in_outline(clean_line): + # Don't add the start/end lines of diffs since we inject the marker + if not diff_start_re.search(clean_line): + is_identity = bool(self.identity_re.search(clean_line)) + + needs_newline = False + for sep in self.chunk_separators: + if sep.search(clean_line): + needs_newline = True + break + + if is_identity and not self.last_was_identity: + needs_newline = True + + if needs_newline and self.outline and self.outline[-1] != "\n": + self.outline.append("\n") + + formatted_line = clean_line + + # 1. Strip timestamps + timestamp_re = re.compile(r'^\d{4}[/-]\d{2}[/-]\d{2}[T\s]\d{2}:\d{2}:\d{2}(?:\.\d{3}[+-]\d{4})?\s+') + formatted_line = timestamp_re.sub('', formatted_line) + + # 2. Truncate struct data dumps + map_dump_re = re.compile(r':\s*map\[string\]interface\s*\{\}.*$') + if map_dump_re.search(formatted_line): + formatted_line = map_dump_re.sub('...', formatted_line) + + # 3. Format Test Steps Visually + step_re = re.compile(r'\[DEBUG\] sdk\.helper_resource: Starting TestStep:.*?test_step_number=(\d+).*') + m = step_re.match(formatted_line) + if m: + step_num = m.group(1) + formatted_line = f">>> STARTING TEST STEP {step_num} <<<" + + # 4. Strip redundant error noise + # The lines immediately following a failure contain duplicate info + if formatted_line.startswith("test_step_number="): + continue + if "error: After applying this test step" in formatted_line: + continue + if formatted_line.strip() == "stdout:": + continue + + self.outline.append(f"{formatted_line}\n") + self.last_was_identity = is_identity + + def print_summary(self): + print("====== API TIMELINE ======") + for i, ev in enumerate(self.events): + if ev["type"] == "request": + print(f"[{i+1}] REQ: {ev.get('method', 'UNKNOWN')} {ev.get('url', 'UNKNOWN')}") + elif ev["type"] == "diff": + print(f"[{i+1}] DIFF: Terraform Plan Diff") + else: + status = ev.get('status', 'UNKNOWN') + body_keys = "No Body" + if "body" in ev and isinstance(ev["body"], dict): + body_keys = f"Keys: {', '.join(ev['body'].keys())}" + print(f"[{i+1}] RES: Status {status} | {body_keys}") + + print("\n====== FAILURES ======") + for f in self.failures: + print(f"Line {f['line']}: {f['message']}") + + print("\n====== LATEST DIFF ======") + if self.diffs: + print(self.diffs[-1]) + else: + print("No plan diff found.") + + def export_dir(self, base_dir: str): + timestamp = int(time.time()) + out_dir = os.path.join(base_dir, f"{self.test_name}_{timestamp}") + + if not os.path.exists(out_dir): + os.makedirs(out_dir) + + for i, ev in enumerate(self.events): + prefix = f"{i+1:02d}_{ev['type'].upper()}" + if ev["type"] == "request": + filename = f"{prefix}_{ev.get('method', 'UNKNOWN')}.json" + filepath = os.path.join(out_dir, filename) + with open(filepath, 'w') as f: + json.dump(ev, f, indent=2) + elif ev["type"] == "diff": + filename = f"{prefix}.txt" + filepath = os.path.join(out_dir, filename) + with open(filepath, 'w') as f: + f.write(ev.get("content", "")) + else: + filename = f"{prefix}_{ev.get('status', 'UNKNOWN').replace(' ', '_')}.json" + filepath = os.path.join(out_dir, filename) + with open(filepath, 'w') as f: + json.dump(ev, f, indent=2) + + # Write outline + with open(os.path.join(out_dir, "outline.txt"), 'w') as f: + for line in self.outline: + f.write(line) + + # Write failures + with open(os.path.join(out_dir, "failures.json"), 'w') as f: + json.dump(self.failures, f, indent=2) + + print(f"Extracted API timeline and errors to {out_dir}/") + return json.dumps({ + "timeline": self.events, + "failures": self.failures, + "diffs": self.diffs + }, indent=2) + +def main(): + parser = argparse.ArgumentParser(description="Parse Terraform Debug Logs for API interaction and errors.") + parser.add_argument("logfile", help="Path to the TF_LOG=DEBUG output file") + parser.add_argument("--summary", action="store_true", help="Print a human-readable summary to stdout") + parser.add_argument("--json", action="store_true", help="Output the full parsed structured timeline as JSON") + + parser.add_argument("--extract-dir", help="Directory to write extracted API JSON files and errors to") + + args = parser.parse_args() + + if not os.path.exists(args.logfile): + print(f"Error: File {args.logfile} not found.") + sys.exit(1) + + tf_parser = TFDebugParser(args.logfile) + tf_parser.parse() + + if args.extract_dir: + tf_parser.export_dir(args.extract_dir) + elif args.json: + print(tf_parser.export_json()) + else: + tf_parser.print_summary() + +if __name__ == "__main__": + main() diff --git a/.agents/skills/SKILL_TEMPLATE.md b/.agents/skills/SKILL_TEMPLATE.md new file mode 100644 index 000000000000..852b2f2a4c76 --- /dev/null +++ b/.agents/skills/SKILL_TEMPLATE.md @@ -0,0 +1,36 @@ +--- +name: template-skill +description: "A single-sentence description of what this skill does and when an agent should invoke it." +--- + +# `template-skill` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +List any environment variables, workspace parity checks, or directory contexts required before executing this skill. +* Example: "You must be in the `magic-modules` root directory." + +## Execution Steps + +### 1. Verification +Provide the exact bash commands the agent should run to verify the prerequisites. Do NOT let the agent proceed if this fails. + +#### Example: Verify Directory +```bash +pwd # Verify we are in /Users/camthornton/magic-modules +``` + +### 2. The Core Commands +Provide the precise, bulletproof bash commands, python script, or instruction set the agent needs to execute. This replaces the agent having to guess CLI flags or complex arguments. + +#### Example: Compile Downstream Provider +```bash +# Make terraform provider for Beta +make terraform VERSION=beta OUTPUT_PATH=$GOPATH/src/github.com/hashicorp/terraform-provider-google-beta PRODUCT=compute +``` + +### 3. Verification & Handoff +Instructions on how the agent should verify the command succeeded, and what workflow or rule it should return to next. + +* Example: "If the `make testacc` command fails, you MUST immediately invoke the `parse-debug-logs` skill. Do not attempt a blind fix." diff --git a/.agents/skills/operations/fix/SKILL.md b/.agents/skills/operations/fix/SKILL.md new file mode 100644 index 000000000000..776b6905c5e9 --- /dev/null +++ b/.agents/skills/operations/fix/SKILL.md @@ -0,0 +1,19 @@ +--- +name: fix +description: "Plan a remediation strategy after a test failure." +--- + +# `fix` + +Use this skill after the `qa-test-runner` subagent returns a failure report. Your job is to analyze the failure and propose a new fix strategy (Remediation Planning). Do NOT run generation or testing yourself. + +## Execution Steps + +### 1. Analyze Failure +Read the report returned by `qa-test-runner`. Compare findings against standard troubleshooting patterns (e.g. perpetual diffs, normalization issues). + +### 2. Propose a New Strategy +Ask the user if they have a suggested change, or if you should propose a new strategy from reference guides. Offer specific recommendations. + +### 3. Handoff +Once a solution is agreed upon, apply the change manually, and then transition back to Step 3 (Generate) to compile the fix. diff --git a/.agents/skills/operations/generate-provider/SKILL.md b/.agents/skills/operations/generate-provider/SKILL.md new file mode 100644 index 000000000000..af17ddb216af --- /dev/null +++ b/.agents/skills/operations/generate-provider/SKILL.md @@ -0,0 +1,50 @@ +--- +name: generate-provider +description: "Executes code generation from Magic Modules into downstream Terraform providers and optionally compiles the binary." +--- + +# `generate-provider` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +* You must be in the `magic-modules` root directory. +* The `$GOPATH` environment variable must be set correctly. +* You must have verified there are no unsaved or uncommitted changes in the downstream provider directory that would be overwritten by code generation. + +## Execution Steps + +Set your variables and run the commands in sequence. + +```bash +# 1. Define Variables +VERSION="beta" # or "ga" +PROVIDER_PATH="$GOPATH/src/github.com/hashicorp/terraform-provider-google-beta" # or "terraform-provider-google" for GA + +# Verify we are in /Users/camthornton/magic-modules +pwd + +# Verify no uncommitted changes exist in the downstream provider directory. +# Stop if there are uncommitted changes and alert the user. +cd "$PROVIDER_PATH" +git status --porcelain + +# 2. Code Generation (Run from Magic Modules root) +cd /Users/camthornton/magic-modules +make provider VERSION=$VERSION OUTPUT_PATH="$PROVIDER_PATH" + +# 3. Verify Changes (Run from Downstream Provider root) +cd "$PROVIDER_PATH" + +# Verify that git status precisely matches the scope of your local Magic Modules edits. +# If you see "surprise" diffs in unrelated resources, ask the user if you should run `sync-provider` first. +git status --porcelain + +# 4. Compile Binary (Already in Downstream Provider root) +make build +``` + +## Handoff & Guardrails + +- Verify successful compilation. +- **CRITICAL SAFEGUARD:** Stop here! Do NOT automatically proceed to running tests unless the user explicitly requested you to do so in their initial prompt. If testing was not requested, ask the user for their next steps. diff --git a/.agents/skills/operations/qa-test-runner/SKILL.md b/.agents/skills/operations/qa-test-runner/SKILL.md new file mode 100644 index 000000000000..6e89331a0c15 --- /dev/null +++ b/.agents/skills/operations/qa-test-runner/SKILL.md @@ -0,0 +1,22 @@ +--- +name: qa-test-runner +description: "Triggers the QA Test Runner subagent to reproduce failures and interpret logs." +--- + +# `qa-test-runner` + +Use this skill to delegate heavy test reproduction and log parsing to a dedicated Subagent. This keeps your main context window clean. + +## Execution Steps + +### 1. Identify Target and Context +Gather context on *what* changed (the resource, the field, the PR) and which test you need to run. + +### 2. Invoke Subagent +Use the `invoke_subagent` tool. Pass the context of the change as part of the trigger prompt so the subagent knows what it's looking for! + +**Trigger Example:** +invoke_subagent("qa-test-runner", "Run . We just made the following change: . Verify if it fails or passes. Use your active workspace to find the magic-modules path and output debug logs to /debug_output.") + +### 3. Verify Report +Read the human-readable Markdown report returned by the subagent. Formulate a fix strategy using `troubleshooting_reference.md` based on their analysis. diff --git a/.agents/skills/operations/repo-sync/SKILL.md b/.agents/skills/operations/repo-sync/SKILL.md new file mode 100644 index 000000000000..9dbb4022be9d --- /dev/null +++ b/.agents/skills/operations/repo-sync/SKILL.md @@ -0,0 +1,22 @@ +--- +name: repo-sync +description: "Checks sync status and invokes the subagent to align repositories if needed." +--- + +# `repo-sync` + +Use this skill to check if the downstream workspace is synchronized with Magic Modules and to perform the sync if needed. + +## Execution Steps + +### 1. Check Sync Status +* Execute the `check-sync-provider` skill (located in `.agents/skills/utils/check-sync-provider/SKILL.md`) to determine if the downstream repository is aligned with the correct Magic Modules base commit. + +### 2. Prompt User if Needed +* If the workspace is clearly out of sync or if you are unsure, **ask the user** if they would like to run a full repository sync to establish a clean baseline. +* If the user says no, skip the sync and report back to the workflow. + +### 3. Execute Sync +* If the user agrees or if you are confident a sync is required and safe, use the `invoke_subagent` tool to call the `repo-sync` subagent. +* **Prompt to send:** "Please initialize and sync the workspace located at the following path: ``" +* Wait for the subagent to return its final completion message. \ No newline at end of file diff --git a/.agents/skills/operations/triage/SKILL.md b/.agents/skills/operations/triage/SKILL.md new file mode 100644 index 000000000000..c8ac0b1a06af --- /dev/null +++ b/.agents/skills/operations/triage/SKILL.md @@ -0,0 +1,22 @@ +--- +name: triage +description: "Gather context on a change or bug and plan the implementation." +--- + +# `triage` + +Use this skill when a user asks you to implement a feature or fix a bug. Gather context and plan before writing code. + +## Execution Steps + +### 1. Gather Context (Ask User First) +Propose multiple places to look (Resource YAML definitions and Cloud API documentation) and ask the user where to start. Plan the change (New feature or bug fix) within schema or logic. + +### 2. Formulate a Proposal +- Write an `implementation_plan.md` in your temporary artifacts. +- State the intent of the change. +- List the files to modify. + +### 3. Verification & Handoff +- Halt. Discuss the plan with the user. +- Once approved and the change is made, proceed back to the outer loop (Step 3: Generate). diff --git a/.agents/skills/utils/check-sync-provider/SKILL.md b/.agents/skills/utils/check-sync-provider/SKILL.md new file mode 100644 index 000000000000..d3c49c0022f5 --- /dev/null +++ b/.agents/skills/utils/check-sync-provider/SKILL.md @@ -0,0 +1,24 @@ +--- +name: check-sync-provider +description: "Checks if the downstream provider repository is aligned with the correct Magic Modules base commit." +--- + +# `check-sync-provider` + +Use this skill to verify if the downstream repository is at the correct baseline commit before generating code or running tests. + +## Execution Steps + +### 1. Identify Magic Modules Base Commit +* Identify the official `GoogleCloudPlatform/magic-modules` remote (usually `upstream`). +* Calculate the target base commit: + * If on `main`: Use current commit (`HEAD`). + * If on a feature branch: Run `git merge-base HEAD /main` to find where the branch diverged. + +### 2. Find the Matching Downstream Commit +* Search the downstream repository's log for a commit that references this Magic Modules base commit hash in its commit message. + +### 3. Compare and Report +* Verify if the `HEAD` of the downstream repository matches that found commit. +* If they match, report **Synced**. +* If they do not match, or the commit cannot be found, report **Out of Sync** and provide the details. diff --git a/.agents/skills/utils/dev-overrides/SKILL.md b/.agents/skills/utils/dev-overrides/SKILL.md new file mode 100644 index 000000000000..2f225a8a1646 --- /dev/null +++ b/.agents/skills/utils/dev-overrides/SKILL.md @@ -0,0 +1,49 @@ +--- +name: dev-overrides +description: "Configures Terraform CLI with developer overrides to test locally built provider binaries without full Go acceptance tests, enabling rapid plan/apply cycles." +--- + +# `dev-overrides` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +* You must have successfully compiled a local provider binary using the `generate-provider` skill. +* You need a directory containing the `.tf` configuration you want to test. + +## Execution Steps + +### 1. Verification +Ensure the provider binaries exist in the expected output paths. + +#### Verify Built Binaries +```bash +# Verify the binaries were built (modify paths as necessary based on your host OS) +ls -lh $GOPATH/bin/terraform-provider-google* +``` + +### 2. The Core Commands +Create a `.terraformrc` file referencing the local binaries and invoke Terraform with it. + +#### Setup Overrides and Test +```bash +# 1. Create the dev override file dynamically +cat << EOF > /tmp/tf-dev-override.tfrc +provider_installation { + dev_overrides { + "hashicorp/google" = "${GOPATH}/bin" + "hashicorp/google-beta" = "${GOPATH}/bin" + } + direct {} +} +EOF + +# 2. Navigate to your test directory and run terraform using the override +# cd /path/to/test-directory +TF_CLI_CONFIG_FILE="/tmp/tf-dev-override.tfrc" terraform plan +# TF_CLI_CONFIG_FILE="/tmp/tf-dev-override.tfrc" terraform apply -auto-approve +``` + +### 3. Verification & Handoff +* Verify Terraform warns that "Provider development overrides are in effect." +* Once the behavior is validated via plan/apply outputs, proceed to write the formal Go acceptance tests. diff --git a/.agents/skills/utils/parse-debug-logs/SKILL.md b/.agents/skills/utils/parse-debug-logs/SKILL.md new file mode 100644 index 000000000000..93f7267a3611 --- /dev/null +++ b/.agents/skills/utils/parse-debug-logs/SKILL.md @@ -0,0 +1,36 @@ +--- +name: parse-debug-logs +description: "Parses massive Terraform debug logs into an easy-to-read outline of API delays, failures, and request payloads." +--- + +# `parse-debug-logs` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +* You must have a debug log file resulting from a failed `run-acctests` execution (e.g., `test_output.log`). + +## Execution Steps + +### 1. Verification +Verify the log file exists. + +#### Verify Log Exists +```bash +# Replace /path/to/test_output.log with the actual path +ls -lh /path/to/test_output.log +``` + +### 2. The Core Commands +Execute the `tf_debug_parser.py` script against the debug logs. + +#### Parse Debug Logs +```bash +# Execute the parser to extract the outline +python3 /.agents/scripts/tf_debug_parser.py /path/to/test_output.log --extract-dir /debug_output +``` + +### 3. Verification & Handoff +* Use the `view_file` tool to read the generated `outline.txt` INSIDE the output directory (or its subdirectory if the script creates one). It contains a compressed timeline of API requests/responses and Terraform state transitions. +* If you find an API error (HTTP 4xx or 5xx) or an unexpected default field, use `view_file` on the specific JSON payload file referenced in `outline.txt` (e.g., `01_REQUEST_POST.json`) found in that same directory. +* Pivot to the `.agents/workflows/troubleshooting_reference.md` document to map the failure to a known fix strategy before invoking the `fix` workflow. diff --git a/.agents/skills/utils/run-acctests/SKILL.md b/.agents/skills/utils/run-acctests/SKILL.md new file mode 100644 index 000000000000..3519d0ad9432 --- /dev/null +++ b/.agents/skills/utils/run-acctests/SKILL.md @@ -0,0 +1,34 @@ +--- +name: run-acctests +description: "Executes acceptance tests (testacc) for a specific resource or suite in the provider and outputs verbose debug logs." +--- + +# `run-acctests` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +* You must be in the relevant provider root directory, e.g., `$GOPATH/src/github.com/hashicorp/terraform-provider-google-beta`. +* You must know the specific service path (e.g., `./google-beta/services/compute`) and test name (e.g., `TestAccComputeInstance_basic`) you wish to run. + +## Execution Steps + +### 1. Verification + +#### Verify Directory Structure +```bash +pwd # Verify we are in the generated provider directory +``` + +### 2. The Core Commands +Run the acceptance test with `TF_LOG=DEBUG` enabled, and stream the output to a log file (`test_output.log`) so it can be parsed later if it fails. + +#### Execute Acceptance Test +```bash +# Replace and with the appropriate values +TF_LOG=DEBUG make testacc TEST=./google-beta/services/ TESTARGS='-run=$$' > test_output.log 2>&1 +``` + +### 3. Verification & Handoff +* If the test succeeds, return to your primary workflow. +* If the test fails, do **NOT** attempt a blind fix immediately. You MUST invoke the `parse-debug-logs` skill on `test_output.log` to understand the API failure before proposing a fix. diff --git a/.agents/skills/utils/schema-review/SKILL.md b/.agents/skills/utils/schema-review/SKILL.md new file mode 100644 index 000000000000..b04676cfa6ea --- /dev/null +++ b/.agents/skills/utils/schema-review/SKILL.md @@ -0,0 +1,30 @@ +--- +name: schema-review +description: "Stub skill for reviewing Magic Modules schemas. Currently covers Enum vs. String trade-offs." +--- + +# `schema-review` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +* You must be in the `magic-modules` root directory. +* You must be reviewing or adding a field. + +## Execution Steps + +### 1. Enum vs. String Trade-off +When adding a field that is defined as an Enum in the API, you must decide between `Enum` and `String` in Magic Modules. + +#### The Trade-off: +* **Prefer `Enum`** when you want strict, plan-time validation of values to fail fast. +* **Prefer `String`** (with allowed values documented) when the API is dynamic or likely to add values. This prevents Terraform from crashing with a validation error for users when the API updates *before* the provider catches up. + +> [!NOTE] +> This skill is a **stub** and will be expanded over time with more schema review checklist items (such as `api_name` overrides, array flattening, output-only fields, etc.). + +### 2. Verification & Handoff +Instructions on how the agent should verify the command succeeded, and what workflow or rule it should return to next. + +* Proceed with your field addition or PR review based on this stylistic choice. +* Reference the `modernization_roadmap.md` for upcoming expansions to this checklist. diff --git a/.agents/skills/utils/sync-provider/SKILL.md b/.agents/skills/utils/sync-provider/SKILL.md new file mode 100644 index 000000000000..53671b2e52d1 --- /dev/null +++ b/.agents/skills/utils/sync-provider/SKILL.md @@ -0,0 +1,98 @@ +--- +name: sync-provider +description: "Synchronize a downstream Terraform provider repository with Magic Modules by aligning commit history and verifying parity." +--- + +# `sync-provider` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your required task. +> This skill is designed to be completely self-contained and unambiguous for a fresh agent without prior context. + +## Prerequisites + +- You must be operating relative to the `magic-modules` and downstream provider repositories. +- You must have the absolute path to the downstream repository (e.g., `terraform-provider-google-beta`). +- You must have verified there are no unsaved or uncommitted changes in the downstream provider directory that would be overwritten by code generation. + +## Execution Steps + +### 1. Identify Magic Modules Base Commit + +Check if the `magic-modules` repository is a fork or has multiple remotes: +```bash +git remote -v +``` + +Identify the official `googleapis/magic-modules` remote (e.g., `origin` or `upstream`). +If it is ambiguous, **ask the user** which remote is the canonical upstream. + +Then calculate the target base commit: + +- **If on `main` (of the upstream):** Use the current commit (`HEAD`). +- **If on a feature branch:** Calculate the merge base where the branch diverged from the canonical `main`: + ```bash + git merge-base HEAD /main + ``` + +Record the base commit hash and date. This hash will be used to find the matching commit in the downstream repository. + +### 2. Check for Uncommitted Downstream Changes + +Before checking out older commits, check if there are local modifications in the downstream repository: +```bash +cd +git status +``` +If changes exist, point them out to the user and **ask if they wish to save/stash them**. Do not proceed without consent. If consent is given, you can stash or reset them. + +### 3. Find the Matching Downstream Commit + +Search for a commit in the downstream repository that corresponds to the Magic Modules base commit hash: +```bash +cd +git log -n 50 --grep="[upstream:]" +``` + +If not found, search `origin/main` (in case your local `main` is behind): +```bash +git log -n 50 --grep="[upstream:]" origin/main +``` +If found, pull your `main` or checkout the specific commit. If not found, try history traversal before falling back to date-based matching. + +#### Fallback: History Traversal (Recommended) + +If the exact base hash is not found, it is likely because the specific `magic-modules` commit did not generate code changes for this specific provider (resulting in no downstream generation commit). + +Walk backwards through the `magic-modules` commit history from your base commit. For each parent commit: + +1. View previous commit history: `git log -n 10 --format="%H %s"` +2. Search for its hash in the downstream: `git log --grep="[upstream:]"` +3. The first commit found is the true synchronization point where the downstream repository diverges or sits. + +#### Fallback: Date-Based Matching + +If no commit message contains the hash, find the commit in the downstream repository that is closest to the date/timestamp of the MM base commit: +```bash +git log --since="" --until="" +``` +Select the commit that appears to be the matching nightly or generation commit. If ambiguous, **ask the user for clarification**. + +### 4. Align Downstream + +Checkout the matching commit in the downstream repository: +```bash +git checkout +``` + +### 5. Verify Parity + +Return to `magic-modules` and run code generation to verify that there are no unexpected diffs: +```bash +cd +make provider VERSION= OUTPUT_PATH="" +``` +Verify the output of `git status` in the downstream repository. It should be clean or only contain changes from our specific branch. + +### 6. Verification & Handoff + +Verify that the `make provider` command succeeded without unexpected diffs. Return to the workflow that invoked this skill to proceed. diff --git a/.agents/skills/utils/verify-api-schema/SKILL.md b/.agents/skills/utils/verify-api-schema/SKILL.md new file mode 100644 index 000000000000..701781e4e08d --- /dev/null +++ b/.agents/skills/utils/verify-api-schema/SKILL.md @@ -0,0 +1,42 @@ +--- +name: verify-api-schema +description: "Verify if an MMv1 YAML property matches the live GCP REST API JSON payload using the Discovery Documents." +--- + +# `verify-api-schema` + +> **Note to AI Agents:** You MUST read the YAML frontmatter above first. Only read the rest of this file if the `description` matches your current roadblock or required task. + +## Prerequisites +* You must be in the `magic-modules` root directory. +* You must have `curl` and `jq` installed. + +## Execution Steps + +### 1. Verification +Provide the exact bash commands the agent should run to verify the prerequisites. + +#### Verify jq installation +```bash +jq --version +``` + +### 2. The Core Commands +Query the live GCP Discovery Documents directly. This is the ultimate source of truth for exact JSON payload names (including weird edge cases like double-plurals or typos in the API). + +#### Query exact schema in v1 or beta +```bash +# For v1 Compute API schema +curl -s https://www.googleapis.com/discovery/v1/apis/compute/v1/rest | jq '.schemas.SecurityPolicyRule' + +# For beta Compute API schema +curl -s https://www.googleapis.com/discovery/v1/apis/compute/beta/rest | jq '.schemas.SecurityPolicyRule' +``` + +Replace `SecurityPolicyRule` with the specific schema name you are tracking (e.g., `UrlMap`, `BackendService`). + +### 3. Verification & Handoff +Instructions on how the agent should verify the command succeeded, and what workflow or rule it should return to next. + +* Compare the JSON payload attributes (types, names, pluralization) with the Magic Modules YAML properties. +* If you find a discrepancy (e.g., `exclusions` in JSON vs `exclusion` in YAML), verify if `api_name` is being used to bridge the gap. diff --git a/.agents/skills/workflows/default/SKILL.md b/.agents/skills/workflows/default/SKILL.md new file mode 100644 index 000000000000..3aeff1256696 --- /dev/null +++ b/.agents/skills/workflows/default/SKILL.md @@ -0,0 +1,35 @@ +--- +name: default-workflow +description: "Fallback workflow for general implementation and debugging tasks that do not involve creating a new resource." +--- + +# `default-workflow` + +This document outlines the structured 5-step lifecycle for formal implementation and debugging tasks in Magic Modules. + +## Execution Steps + +### 1. Repo Sync +* Execute the `repo-sync` skill (located in `.agents/skills/operations/repo-sync/`). This skill handles checking the sync status and prompting for action if needed. + +### 2. Triage +* Gather context on the change or bug. Plan the change (New feature or bug fix) within schema or logic. +* Execute the `triage` skill (located in `.agents/skills/operations/triage/`) to perform this work. +* **Transfers to Step 3:** Approved implementation plan and file paths file. + +### 3. Generate +* Once the first pass at the change is made, execute the code generation using the `generate-provider` skill (located in `.agents/skills/operations/generate-provider/`) to compile machine code in the downstream. +* **Transfers to Step 4:** Compiled provider binary. + +### 4. Test and Debug +* Invoke the specialized `qa-test-runner` subagent using the `invoke_subagent` tool to reproduce failures and interpret logs. The subagent evaluates if the test fails/passes and returns a human-readable interpretation of the results. +* **Transfers to Step 5:** Human-readable Markdown report explaining whether the test succeeded or failed, and what discrepancy was found. + +### 5. Fix +* This is a Remediation Planning step (similar to Triage). Take the results from `qa-test-runner` and compare against reference guides or user suggestions. Propose a specific fix code change to the user. +* Execute the `fix` skill (located in `.agents/skills/operations/fix/`) to perform this planning. + +--- + +## The Loop +Repeat steps 2-5 as needed during the session until the primary task is complete. Reset to Step 3 (Generate) after applying an approved fix to compile it! diff --git a/.agents/skills/workflows/new_resource/SKILL.md b/.agents/skills/workflows/new_resource/SKILL.md new file mode 100644 index 000000000000..a0133fc9643b --- /dev/null +++ b/.agents/skills/workflows/new_resource/SKILL.md @@ -0,0 +1,35 @@ +--- +name: new-resource-workflow +description: "Workflow specifically for creating a new resource, supporting both autogen and manual generation." +--- + +# `new-resource-workflow` + +This document guides the agent through the task of creating a new Terraform resource in Magic Modules. + +## Generation Options + +There are two ways to generate the initial YAML definition for the resource: +1. **Autogen Subagent (Default):** Use this method if an OpenAPI specification is available for the resource. +2. **Manual Generation:** Create the YAML definition directly if no spec is available or if it requires custom crafting. + +--- + +## Execution Steps + +### 1. Prompt for OpenAPI Specification (Default Path) +* Ask the user to provide the OpenAPI specification file (or its path) for the new resource. +* **Note:** If no OpenAPI specification is available, state that you will fall back to the **Manual Path (Step 2B)** to draft the YAML directly, and ask for the user's confirmation to proceed. +* If the user provides the spec, proceed to **Step 2A (Autogen Path)**. + +### 2A. Autogen Path +* **Action:** Invoke the `autogen` subagent to handle the generation and initial testing. +* **Prompt:** "Use the OpenAPI spec to generate the new resource. Run tests and report back." +* Wait for the subagent to return its report. +* **Handoff:** + - If the subagent reports that tests passed successfully, present the results to the user. + - If the subagent reports test failures, enter the **Default Workflow** ([.agents/skills/workflows/default/SKILL.md](file:///Users/camthornton/magic-modules/.agents/skills/workflows/default/SKILL.md)) at **Step 5 (Fix)** to plan remediation. + +### 2B. Manual Path +* Follow the standard process to draft the YAML definition in `mmv1/products/...` based on API documentation and repository patterns. +* **Handoff:** Once the YAML is drafted, enter the **Default Workflow** ([.agents/skills/workflows/default/SKILL.md](file:///Users/camthornton/magic-modules/.agents/skills/workflows/default/SKILL.md)) at **Step 3 (Generate)** to compile the provider and continue with testing. diff --git a/.ci/gcb-pr-downstream-generation-and-test.yml b/.ci/gcb-pr-downstream-generation-and-test.yml index f888a22b65da..26d6813495bb 100644 --- a/.ci/gcb-pr-downstream-generation-and-test.yml +++ b/.ci/gcb-pr-downstream-generation-and-test.yml @@ -264,7 +264,7 @@ steps: - $COMMIT_SHA - $BUILD_ID - $PROJECT_ID - - "23" # Build step + - "22" # Build step - "true" - name: 'gcr.io/graphite-docker-images/go-plus' diff --git a/.ci/gcb-test-failure-ticket.yaml b/.ci/gcb-test-failure-ticket.yaml index 8f72ab7d06be..39c9e4aca4d4 100644 --- a/.ci/gcb-test-failure-ticket.yaml +++ b/.ci/gcb-test-failure-ticket.yaml @@ -3,7 +3,7 @@ steps: - name: 'gcr.io/graphite-docker-images/go-plus' id: create-test-failure-ticket entrypoint: '/workspace/.ci/scripts/go-plus/magician/exec.sh' - secretEnv: ["GITHUB_TOKEN"] + secretEnv: ["GITHUB_TOKEN", "SPREADSHEET_ID", "GCB_TICKET_CREATION_SERVICE_ACCOUNT"] args: - 'create-test-failure-ticket' - name: 'gcr.io/graphite-docker-images/go-plus' @@ -22,4 +22,9 @@ logsBucket: 'gs://cloudbuild-test-failure-ticket-logs' availableSecrets: secretManager: - versionName: projects/673497134629/secrets/github-classic--repo-workflow/versions/latest - env: GITHUB_TOKEN \ No newline at end of file + env: GITHUB_TOKEN + - versionName: projects/673497134629/secrets/release-shepherd-spreadsheet-id/versions/latest + env: SPREADSHEET_ID + - versionName: projects/673497134629/secrets/gcb-ticket-creation-service-account/versions/latest + env: GCB_TICKET_CREATION_SERVICE_ACCOUNT + \ No newline at end of file diff --git a/.ci/magician/cmd/create_test_failure_ticket.go b/.ci/magician/cmd/create_test_failure_ticket.go index 1accc5f955dd..72ba5a21cad5 100644 --- a/.ci/magician/cmd/create_test_failure_ticket.go +++ b/.ci/magician/cmd/create_test_failure_ticket.go @@ -33,6 +33,10 @@ import ( "github.com/GoogleCloudPlatform/magic-modules/tools/issue-labeler/labeler" _ "embed" + + "google.golang.org/api/impersonate" + "google.golang.org/api/option" + "google.golang.org/api/sheets/v4" ) var ( @@ -48,6 +52,8 @@ const ( var ctftRequiredEnvironmentVariables = [...]string{ "GITHUB_TOKEN", + "SPREADSHEET_ID", + "GCB_TICKET_CREATION_SERVICE_ACCOUNT", } type testFailureRateLabel int64 @@ -130,7 +136,12 @@ var createTestFailureTicketCmd = &cobra.Command{ } date := now.In(loc) - return execCreateTestFailureTicket(date, gh, gcs) + shepherd, err := getReleaseShepherd(context.Background(), env["SPREADSHEET_ID"], env["GCB_TICKET_CREATION_SERVICE_ACCOUNT"], date) + if err != nil { + return fmt.Errorf("failed to get release shepherd: %w", err) + } + + return execCreateTestFailureTicket(date, gh, gcs, shepherd) }, } @@ -142,7 +153,7 @@ func listCTFTRequiredEnvironmentVariables() string { return result } -func execCreateTestFailureTicket(now time.Time, gh *github.Client, gcs CloudstorageClient) error { +func execCreateTestFailureTicket(now time.Time, gh *github.Client, gcs CloudstorageClient, shepherd string) error { ctx := context.Background() gaTestFailuresMap := make(map[string][]bool) @@ -182,7 +193,7 @@ func execCreateTestFailureTicket(now time.Time, gh *github.Client, gcs Cloudstor // Create tickets for _, testFailure := range testFailuresToday { if shouldCreateTicket(testFailure, existTestNames, closedTestNames) { - err := createTicket(ctx, gh, testFailure) + err := createTicket(ctx, gh, testFailure, shepherd) if err != nil { return fmt.Errorf("error creating test failure ticket: %w", err) } @@ -425,7 +436,8 @@ func ListIssuesWithOpts(ctx context.Context, gh *github.Client, opts *github.Iss return allIssues, nil } -func computeTicketLabels(testFailure *testFailure) ([]string, error) { +// computeTicketRouting determines labels and whether to assign the ticket to the shepherd. +func computeTicketRouting(testFailure *testFailure) ([]string, bool, error) { failureRatelabel := testFailure.FailureRateLabels[provider.GA].String() if testFailure.FailureRateLabels[provider.Beta] > testFailure.FailureRateLabels[provider.GA] { @@ -443,34 +455,38 @@ func computeTicketLabels(testFailure *testFailure) ([]string, error) { labels = append(labels, "crash") } + shouldAssign := false + if IsTerraformTeamOwned(testFailure) { - // Apply terraform team label for team owned ticket + // Team-owned failures go to terraform team and shepherd. labels = append(labels, "service/terraform") + shouldAssign = true } else { // Apply service labels to forward test failure ticket automatically regexpLabels, err := labeler.BuildRegexLabels(labeler.EnrolledTeamsYaml) if err != nil { - return nil, fmt.Errorf("error building regex labels: %w", err) + return nil, false, fmt.Errorf("error building regex labels: %w", err) } labels = append(labels, labeler.ComputeLabels([]string{testFailure.AffectedResource}, regexpLabels)...) - // Apply terraform team label if no service labels applied + // Fallback to terraform team and shepherd if no service label found. Also apply review label. if len(labels) == 0 { - labels = append(labels, "service/terraform") + labels = append(labels, "service/terraform", "test/review") + shouldAssign = true } } ticketLabels = append(ticketLabels, labels...) - return ticketLabels, nil + return ticketLabels, shouldAssign, nil } -func createTicket(ctx context.Context, gh *github.Client, testFailure *testFailure) error { +func createTicket(ctx context.Context, gh *github.Client, testFailure *testFailure, shepherd string) error { issueTitle := fmt.Sprintf("Failing test(s): %s", testFailure.TestName) issueBody, err := formatIssueBody(*testFailure) if err != nil { return fmt.Errorf("error formatting issue body: %w", err) } - ticketLabels, err := computeTicketLabels(testFailure) + ticketLabels, shouldAssign, err := computeTicketRouting(testFailure) if err != nil { return fmt.Errorf("error getting ticket labels: %w", err) } @@ -484,6 +500,11 @@ func createTicket(ctx context.Context, gh *github.Client, testFailure *testFailu Milestone: github.Int(11), } + // Only assign to shepherd if it's a terraform team owned ticket or for test/review tickets + if shouldAssign && shepherd != "" { + issueRquest.Assignee = github.String(shepherd) + } + _, _, err = gh.Issues.Create(ctx, GithubOwner, GithubRepo, issueRquest) if err != nil { return fmt.Errorf("error creating issue: %w", err) @@ -568,6 +589,108 @@ func storeErrorMessage(pVersion provider.Version, gcs CloudstorageClient, errorM return link, nil } +// parseDate parses a date string in supported formats. +func parseDate(s string) (time.Time, error) { + if t, err := time.Parse("2006-01-02", s); err == nil { + return t, nil + } + if t, err := time.Parse("1/2/2006", s); err == nil { + return t, nil + } + return time.Time{}, fmt.Errorf("could not parse date %s", s) +} + +// getReleaseShepherd retrieves the current release shepherd's GitHub username from a Google Sheet. +func getReleaseShepherd(ctx context.Context, spreadsheetId string, sa string, now time.Time) (string, error) { + ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ + TargetPrincipal: sa, + Scopes: []string{sheets.SpreadsheetsReadonlyScope}, + }) + if err != nil { + return "", fmt.Errorf("failed to create impersonated token source: %w", err) + } + // Initialize the Sheets service using the impersonated token source + srv, err := sheets.NewService(ctx, option.WithTokenSource(ts)) + if err != nil { + return "", fmt.Errorf("unable to retrieve Sheets client: %w", err) + } + + schedResp, err := srv.Spreadsheets.Values.Get(spreadsheetId, "Rotation Schedule!A:C").Do() + if err != nil { + return "", fmt.Errorf("unable to retrieve schedule: %w", err) + } + + if len(schedResp.Values) == 0 { + return "", fmt.Errorf("no schedule data found") + } + + // Look ahead to next week's rotation if it's the weekend. + if day := now.Weekday(); day == time.Friday { + now = now.AddDate(0, 0, 3) + } else if day == time.Saturday { + now = now.AddDate(0, 0, 2) + } else if day == time.Sunday { + now = now.AddDate(0, 0, 1) + } + + var currentEmail string + + // Find the latest date in the schedule that is before or equal to now. + for i := 1; i < len(schedResp.Values); i++ { + row := schedResp.Values[i] + if len(row) < 3 { + continue + } + + dateStr := fmt.Sprintf("%v", row[0]) + email := fmt.Sprintf("%v", row[2]) + + rowDate, err := parseDate(dateStr) + if err != nil { + fmt.Printf("Warning: unparsable date at row %d: %v\n", i+1, err) + continue + } + + if rowDate.Before(now) || rowDate.Equal(now) { + currentEmail = email + } else { + break + } + } + + if currentEmail == "" { + return "", fmt.Errorf("could not determine current rotation person") + } + + partResp, err := srv.Spreadsheets.Values.Get(spreadsheetId, "Rotation Participants!A:C").Do() + if err != nil { + return "", fmt.Errorf("unable to retrieve participants data: %w", err) + } + + var githubUsername string + // Look up GitHub username for the determined email. + for i := 1; i < len(partResp.Values); i++ { + row := partResp.Values[i] + if len(row) < 3 { + continue + } + + username := fmt.Sprintf("%v", row[1]) + email := fmt.Sprintf("%v", row[2]) + + if email == currentEmail { + githubUsername = username + break + } + } + + if githubUsername == "" { + return "", fmt.Errorf("could not find GitHub username for email %s", currentEmail) + } + + return githubUsername, nil +} + func init() { rootCmd.AddCommand(createTestFailureTicketCmd) } diff --git a/.ci/magician/cmd/create_test_failure_ticket_test.go b/.ci/magician/cmd/create_test_failure_ticket_test.go index 2fcb78b5965b..1f008b4f316c 100644 --- a/.ci/magician/cmd/create_test_failure_ticket_test.go +++ b/.ci/magician/cmd/create_test_failure_ticket_test.go @@ -233,10 +233,11 @@ func TestShouldCreateTicket(t *testing.T) { } } -func TestGetTicketLabels(t *testing.T) { +func TestComputeTicketRouting(t *testing.T) { cases := map[string]struct { - tf testFailure - expectLabels []string + tf testFailure + expectLabels []string + expectAssignee bool }{ "Team owned error": { tf: testFailure{ @@ -247,7 +248,8 @@ func TestGetTicketLabels(t *testing.T) { provider.GA: testFailure10, }, }, - expectLabels: []string{"size/xs", "test-failure", "test-failure-10", "service/terraform"}, + expectLabels: []string{"size/xs", "test-failure", "test-failure-10", "service/terraform"}, + expectAssignee: true, }, "Crash error": { tf: testFailure{ @@ -258,7 +260,8 @@ func TestGetTicketLabels(t *testing.T) { provider.GA: testFailure100, }, }, - expectLabels: []string{"size/xs", "test-failure", "test-failure-100", "service/compute-instances", "crash"}, + expectLabels: []string{"size/xs", "test-failure", "test-failure-100", "service/compute-instances", "crash"}, + expectAssignee: false, }, "Non-Team owned - has service label": { tf: testFailure{ @@ -269,7 +272,8 @@ func TestGetTicketLabels(t *testing.T) { provider.GA: testFailure50, }, }, - expectLabels: []string{"size/xs", "test-failure", "test-failure-50", "service/compute-instances"}, + expectLabels: []string{"size/xs", "test-failure", "test-failure-50", "service/compute-instances"}, + expectAssignee: false, }, "Non-Team owned - fallback label": { tf: testFailure{ @@ -280,15 +284,16 @@ func TestGetTicketLabels(t *testing.T) { provider.GA: testFailure100, }, }, - expectLabels: []string{"size/xs", "test-failure", "test-failure-100", "service/terraform"}, + expectLabels: []string{"size/xs", "test-failure", "test-failure-100", "service/terraform", "test/review"}, + expectAssignee: true, }, } - for tn, tc := range cases { t.Run(tn, func(t *testing.T) { - labels, err := computeTicketLabels(&tc.tf) + labels, shouldAssign, err := computeTicketRouting(&tc.tf) assert.NoError(t, err) assert.ElementsMatch(t, tc.expectLabels, labels) + assert.Equal(t, tc.expectAssignee, shouldAssign) }) } } diff --git a/.ci/magician/cmd/manage_test_failure_ticket.go b/.ci/magician/cmd/manage_test_failure_ticket.go index 9b8dfebcf04d..c46ca5010490 100644 --- a/.ci/magician/cmd/manage_test_failure_ticket.go +++ b/.ci/magician/cmd/manage_test_failure_ticket.go @@ -42,7 +42,7 @@ var manageTestFailureTicketCmd = &cobra.Command{ It performs the following operations: 1. Lists out GitHub issues with test-failure and forward/review labels. 2. Removes forward/review labels from these issues. - 3. Closes 100% test ticket if it starts to pass for 3 days + 3. Closes 100% test tickets if they pass for 3 days, and 50% test tickets if they pass for 14 days. The following environment variables are required: ` + listMTFTRequiredEnvironmentVariables(), @@ -102,20 +102,39 @@ func execManageTestFailureTicket(now time.Time, gh *github.Client, gcs Cloudstor } } - // Get Test status for past 3 days + // Get Test status for past 14 days gaTestFailuresMap := make(map[string][]bool) betaTestFailuresMap := make(map[string][]bool) - lastNDaysTestNonSuccessMap(provider.GA, 3, now, gcs, gaTestFailuresMap) - lastNDaysTestNonSuccessMap(provider.Beta, 3, now, gcs, betaTestFailuresMap) + err = lastNDaysTestNonSuccessMap(provider.GA, 14, now, gcs, gaTestFailuresMap) + if err != nil { + return err + } + err = lastNDaysTestNonSuccessMap(provider.Beta, 14, now, gcs, betaTestFailuresMap) + if err != nil { + return err + } + + err = closeResolvedTickets(ctx, gh, "test-failure-100", 3, gaTestFailuresMap, betaTestFailuresMap) + if err != nil { + return err + } - // Get 100% failing test tickets - opts = &github.IssueListByRepoOptions{ + err = closeResolvedTickets(ctx, gh, "test-failure-50", 14, gaTestFailuresMap, betaTestFailuresMap) + if err != nil { + return err + } + + return nil +} + +func closeResolvedTickets(ctx context.Context, gh *github.Client, label string, daysToCheck int, gaTestFailuresMap, betaTestFailuresMap map[string][]bool) error { + opts := &github.IssueListByRepoOptions{ State: "open", - Labels: []string{"test-failure-100"}, + Labels: []string{label}, ListOptions: github.ListOptions{PerPage: 100}, } - issues, err = ListIssuesWithOpts(ctx, gh, opts) + issues, err := ListIssuesWithOpts(ctx, gh, opts) if err != nil { return err } @@ -133,12 +152,12 @@ func execManageTestFailureTicket(now time.Time, gh *github.Client, gcs Cloudstor continue } - if shouldCloseTestTicket(tests, gaTestFailuresMap, betaTestFailuresMap) { + if shouldCloseTestTicket(tests, gaTestFailuresMap, betaTestFailuresMap, daysToCheck) { shouldCloseTickets = append(shouldCloseTickets, issue.GetNumber()) } } - comment := "All failing tests listed in this ticket have passed in the last three consecutive nightly runs. Closing the ticket." + comment := fmt.Sprintf("All failing tests listed in this ticket have passed in the last %d consecutive nightly runs. Closing the ticket.", daysToCheck) for _, ticketNumber := range shouldCloseTickets { fmt.Println("Closing ticket ", ticketNumber) issueComment := &github.IssueComment{ @@ -178,7 +197,7 @@ func lastNDaysTestNonSuccessMap(pVersion provider.Version, n int, now time.Time, return nil } -func shouldCloseTestTicket(tests []string, gaTestFailuresMap, betaTestFailuresMap map[string][]bool) bool { +func shouldCloseTestTicket(tests []string, gaTestFailuresMap, betaTestFailuresMap map[string][]bool, daysToCheck int) bool { for _, test := range tests { gaFailures, foundGaTest := gaTestFailuresMap[test] betaFailures, foundBetaTest := betaTestFailuresMap[test] @@ -189,15 +208,15 @@ func shouldCloseTestTicket(tests []string, gaTestFailuresMap, betaTestFailuresMa } if foundGaTest { - for _, fail := range gaFailures { - if fail { + for i := 0; i < daysToCheck; i++ { + if gaFailures[i] { return false } } } if foundBetaTest { - for _, fail := range betaFailures { - if fail { + for i := 0; i < daysToCheck; i++ { + if betaFailures[i] { return false } } diff --git a/.ci/magician/cmd/templates/vcr/post_replay.tmpl b/.ci/magician/cmd/templates/vcr/post_replay.tmpl index 141f93269c2d..8b09c0081b62 100644 --- a/.ci/magician/cmd/templates/vcr/post_replay.tmpl +++ b/.ci/magician/cmd/templates/vcr/post_replay.tmpl @@ -47,11 +47,18 @@ {{ if gt (len .ReplayingResult.FailedTests) 0 }} #### Action taken + +Found {{len .ReplayingResult.FailedTests}} affected test(s) by replaying old test recordings. Starting RECORDING based on the most recent commit. + +{{ if gt (len .ReplayingResult.FailedTests) 100 -}} +More than 100 tests failed in replaying; this is too many to display on GitHub. View the [Cloud Build logs]({{$.BuildStepUrl}}) to see the full list. +{{- else -}}
-Found {{len .ReplayingResult.FailedTests}} affected test(s) by replaying old test recordings. Starting RECORDING based on the most recent commit. Click here to see the affected tests +Click here to see the affected tests {{range .ReplayingResult.FailedTests}}{{. | printf "* %s\n"}}{{end}}
+{{- end }} {{ else }} {{ if .ReplayingErr }} > [!CAUTION] @@ -70,4 +77,4 @@ {{ end }} {{ end }} -View the [build log](https://storage.cloud.google.com/{{.LogBucket}}/{{.Version}}/refs/heads/{{.Head}}/artifacts/{{.BuildID}}/build-log/replaying_test.log) +View the [replaying VCR build log](https://storage.cloud.google.com/{{.LogBucket}}/{{.Version}}/refs/heads/{{.Head}}/artifacts/{{.BuildID}}/build-log/replaying_test.log) diff --git a/.ci/magician/cmd/templates/vcr/record_replay.tmpl b/.ci/magician/cmd/templates/vcr/record_replay.tmpl index 873a2aa941c4..5826b1f7f3ce 100644 --- a/.ci/magician/cmd/templates/vcr/record_replay.tmpl +++ b/.ci/magician/cmd/templates/vcr/record_replay.tmpl @@ -2,11 +2,11 @@ **Step 2: Recording Mode** -| Recording Mode | Replaying Rerun | Test Name | -| :--- | :--- | :--- | -{{range .TestRows -}} -| {{symbol .RecordingStatus}}{{if .RecordingErrorUrl}} [Error]({{.RecordingErrorUrl}}){{end}}{{if .RecordingLogUrl}}{{if .RecordingErrorUrl}} · {{else}} {{end}}[Log]({{.RecordingLogUrl}}){{end}} | {{symbol .ReplayingAfterRecordingStatus}}{{if .ReplayingAfterRecordingErrorUrl}} [Error]({{.ReplayingAfterRecordingErrorUrl}}){{end}}{{if .ReplayingAfterRecordingLogUrl}}{{if .ReplayingAfterRecordingErrorUrl}} · {{else}} {{end}}[Log]({{.ReplayingAfterRecordingLogUrl}}){{end}} | {{.DisplayName}} | -{{end}} +{{ if gt (len .TestRows) 100 -}} +More than 100 tests ran in recording mode; this is too many to display on GitHub. View the [Cloud Build logs]({{$.BuildStepUrl}}) to see the result summary. +{{- else -}} +{{template "RecordReplayRows" .}} +{{- end}} {{ if or (gt (len .ReplayingAfterRecordingResult.FailedTests) 0) (gt (len .RecordingResult.FailedTests) 0) .HasTerminatedTests .RecordingErr (gt (len .NotRunBetaTests) 0) (gt (len .NotRunGATests) 0) }} > [!CAUTION] @@ -32,4 +32,4 @@ {{ color "green" "**All tests passed!**" }} {{ end }} -View the [build log]({{.LogBaseUrl}}/build-log/recording_test.log) or the [debug logs folder]({{.BrowseLogBaseUrl}}/recording) for detailed results. +View the [recording VCR build log]({{.LogBaseUrl}}/build-log/recording_test.log) or the [debug logs folder]({{.BrowseLogBaseUrl}}/recording) for detailed results. diff --git a/.ci/magician/cmd/templates/vcr/record_replay_rows.tmpl b/.ci/magician/cmd/templates/vcr/record_replay_rows.tmpl new file mode 100644 index 000000000000..3604990f3139 --- /dev/null +++ b/.ci/magician/cmd/templates/vcr/record_replay_rows.tmpl @@ -0,0 +1,7 @@ +{{define "RecordReplayRows" -}} +| Recording Mode | Replaying Rerun | Test Name | +| :--- | :--- | :--- | +{{range .TestRows -}} +| {{symbol .RecordingStatus}}{{if .RecordingErrorUrl}} [Error]({{.RecordingErrorUrl}}){{end}}{{if .RecordingLogUrl}}{{if .RecordingErrorUrl}} · {{else}} {{end}}[Log]({{.RecordingLogUrl}}){{end}} | {{symbol .ReplayingAfterRecordingStatus}}{{if .ReplayingAfterRecordingErrorUrl}} [Error]({{.ReplayingAfterRecordingErrorUrl}}){{end}}{{if .ReplayingAfterRecordingLogUrl}}{{if .ReplayingAfterRecordingErrorUrl}} · {{else}} {{end}}[Log]({{.ReplayingAfterRecordingLogUrl}}){{end}} | {{.DisplayName}} | +{{end}} +{{- end -}} diff --git a/.ci/magician/cmd/test_eap_vcr.go b/.ci/magician/cmd/test_eap_vcr.go index bcf850fae96f..a20375029ac3 100644 --- a/.ci/magician/cmd/test_eap_vcr.go +++ b/.ci/magician/cmd/test_eap_vcr.go @@ -276,7 +276,7 @@ func execTestEAPVCR(changeNumber, genPath, kokoroArtifactsDir string, rnr ExecRu Version: provider.Private.String(), Head: head, } - recordReplayComment, err := formatRecordReplay(recordReplayData) + recordReplayComment, err := formatRecordReplay(recordReplayData, os.Stdout) if err != nil { return fmt.Errorf("error formatting record replay comment: %w", err) } diff --git a/.ci/magician/cmd/test_terraform_vcr.go b/.ci/magician/cmd/test_terraform_vcr.go index 5454d20578c2..b5d15f7d0aff 100644 --- a/.ci/magician/cmd/test_terraform_vcr.go +++ b/.ci/magician/cmd/test_terraform_vcr.go @@ -3,6 +3,7 @@ package cmd import ( "errors" "fmt" + "io" "os" "path/filepath" "regexp" @@ -28,6 +29,8 @@ var ( postReplayTmplText string //go:embed templates/vcr/record_replay.tmpl recordReplayTmplText string + //go:embed templates/vcr/record_replay_rows.tmpl + recordReplayRowsTmplText string ) var ttvRequiredEnvironmentVariables = [...]string{ @@ -68,6 +71,7 @@ type postReplay struct { Version string Head string BuildID string + BuildStepUrl string } type VCRTestTableRow struct { @@ -91,6 +95,7 @@ type recordReplay struct { Version string Head string BuildID string + BuildStepUrl string LogBaseUrl string BrowseLogBaseUrl string NotRunBetaTests []string @@ -226,8 +231,8 @@ func execTestTerraformVCR(prNumber, mmCommitSha, buildID, projectID, buildStep, return fmt.Errorf("error fetching cassettes: %w", err) } - buildStatusTargetURL := fmt.Sprintf("https://console.cloud.google.com/cloud-build/builds;region=global/%s;step=%s?project=%s", buildID, buildStep, projectID) - if err := gh.PostBuildStatus(prNumber, "VCR-test", "pending", buildStatusTargetURL, mmCommitSha); err != nil { + buildStepUrl := fmt.Sprintf("https://console.cloud.google.com/cloud-build/builds;region=global/%s;step=%s?project=%s", buildID, buildStep, projectID) + if err := gh.PostBuildStatus(prNumber, "VCR-test", "pending", buildStepUrl, mmCommitSha); err != nil { return fmt.Errorf("error posting pending status: %w", err) } @@ -246,13 +251,13 @@ func execTestTerraformVCR(prNumber, mmCommitSha, buildID, projectID, buildStep, return fmt.Errorf("error uploading replaying logs: %w", err) } - if hasPanics, err := handlePanics(prNumber, buildID, buildStatusTargetURL, mmCommitSha, replayingResult, vcr.Replaying, gh, rnr); err != nil { + if hasPanics, err := handlePanics(prNumber, buildID, buildStepUrl, mmCommitSha, replayingResult, vcr.Replaying, gh, rnr); err != nil { return fmt.Errorf("error handling panics: %w", err) } else if hasPanics { return nil } - if hasBuildFailures, err := handleBuildFailures(prNumber, buildID, buildStatusTargetURL, mmCommitSha, replayingResult, vcr.Replaying, gh, rnr); err != nil { + if hasBuildFailures, err := handleBuildFailures(prNumber, buildID, buildStepUrl, mmCommitSha, replayingResult, vcr.Replaying, gh, rnr); err != nil { return fmt.Errorf("error handling build failures: %w", err) } else if hasBuildFailures { return nil @@ -275,9 +280,10 @@ func execTestTerraformVCR(prNumber, mmCommitSha, buildID, projectID, buildStep, Version: provider.Beta.String(), Head: newBranch, BuildID: buildID, + BuildStepUrl: buildStepUrl, } - comment, err := formatPostReplay(postReplayData) + comment, err := formatPostReplay(postReplayData, os.Stdout) if err != nil { return fmt.Errorf("error formatting post replay comment: %w", err) } @@ -318,13 +324,13 @@ func execTestTerraformVCR(prNumber, mmCommitSha, buildID, projectID, buildStep, return fmt.Errorf("error uploading recording logs: %w", err) } - if hasPanics, err := handlePanics(prNumber, buildID, buildStatusTargetURL, mmCommitSha, recordingResult, vcr.Recording, gh, rnr); err != nil { + if hasPanics, err := handlePanics(prNumber, buildID, buildStepUrl, mmCommitSha, recordingResult, vcr.Recording, gh, rnr); err != nil { return fmt.Errorf("error handling panics: %w", err) } else if hasPanics { return nil } - if hasBuildFailures, err := handleBuildFailures(prNumber, buildID, buildStatusTargetURL, mmCommitSha, recordingResult, vcr.Recording, gh, rnr); err != nil { + if hasBuildFailures, err := handleBuildFailures(prNumber, buildID, buildStepUrl, mmCommitSha, recordingResult, vcr.Recording, gh, rnr); err != nil { return fmt.Errorf("error handling build failures: %w", err) } else if hasBuildFailures { return nil @@ -382,10 +388,11 @@ func execTestTerraformVCR(prNumber, mmCommitSha, buildID, projectID, buildStep, Version: provider.Beta.String(), Head: newBranch, BuildID: buildID, + BuildStepUrl: buildStepUrl, NotRunBetaTests: notRunBeta, NotRunGATests: notRunGa, } - recordReplayComment, err := formatRecordReplay(recordReplayData) + recordReplayComment, err := formatRecordReplay(recordReplayData, os.Stdout) if err != nil { return fmt.Errorf("error formatting record replay comment: %w", err) } @@ -398,7 +405,7 @@ func execTestTerraformVCR(prNumber, mmCommitSha, buildID, projectID, buildStep, } } - if err := gh.PostBuildStatus(prNumber, "VCR-test", testState, buildStatusTargetURL, mmCommitSha); err != nil { + if err := gh.PostBuildStatus(prNumber, "VCR-test", testState, buildStepUrl, mmCommitSha); err != nil { return fmt.Errorf("error posting build status: %w", err) } return nil @@ -546,7 +553,7 @@ func runReplaying(runFullVCR bool, version provider.Version, services map[string return result, testDirs, replayingErr } -func handlePanics(prNumber, buildID, buildStatusTargetURL, mmCommitSha string, result vcr.Result, mode vcr.Mode, gh GithubClient, rnr ExecRunner) (bool, error) { +func handlePanics(prNumber, buildID, buildStepUrl, mmCommitSha string, result vcr.Result, mode vcr.Mode, gh GithubClient, rnr ExecRunner) (bool, error) { if len(result.Panics) > 0 { comment := "> [!CAUTION]\n" comment += "> **Panic occurred during VCR tests**\n>\n" @@ -571,7 +578,7 @@ func handlePanics(prNumber, buildID, buildStatusTargetURL, mmCommitSha string, r if err := appendVCRResultToDiffComment(prNumber, comment, gh, rnr); err != nil { return true, fmt.Errorf("error appending comment: %v", err) } - if err := gh.PostBuildStatus(prNumber, "VCR-test", "failure", buildStatusTargetURL, mmCommitSha); err != nil { + if err := gh.PostBuildStatus(prNumber, "VCR-test", "failure", buildStepUrl, mmCommitSha); err != nil { return true, fmt.Errorf("error posting failure status: %v", err) } return true, nil @@ -579,7 +586,7 @@ func handlePanics(prNumber, buildID, buildStatusTargetURL, mmCommitSha string, r return false, nil } -func handleBuildFailures(prNumber, buildID, buildStatusTargetURL, mmCommitSha string, result vcr.Result, mode vcr.Mode, gh GithubClient, rnr ExecRunner) (bool, error) { +func handleBuildFailures(prNumber, buildID, buildStepUrl, mmCommitSha string, result vcr.Result, mode vcr.Mode, gh GithubClient, rnr ExecRunner) (bool, error) { if len(result.BuildFailures) > 0 { comment := "> [!CAUTION]\n" comment += "> **Build Failure during VCR tests**\n>\n" @@ -607,7 +614,7 @@ func handleBuildFailures(prNumber, buildID, buildStatusTargetURL, mmCommitSha st if err := appendVCRResultToDiffComment(prNumber, comment, gh, rnr); err != nil { return true, fmt.Errorf("error appending comment: %v", err) } - if err := gh.PostBuildStatus(prNumber, "VCR-test", "failure", buildStatusTargetURL, mmCommitSha); err != nil { + if err := gh.PostBuildStatus(prNumber, "VCR-test", "failure", buildStepUrl, mmCommitSha); err != nil { return true, fmt.Errorf("error posting failure status: %v", err) } return true, nil @@ -675,7 +682,7 @@ func init() { rootCmd.AddCommand(testTerraformVCRCmd) } -func formatComment(fileName string, tmplText string, data any) (string, error) { +func parseTemplate(filename string, tmplText string) *template.Template { funcs := template.FuncMap{ "join": strings.Join, "add": func(i, j int) int { return i + j }, @@ -685,30 +692,50 @@ func formatComment(fileName string, tmplText string, data any) (string, error) { "symbol": symbol, "contains": contains, } - tmpl, err := template.New(fileName).Funcs(funcs).Parse(tmplText) + tmpl, err := template.New(filename).Funcs(funcs).Parse(tmplText) if err != nil { - panic(fmt.Sprintf("Unable to parse %s: %s", fileName, err)) + panic(fmt.Sprintf("Unable to parse %s: %s", filename, err)) } + return tmpl +} + +func formatComment(filename string, tmplText string, data any) (string, error) { + tmpl := parseTemplate(filename, tmplText) sb := new(strings.Builder) - err = tmpl.Execute(sb, data) + err := tmpl.Execute(sb, data) if err != nil { return "", err } return strings.TrimSpace(sb.String()), nil } -func formatPostReplay(data postReplay) (string, error) { +func formatPostReplay(data postReplay, w io.Writer) (string, error) { + if len(data.ReplayingResult.FailedTests) > 100 { + fmt.Fprintln(w, "Failed replaying tests:") + for _, t := range data.ReplayingResult.FailedTests { + fmt.Fprintln(w, "* "+t) + } + } return formatComment("post_replay.tmpl", postReplayTmplText, data) } -func formatRecordReplay(data recordReplay) (string, error) { +func formatRecordReplay(data recordReplay, w io.Writer) (string, error) { + if len(data.TestRows) > 100 { + tmpl := parseTemplate("record_replay_rows.tmpl", recordReplayRowsTmplText+`{{ template "RecordReplayRows" . }}`) + sb := new(strings.Builder) + err := tmpl.Execute(sb, data) + if err != nil { + return "", err + } + fmt.Fprintln(w, strings.TrimSpace(sb.String())) + } logBasePath := fmt.Sprintf("%s/%s/refs/heads/%s/artifacts/%s", data.LogBucket, data.Version, data.Head, data.BuildID) if data.BuildID == "" { logBasePath = fmt.Sprintf("%s/%s/refs/heads/%s", data.LogBucket, data.Version, data.Head) } data.LogBaseUrl = fmt.Sprintf("https://storage.cloud.google.com/%s", logBasePath) data.BrowseLogBaseUrl = fmt.Sprintf("https://console.cloud.google.com/storage/browser/%s", logBasePath) - return formatComment("record_replay.tmpl", recordReplayTmplText, data) + return formatComment("record_replay.tmpl", recordReplayRowsTmplText+recordReplayTmplText, data) } func contains(slice []string, item string) bool { diff --git a/.ci/magician/cmd/test_terraform_vcr_test.go b/.ci/magician/cmd/test_terraform_vcr_test.go index 92abd4733629..d7e6cf902840 100644 --- a/.ci/magician/cmd/test_terraform_vcr_test.go +++ b/.ci/magician/cmd/test_terraform_vcr_test.go @@ -291,7 +291,7 @@ func TestAnalyticsComment(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - got, err := formatPostReplay(tc.data) + got, err := formatPostReplay(tc.data, new(strings.Builder)) if err != nil { t.Fatalf("Failed to format comment: %v", err) } @@ -363,7 +363,7 @@ func TestNonExercisedTestsComment(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - got, err := formatPostReplay(tc.data) + got, err := formatPostReplay(tc.data, new(strings.Builder)) if err != nil { t.Fatalf("Failed to format comment: %v", err) } @@ -377,10 +377,16 @@ func TestNonExercisedTestsComment(t *testing.T) { } func TestWithReplayFailedTests(t *testing.T) { + manyFailedTests := make([]string, 101) + for i := range manyFailedTests { + manyFailedTests[i] = "TestAccAlloydbBackup_alloydbBackupFullTestNewExample" + } tests := []struct { - name string - data postReplay - wantContains []string + name string + data postReplay + wantContains []string + wantNotContains []string + wantStdoutContains []string }{ { name: "with failed tests", @@ -391,18 +397,38 @@ func TestWithReplayFailedTests(t *testing.T) { }, wantContains: []string{ "#### Action taken", + "Found 2 affected test(s) by replaying old test recordings. Starting RECORDING based on the most recent commit.", "
", - "Found 2 affected test(s) by replaying old test recordings. Starting RECORDING based on the most recent commit. Click here to see the affected tests", + "Click here to see the affected tests", "* a", "* b", "
", "[Learn how VCR tests work](https://googlecloudplatform.github.io/magic-modules/develop/test/test/)", }, }, + { + name: "Too many failed tests", + data: postReplay{ + ReplayingResult: vcr.Result{ + FailedTests: manyFailedTests, + }, + RunFullVCR: true, + }, + wantContains: []string{ + "More than 100 tests failed in replaying; this is too many to display on GitHub.", + }, + wantNotContains: []string{manyFailedTests[0]}, + wantStdoutContains: []string{ + "Failed replaying tests", + manyFailedTests[0], + }, + }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - got, err := formatPostReplay(tc.data) + sb := new(strings.Builder) + got, err := formatPostReplay(tc.data, sb) + gotStdout := sb.String() if err != nil { t.Fatalf("Failed to format comment: %v", err) } @@ -411,6 +437,12 @@ func TestWithReplayFailedTests(t *testing.T) { t.Errorf("formatPostReplay() returned %q, which does not contain %q", got, wc) } } + for _, s := range tc.wantNotContains { + assert.NotContains(t, got, s) + } + for _, s := range tc.wantStdoutContains { + assert.Contains(t, gotStdout, s) + } }) } } @@ -433,7 +465,7 @@ func TestWithoutReplayFailedTests(t *testing.T) { wantContains: []string{ "> [!CAUTION]", "🔴 Errors occurred during REPLAYING mode. Please check the build log for details.", - "View the [build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/replaying_test.log)", + "View the [replaying VCR build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/replaying_test.log)", }, }, { @@ -446,13 +478,13 @@ func TestWithoutReplayFailedTests(t *testing.T) { }, wantContains: []string{ "🟢 **All tests passed in Replaying mode! No Recording was needed.**", - "View the [build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/replaying_test.log)", + "View the [replaying VCR build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/replaying_test.log)", }, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - got, err := formatPostReplay(tc.data) + got, err := formatPostReplay(tc.data, new(strings.Builder)) if err != nil { t.Fatalf("Failed to format comment: %v", err) } @@ -466,10 +498,21 @@ func TestWithoutReplayFailedTests(t *testing.T) { } func TestRecordReplay(t *testing.T) { + manyRows := make([]VCRTestTableRow, 101) + for i := range manyRows { + manyRows[i] = VCRTestTableRow{ + DisplayName: "TestAcc_a", + RecordingStatus: "Passed", + RecordingLogUrl: "https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording/a.log", + ReplayingAfterRecordingStatus: "Passed", + } + } tests := []struct { - name string - data recordReplay - wantContains []string + name string + data recordReplay + wantContains []string + wantNotContains []string + wantStdoutContains []string }{ { name: "ReplayingAfterRecordingResult has failed tests", @@ -528,7 +571,7 @@ func TestRecordReplay(t *testing.T) { "| ❌ [Error](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/recording_build/e_recording_test.log) · [Log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording/e.log) | - | TestAcc_e |", "Please address these issues to complete your PR", - "View the [build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/recording_test.log) or the [debug logs folder](https://console.cloud.google.com/storage/browser/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording) for detailed results.", + "View the [recording VCR build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/recording_test.log) or the [debug logs folder](https://console.cloud.google.com/storage/browser/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording) for detailed results.", }, }, { @@ -566,18 +609,47 @@ func TestRecordReplay(t *testing.T) { "| ✅ [Log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording/b.log) | ✅ | TestAcc_b |", "| ✅ [Log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording/c.log) | ✅ | TestAcc_c |", "🟢 **All tests passed!**", - "View the [build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/recording_test.log) or the [debug logs folder](https://console.cloud.google.com/storage/browser/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording) for detailed results.", + "View the [recording VCR build log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/build-log/recording_test.log) or the [debug logs folder](https://console.cloud.google.com/storage/browser/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording) for detailed results.", + }, + }, + { + name: "Too many rows", + data: recordReplay{ + TestRows: manyRows, + AllRecordingPassed: true, + BuildID: "build-123", + Head: "auto-pr-123", + Version: provider.Beta.String(), + LogBucket: "ci-vcr-logs", + }, + wantContains: []string{ + "More than 100 tests ran in recording mode; this is too many to display on GitHub.", + }, + wantNotContains: []string{ + manyRows[0].DisplayName, + }, + wantStdoutContains: []string{ + "| Recording Mode | Replaying Rerun | Test Name |", + "| ✅ [Log](https://storage.cloud.google.com/ci-vcr-logs/beta/refs/heads/auto-pr-123/artifacts/build-123/recording/a.log) | ✅ | TestAcc_a |", }, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - got, err := formatRecordReplay(tc.data) + sb := new(strings.Builder) + got, err := formatRecordReplay(tc.data, sb) + gotStdout := sb.String() if err != nil { t.Fatalf("Failed to format comment: %v", err) } - for _, wc := range tc.wantContains { - assert.Contains(t, got, wc) + for _, s := range tc.wantContains { + assert.Contains(t, got, s) + } + for _, s := range tc.wantNotContains { + assert.NotContains(t, got, s) + } + for _, s := range tc.wantStdoutContains { + assert.Contains(t, gotStdout, s) } }) } diff --git a/.ci/magician/cmd/vcr_cassette_update.go b/.ci/magician/cmd/vcr_cassette_update.go index 44c15f2f1caf..60b399656c4f 100644 --- a/.ci/magician/cmd/vcr_cassette_update.go +++ b/.ci/magician/cmd/vcr_cassette_update.go @@ -177,9 +177,10 @@ func execVCRCassetteUpdate(buildID, today string, rnr ExecRunner, ctlr *source.C fmt.Println("running tests in RECORDING mode now") recordingResult, recordingErr := vt.RunParallel(vcr.RunOptions{ - Mode: vcr.Recording, - Version: provider.Beta, - Tests: replayingResult.FailedTests, + Mode: vcr.Recording, + Version: provider.Beta, + Tests: replayingResult.FailedTests, + UploadBranchName: "main", }) // upload build and test logs first to preserve debugging logs in case diff --git a/.ci/magician/github/membership_data.go b/.ci/magician/github/membership_data.go index b2514e06854d..b94267234544 100644 --- a/.ci/magician/github/membership_data.go +++ b/.ci/magician/github/membership_data.go @@ -82,7 +82,12 @@ var ( }, }, "hao-nan-li": { - vacations: []Vacation{}, + vacations: []Vacation{ + { + startDate: newDate(2026, 5, 15), + endDate: newDate(2026, 5, 26), + }, + }, }, "malhotrasagar2212": { vacations: []Vacation{}, @@ -125,6 +130,10 @@ var ( startDate: newDate(2026, 04, 14), endDate: newDate(2026, 04, 19), }, + { + startDate: newDate(2026, 05, 14), + endDate: newDate(2026, 05, 25), + }, }, }, "roaks3": { @@ -146,8 +155,8 @@ var ( "shuyama1": { vacations: []Vacation{ { - startDate: newDate(2026, 01, 29), - endDate: newDate(2026, 02, 04), + startDate: newDate(2026, 05, 22), + endDate: newDate(2026, 06, 01), }, }, }, diff --git a/.ci/magician/vcr/tester.go b/.ci/magician/vcr/tester.go index 18ba541fd665..8d9b218e48d7 100644 --- a/.ci/magician/vcr/tester.go +++ b/.ci/magician/vcr/tester.go @@ -620,8 +620,15 @@ func (vt *Tester) asyncUploadCassettes(version provider.Version, branch string, } } +func (vt *Tester) asyncCassetteUploadPath(head string, version provider.Version) string { + if head == "main" { + return fmt.Sprintf("gs://%s/%s/fixtures/", vt.cassetteBucket, version) + } + return fmt.Sprintf("gs://%s/%s/refs/heads/%s/fixtures/", vt.cassetteBucket, version, head) +} + func (vt *Tester) uploadOneCassetteFile(head string, version provider.Version, fileName string) error { - uploadPath := fmt.Sprintf("gs://%s/%s/refs/heads/%s/fixtures/", vt.cassetteBucket, version, head) + uploadPath := vt.asyncCassetteUploadPath(head, version) args := []string{ "storage", "cp", diff --git a/.ci/magician/vcr/tester_test.go b/.ci/magician/vcr/tester_test.go index 9ef95ccac8f3..8c463cccdf12 100644 --- a/.ci/magician/vcr/tester_test.go +++ b/.ci/magician/vcr/tester_test.go @@ -1,6 +1,7 @@ package vcr import ( + "magician/provider" "testing" "github.com/google/go-cmp/cmp" @@ -80,3 +81,24 @@ go: downloading ... } } + +func TestAsyncCassetteUploadPath(t *testing.T) { + vt := &Tester{ + cassetteBucket: "ci-vcr-cassettes", + } + + wantNightly := "gs://ci-vcr-cassettes/beta/fixtures/" + if got := vt.asyncCassetteUploadPath("main", provider.Beta); got != wantNightly { + t.Errorf("asyncCassetteUploadPath(\"main\", Beta) = %q; want %q", got, wantNightly) + } + + wantFallback := "gs://ci-vcr-cassettes/beta/refs/heads//fixtures/" + if got := vt.asyncCassetteUploadPath("", provider.Beta); got != wantFallback { + t.Errorf("asyncCassetteUploadPath(\"\", Beta) = %q; want %q", got, wantFallback) + } + + wantPR := "gs://ci-vcr-cassettes/beta/refs/heads/auto-pr-123/fixtures/" + if got := vt.asyncCassetteUploadPath("auto-pr-123", provider.Beta); got != wantPR { + t.Errorf("asyncCassetteUploadPath(\"auto-pr-123\", Beta) = %q; want %q", got, wantPR) + } +} diff --git a/.github/workflows/teamcity-services-diff-check-weekly.yml b/.github/workflows/teamcity-services-diff-check-weekly.yml index ca586b5f522e..136ea508e0f5 100644 --- a/.github/workflows/teamcity-services-diff-check-weekly.yml +++ b/.github/workflows/teamcity-services-diff-check-weekly.yml @@ -40,9 +40,9 @@ jobs: run: | # Create lists of service packages in providers. Need to cd into repos where go.mod is to do this command. cd ${GOOGLE_REPO_PATH} - go list -f '{{.Name}}' ${GOOGLE_REPO_PATH}/google/services/... > $GITHUB_WORKSPACE/provider_services_ga.txt + go list -e -f '{{.Name}}' ${GOOGLE_REPO_PATH}/google/services/* > $GITHUB_WORKSPACE/provider_services_ga.txt cd ${GOOGLE_BETA_REPO_PATH} - go list -f '{{.Name}}' ${GOOGLE_BETA_REPO_PATH}/google-beta/services/... > $GITHUB_WORKSPACE/provider_services_beta.txt + go list -e -f '{{.Name}}' ${GOOGLE_BETA_REPO_PATH}/google-beta/services/* > $GITHUB_WORKSPACE/provider_services_beta.txt # Run tool to compare service packages in the providers vs those listed in TeamCity config files cd $GITHUB_WORKSPACE diff --git a/.github/workflows/teamcity-services-diff-check.yml b/.github/workflows/teamcity-services-diff-check.yml index 5c6af2b49f1e..40fb3390b595 100644 --- a/.github/workflows/teamcity-services-diff-check.yml +++ b/.github/workflows/teamcity-services-diff-check.yml @@ -54,9 +54,9 @@ jobs: run: | # Create lists of service packages in providers. Need to cd into repos where go.mod is to do this command. cd ${GOOGLE_REPO_PATH} - go list -f '{{.Name}}' ${GOOGLE_REPO_PATH}/google/services/... > $GITHUB_WORKSPACE/provider_services_ga.txt + go list -e -f '{{.Name}}' ${GOOGLE_REPO_PATH}/google/services/* > $GITHUB_WORKSPACE/provider_services_ga.txt cd ${GOOGLE_BETA_REPO_PATH} - go list -f '{{.Name}}' ${GOOGLE_BETA_REPO_PATH}/google-beta/services/... > $GITHUB_WORKSPACE/provider_services_beta.txt + go list -e -f '{{.Name}}' ${GOOGLE_BETA_REPO_PATH}/google-beta/services/* > $GITHUB_WORKSPACE/provider_services_beta.txt # Run tool to compare service packages in the providers vs those listed in TeamCity config files cd $GITHUB_WORKSPACE diff --git a/.gitignore b/.gitignore index 89df176e7e96..8417e4c952aa 100644 --- a/.gitignore +++ b/.gitignore @@ -68,3 +68,4 @@ MODULE.bazel.lock go.work go.work.sum terraform-provider-google/ +debug_output/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000000..f98ab5c6df89 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,5 @@ +## Workflows + +Structured workflows for specific tasks are available in `.agents/skills/workflows/` (see [.agents/WORKFLOWS.md](.agents/WORKFLOWS.md) for the menu). + +This framework is strictly **opt-in**. Unless the user explicitly asks to use **Workflow Mode** or references these instructions, ignore these files and proceed normally. For Workflow Mode, you MUST first read [.agents/WORKFLOWS.md](.agents/WORKFLOWS.md) to understand the rules and menu before proceeding. diff --git a/BUILD.bazel b/BUILD.bazel index f2871d09863f..7ad9c8ecd8d7 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -1,4 +1,4 @@ -load("@gazelle//:def.bzl", "gazelle") +load("@gazelle//:def.bzl", "gazelle", "gazelle_test") # gazelle:exclude .ci # gazelle:exclude .github @@ -12,3 +12,8 @@ load("@gazelle//:def.bzl", "gazelle") # gazelle:exclude tpgtools/serializable # gazelle:prefix github.com/GoogleCloudPlatform/magic-modules gazelle(name = "gazelle") + +gazelle_test( + name = "gazelle_test", + workspace = "//:BUILD.bazel", # a file in the workspace root, where the gazelle will be run +) diff --git a/MODULE.bazel b/MODULE.bazel index 31b21dadb26c..78a230804fae 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -3,8 +3,17 @@ bazel_dep(name = "gazelle", version = "0.47.0") bazel_dep(name = "bazel_skylib", version = "1.8.2") go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") -go_sdk.download(version = "1.24.0") +go_sdk.download(version = "1.26.0") go_deps = use_extension("@gazelle//:extensions.bzl", "go_deps") -go_deps.from_file(go_work = "//:go.work") -use_repo(go_deps, "com_github_getkin_kin_openapi", "com_github_golang_glog", "com_github_google_go_cmp", "com_github_googlecloudplatform_declarative_resource_client_library", "com_github_hashicorp_hcl", "com_github_kylelemons_godebug", "com_github_nasa9084_go_openapi", "com_github_otiai10_copy", "in_gopkg_yaml_v2", "in_gopkg_yaml_v3", "org_bitbucket_creachadair_stringset", "org_golang_x_exp") +go_deps.from_file(go_mod = "//mmv1:go.mod") + +use_repo( + go_deps, + "com_github_getkin_kin_openapi", + "com_github_golang_glog", + "com_github_google_go_cmp", + "com_github_otiai10_copy", + "in_gopkg_yaml_v3", + "org_golang_x_exp", +) diff --git a/docs/content/test/test.md b/docs/content/test/test.md index e07d7c601cac..7c7dd12c69e6 100644 --- a/docs/content/test/test.md +++ b/docs/content/test/test.md @@ -109,14 +109,14 @@ An **acceptance test** verifies that a resource can be created, updated, and des network_name: "example-network" # test_vars_overrides contains literal overrides for variables in tests. test_vars_overrides: - network_name: 'acctest.BootstrapSharedServiceNetworkingConnection(t, "pubsub-topic-network-config")' + network_name: 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "pubsub-topic-network-config")' # Subsequent steps define update configurations. - name: "pubsub_topic_full" resource_id_vars: resource_name: "example-resource" network_name: "example-network" test_vars_overrides: - network_name: 'acctest.BootstrapSharedServiceNetworkingConnection(t, "pubsub-topic-network-config")' + network_name: 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "pubsub-topic-network-config")' # vars should ONLY be used for fields that vary between steps. # Fields that stay constant across steps should be hardcoded in the .tf.tmpl file. vars: @@ -126,7 +126,7 @@ An **acceptance test** verifies that a resource can be created, updated, and des resource_name: "example-resource" network_name: "example-network" test_vars_overrides: - network_name: 'acctest.BootstrapSharedServiceNetworkingConnection(t, "pubsub-topic-network-config")' + network_name: 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "pubsub-topic-network-config")' vars: display_name: "Updated Display Name" # The new value for the updatable field ``` @@ -291,7 +291,7 @@ Tests within the legacy `examples` generator are configured directly on the reso # a shared network for your product to avoid test failures due to limits # on the default network. test_vars_overrides: - network_name: 'acctest.BootstrapSharedServiceNetworkingConnection(t, "PRODUCT-RESOURCE-network-config")' + network_name: 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "PRODUCT-RESOURCE-network-config")' # Set min_version: beta if the resource is not beta-only and any beta-only fields are being tested. min_version: beta ``` @@ -347,16 +347,20 @@ samples: resource_id_vars: kms_key_name: 'kms-key' test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKey(t).CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKey(t).CryptoKey.Name' ``` {{< /tab >}} {{< tab "Handwritten" >}} ```go +import ( + "github.com/hashicorp/terraform-provider-google/google/services/kms" +) + func TestAccProductResource_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "kms": acctest.BootstrapKMSKey(t).CryptoKey.Name, + "kms": kms.BootstrapKMSKey(t).CryptoKey.Name, // other variables } // rest of test @@ -406,13 +410,13 @@ samples: ```go // Project-level IAM import ( - "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccProductResource_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -424,14 +428,14 @@ func TestAccProductResource_update(t *testing.T) { ```go // Org-level IAM import ( - "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" - "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccProductResource_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-org-{organization_id}@gcp-sa-osconfig.iam.gserviceaccount.com", Role: "roles/osconfig.serviceAgent", @@ -471,20 +475,24 @@ samples: network_name: 'default' subnetwork_name: 'default' test_vars_overrides: - network_name: 'acctest.BootstrapSharedTestNetwork(t, "network-identifier")' - subnetwork_name: 'acctest.BootstrapSubnet(t, "subnet-identifier", acctest.BootstrapSharedTestNetwork(t, "network-identifier"))' + network_name: 'tpgcompute.BootstrapSharedTestNetwork(t, "network-identifier")' + subnetwork_name: 'tpgcompute.BootstrapSubnet(t, "subnet-identifier", tpgcompute.BootstrapSharedTestNetwork(t, "network-identifier"))' ``` {{< /tab >}} {{< tab "Handwritten" >}} ```go +import ( + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" +) + func TestAccProductResource_update(t *testing.T) { t.Parallel() networkName := subnetName := context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "network-identifier"), - "subnetwork_name": acctest.BootstrapSubnet(t, "subnet-identifier", acctest.BootstrapSharedTestNetwork(t, "network-identifier")), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "network-identifier"), + "subnetwork_name": tpgcompute.BootstrapSubnet(t, "subnet-identifier", tpgcompute.BootstrapSharedTestNetwork(t, "network-identifier")), // other variables } // rest of test @@ -502,8 +510,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" - "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" ) func TestAccProductResourceName_update(t *testing.T) { t.Parallel() diff --git a/mmv1/api/BUILD.bazel b/mmv1/api/BUILD.bazel index 2feaf2de210e..c1c6946f1850 100644 --- a/mmv1/api/BUILD.bazel +++ b/mmv1/api/BUILD.bazel @@ -7,6 +7,7 @@ go_library( "compiler.go", "product.go", "resource.go", + "runtime.go", "timeouts.go", "type.go", ], @@ -30,5 +31,9 @@ go_test( "type_test.go", ], embed = [":api"], - deps = ["//mmv1/api/product"], + deps = [ + "//mmv1/api/product", + "//mmv1/api/resource", + "@com_github_google_go_cmp//cmp", + ], ) diff --git a/mmv1/api/metadata/metadata.go b/mmv1/api/metadata/metadata.go index 98783a918367..cc0a7484f466 100644 --- a/mmv1/api/metadata/metadata.go +++ b/mmv1/api/metadata/metadata.go @@ -35,6 +35,12 @@ func FromResource(r api.Resource) Metadata { ApiField: "selfLink", }) } + if !r.DeletionPolicyExclude && !r.ExcludeDelete { + m.Fields = append(m.Fields, Field{ + Field: "deletion_policy", + ProviderOnly: true, + }) + } return m } diff --git a/mmv1/api/metadata/metadata_test.go b/mmv1/api/metadata/metadata_test.go index c2e2201a4c26..a5e7969f62b7 100644 --- a/mmv1/api/metadata/metadata_test.go +++ b/mmv1/api/metadata/metadata_test.go @@ -21,8 +21,10 @@ func TestFromResource(t *testing.T) { wantMetadata Metadata }{ { - name: "empty resource", - resource: api.Resource{}, + name: "empty resource", + resource: api.Resource{ + DeletionPolicyExclude: true, + }, wantMetadata: Metadata{ Resource: "google_product_", GenerationType: "mmv1", @@ -55,6 +57,10 @@ func TestFromResource(t *testing.T) { { ApiField: "field", }, + { + Field: "deletion_policy", + ProviderOnly: true, + }, }, }, }, @@ -87,6 +93,10 @@ func TestFromResource(t *testing.T) { { ApiField: "selfLink", }, + { + Field: "deletion_policy", + ProviderOnly: true, + }, }, }, }, diff --git a/mmv1/api/product.go b/mmv1/api/product.go index f41569bae59c..6f0b48d27278 100644 --- a/mmv1/api/product.go +++ b/mmv1/api/product.go @@ -72,6 +72,10 @@ type Product struct { ClientName string `yaml:"client_name,omitempty"` + // RepByDefault is if this product should default to REP endpoints if + // available. Changing this requires REP to be supported in *ALL* regions + RepByDefault bool `yaml:"rep_by_default,omitempty"` + // The version of the product which is currently being generated. Version *product.Version `yaml:"-"` @@ -81,9 +85,8 @@ type Product struct { // ImportPath contains the prefix used for importing packages in generated files. ImportPath string `yaml:"-"` - // RepByDefault is if this product should default to REP endpoints if - // available. Changing this requires REP to be supported in *ALL* regions - RepByDefault bool `yaml:"rep_by_default,omitempty"` + // Runtime contains information about the currently-running generation process. + Runtime Runtime `yaml:"-"` } func (p *Product) UnmarshalYAML(value *yaml.Node) error { diff --git a/mmv1/api/product/version.go b/mmv1/api/product/version.go index 200926470ce0..cb5b88e4e581 100644 --- a/mmv1/api/product/version.go +++ b/mmv1/api/product/version.go @@ -31,6 +31,11 @@ type Version struct { BaseUrl string `yaml:"base_url"` Name string RepUrl string `yaml:"rep_url,omitempty"` + + // EXPERIMENTAL: RPC settings are not fully implemented, and should not be + // used at this time. + RPCAddress string `yaml:"rpc_address,omitempty"` + RPCPackage string `yaml:"rpc_package,omitempty"` } func (v *Version) Validate(pName string) { diff --git a/mmv1/api/resource.go b/mmv1/api/resource.go index b2013f2073c7..e191a6636bcd 100644 --- a/mmv1/api/resource.go +++ b/mmv1/api/resource.go @@ -94,6 +94,11 @@ type Resource struct { // [Optional] If set to true, the resource is not able to be updated. Immutable bool `yaml:"immutable,omitempty"` + // [Optional] If set to true, bypasses the generated client-side only check during update. + // This should only be used for edge cases of an edge case where virtual field flags that can be set + // in advance of an intended change are being used to detect explicit nulls on Optional+Computed fields. + BypassClientsideUpdateCheck bool `yaml:"bypass_clientside_update_check,omitempty"` + // [Optional] If set to true, the object has a `self_link` field. This is // typical of older GCP APIs. HasSelfLink bool `yaml:"has_self_link,omitempty"` @@ -245,6 +250,8 @@ type Resource struct { // EXPERIMENTAL: If true, resource should be autogenerated as a data source Datasource *resource.Datasource `yaml:"datasource_experimental,omitempty"` + GenerateListResource bool `yaml:"generate_list_resource,omitempty"` + // If true, skip sweeper generation for this resource ExcludeSweeper bool `yaml:"exclude_sweeper,omitempty"` @@ -298,6 +305,19 @@ type Resource struct { // public ca external account keys ExcludeRead bool `yaml:"exclude_read,omitempty"` + // Set to true for resources that are excluded from universal deletion policy due to differing + // behavior on a universal option or use a different data type + DeletionPolicyExclude bool `yaml:"deletion_policy_exclude,omitempty"` + + // Set to true for resources that have deletion policy fields with custom options that are + // compatible with the universal deletion policy + // if set to true, use implement `deletion_policy` within the yaml of the resource + DeletionPolicyCustomDocs bool `yaml:"deletion_policy_custom_docs,omitempty"` + + // Set to the default deletion policy value for the resource. + // By default this will be "DELETE". + DeletionPolicyDefault string `yaml:"deletion_policy_default,omitempty"` + // Set to true for resources that wish to disable automatic generation of default provider // value customdiff functions // TODO rewrite: 1 instance used @@ -353,6 +373,14 @@ type Resource struct { // ==================== TGCResource `yaml:",inline"` + // EXPERIMENTAL: RPC settings are not fully implemented, and should not be + // used at this time. + RPCService string `yaml:"rpc_service,omitempty"` + RPCCreateMethod string `yaml:"rpc_create_method,omitempty"` + RPCReadMethod string `yaml:"rpc_read_method,omitempty"` + RPCUpdateMethod string `yaml:"rpc_update_method,omitempty"` + RPCDeleteMethod string `yaml:"rpc_delete_method,omitempty"` + CustomCode resource.CustomCode `yaml:"custom_code,omitempty"` // Examples in documentation. Backed by generated tests, and have @@ -384,6 +412,9 @@ type Resource struct { Parameters []*Type `yaml:"parameters,omitempty"` Properties []*Type + + // Runtime contains information about the currently-running generation process. + Runtime Runtime `yaml:"-"` } type TestConfig struct { @@ -492,6 +523,11 @@ func (r *Resource) setShallowDefaults() { if r.Timeouts == nil { r.Timeouts = NewTimeouts() // This only sets defaults if Timeouts is nil } + if !r.DeletionPolicyExclude { + if r.DeletionPolicyDefault == "" { + r.DeletionPolicyDefault = "DELETE" + } + } } // SetDefault sets default values for this Resource and all its properties. @@ -682,8 +718,9 @@ func (r Resource) IdentityProperties() []*Type { } } + hasField := map[string]bool{"project": r.HasProject(), "zone": r.HasZone(), "region": r.HasRegion()} for _, field := range []string{"project", "zone", "region"} { // prevents duplicates - if slices.Contains(importFormat, field) && !optionalValues[field] { + if slices.Contains(importFormat, field) && !optionalValues[field] && hasField[field] { props = append(props, &Type{Name: field, Type: "string"}) } } @@ -697,6 +734,25 @@ func (r Resource) IdentityProperties() []*Type { return props } +func (r Resource) ListScopeProperties() []*Type { + scope := r.ExtractIdentifiers(r.CollectionUrl()) + return google.Select(r.IdentityProperties(), func(p *Type) bool { + return slices.Contains(scope, google.Underscore(p.Name)) + }) +} + +func (r Resource) ListResultDisplayNameKeyStrings() []string { + var keys []string + if slices.ContainsFunc(r.RootProperties(), func(p *Type) bool { return p.Name == "display_name" }) { + keys = append(keys, "display_name") + } + markers := regexp.MustCompile(`\{\{(\w+)\}\}`).FindAllStringSubmatch(r.IdFormat, -1) + if len(markers) > 0 { + keys = append(keys, markers[len(markers)-1][1]) + } + return keys +} + func (r Resource) SensitiveProps() []*Type { props := r.AllNestedProperties(r.RootProperties()) return google.Select(props, func(p *Type) bool { @@ -2141,6 +2197,26 @@ func (r Resource) TestSampleSetUp(sysfs fs.FS) { } } +// TestServiceDependencies returns a map of service names to import aliases that are required +// by this resource's samples. +func (r Resource) TestServiceDependencies() map[string]string { + deps := map[string]string{} + for _, s := range r.TestSamples() { + for service, alias := range s.TestServiceDependencies(r.Runtime.ResourcePrefixServiceMap) { + if depsAlias, ok := deps[service]; ok && alias != depsAlias { + if (alias == "_" && depsAlias == "") || (alias == "" && depsAlias == "_") { + deps[service] = "" + continue + } + log.Fatalf("Conflicting aliases (%s vs %s) for service dependency %s for resource %s", depsAlias, alias, service, r.ApiName) + } + deps[service] = alias + } + } + delete(deps, strings.ToLower(r.ProductMetadata.Name)) + return deps +} + func (r Resource) VersionedProvider(exampleVersion string) bool { var vp string if exampleVersion != "" { @@ -2476,14 +2552,10 @@ func (r Resource) ShouldDatasourceSetAnnotations() bool { // that should be marked as "Required". func (r Resource) DatasourceRequiredFields() []string { requiredFields := []string{} - uriParts := strings.Split(r.IdFormat, "/") - for _, part := range uriParts { - if strings.HasPrefix(part, "{{") && strings.HasSuffix(part, "}}") { - field := strings.TrimSuffix(strings.TrimPrefix(part, "{{"), "}}") - if field != "region" && field != "project" && field != "zone" { - requiredFields = append(requiredFields, field) - } + for _, field := range r.ExtractIdentifiers(r.IdFormat) { + if field != "region" && field != "project" && field != "zone" { + requiredFields = append(requiredFields, field) } } return requiredFields @@ -2493,14 +2565,10 @@ func (r Resource) DatasourceRequiredFields() []string { // that should be marked as "Optional". func (r Resource) DatasourceOptionalFields() []string { optionalFields := []string{} - uriParts := strings.Split(r.IdFormat, "/") - for _, part := range uriParts { - if strings.HasPrefix(part, "{{") && strings.HasSuffix(part, "}}") { - field := strings.TrimSuffix(strings.TrimPrefix(part, "{{"), "}}") - if field == "region" || field == "project" || field == "zone" { - optionalFields = append(optionalFields, field) - } + for _, field := range r.ExtractIdentifiers(r.IdFormat) { + if field == "region" || field == "project" || field == "zone" { + optionalFields = append(optionalFields, field) } } return optionalFields diff --git a/mmv1/api/resource/BUILD.bazel b/mmv1/api/resource/BUILD.bazel index a1d03a5aba0b..2bc537ff3a4a 100644 --- a/mmv1/api/resource/BUILD.bazel +++ b/mmv1/api/resource/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_go//go:def.bzl", "go_library") +load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "resource", @@ -26,3 +26,15 @@ go_library( "@in_gopkg_yaml_v3//:yaml_v3", ], ) + +go_test( + name = "resource_test", + srcs = [ + "sample_test.go", + "step_test.go", + ], + deps = [ + ":resource", + "@com_github_google_go_cmp//cmp", + ], +) diff --git a/mmv1/api/resource/sample.go b/mmv1/api/resource/sample.go index 4578363f39a1..0edb29c8ca95 100644 --- a/mmv1/api/resource/sample.go +++ b/mmv1/api/resource/sample.go @@ -15,6 +15,7 @@ package resource import ( "fmt" + "log" "slices" "github.com/GoogleCloudPlatform/magic-modules/mmv1/api/product" @@ -109,6 +110,28 @@ func (s *Sample) TestSteps() []*Step { }) } +// TestServiceDependencies returns a map of service names to import aliases that are required +// by this sample's steps. +func (s *Sample) TestServiceDependencies(resourcePrefixServiceMap map[string]string) map[string]string { + deps := map[string]string{} + if len(s.BootstrapIam) > 0 { + deps["resourcemanager"] = "" + } + for _, step := range s.TestSteps() { + for service, alias := range step.TestServiceDependencies(resourcePrefixServiceMap) { + if depsAlias, ok := deps[service]; ok && alias != depsAlias { + if (alias == "_" && depsAlias == "") || (alias == "" && depsAlias == "_") { + deps[service] = "" + continue + } + log.Fatalf("Conflicting aliases (%s vs %s) for service dependency %s for sample %s", depsAlias, alias, service, s.Name) + } + deps[service] = alias + } + } + return deps +} + func (s *Sample) ResourceType(terraformName string) string { if s.PrimaryResourceType != "" { return s.PrimaryResourceType diff --git a/mmv1/api/resource/sample_test.go b/mmv1/api/resource/sample_test.go new file mode 100644 index 000000000000..8efcaf2f9d2d --- /dev/null +++ b/mmv1/api/resource/sample_test.go @@ -0,0 +1,125 @@ +package resource_test + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + + "github.com/GoogleCloudPlatform/magic-modules/mmv1/api/resource" +) + +func TestSample_TestServiceDependencies(t *testing.T) { + cases := []struct { + name string + sample resource.Sample + resourcePrefixServiceMap map[string]string + want map[string]string + }{ + { + name: "empty", + sample: resource.Sample{ + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{}, + TestHCLText: "", + }, + }, + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{}, + }, + { + name: "bootstrap iam", + sample: resource.Sample{ + BootstrapIam: []resource.IamMember{ + { + Member: "whatever", + Role: "role", + }, + }, + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{ + "resourcemanager": "", + }, + }, + { + name: "no conflict", + sample: resource.Sample{ + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + }, + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{ + "compute": "", + }, + }, + { + name: "underscore vs empty string conflict", + sample: resource.Sample{ + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + { + TestContextVars: map[string]string{}, + TestHCLText: `resource "google_compute_instance"`, + }, + }, + }, + resourcePrefixServiceMap: map[string]string{ + "google_compute_": "compute", + }, + want: map[string]string{ + "compute": "", + }, + }, + { + name: "merge boostrapped iam", + sample: resource.Sample{ + BootstrapIam: []resource.IamMember{ + { + Member: "whatever", + Role: "role", + }, + }, + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{}, + TestHCLText: `resource "google_project"`, + }, + }, + }, + resourcePrefixServiceMap: map[string]string{ + "google_project": "resourcemanager", + }, + want: map[string]string{ + "resourcemanager": "", + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := tc.sample.TestServiceDependencies(tc.resourcePrefixServiceMap) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("TestServiceDependencies() mismatch (-want +got:\n%s", diff) + } + }) + } +} diff --git a/mmv1/api/resource/step.go b/mmv1/api/resource/step.go index 0ea53b5791f0..cd1fb575eaca 100644 --- a/mmv1/api/resource/step.go +++ b/mmv1/api/resource/step.go @@ -29,6 +29,8 @@ import ( "github.com/golang/glog" ) +var hclResourceRegexp = regexp.MustCompile(`resource "(?Pgoogle_[^"]+)"`) + type Step struct { Name string `yaml:"name,omitempty"` @@ -122,6 +124,44 @@ func (s *Step) TestStepSlug(productName, resourceName string) string { return ret } +// TestServiceDependencies returns a map of service names to import aliases that are required +// by this step. +func (s *Step) TestServiceDependencies(resourcePrefixServiceMap map[string]string) map[string]string { + deps := map[string]string{} + for _, val := range s.TestContextVars { + if strings.HasPrefix(val, "compute.") { + deps["compute"] = "" + } + if strings.HasPrefix(val, "kms.") { + deps["kms"] = "" + } + if strings.HasPrefix(val, "servicenetworking.") { + deps["servicenetworking"] = "" + } + } + matches := hclResourceRegexp.FindAllStringSubmatch(s.TestHCLText, -1) + resources := map[string]struct{}{} + for _, m := range matches { + resources[m[1]] = struct{}{} + } + + for r, _ := range resources { + longestPrefix := "" + for prefix, _ := range resourcePrefixServiceMap { + if strings.HasPrefix(r, prefix) && len(prefix) > len(longestPrefix) { + longestPrefix = prefix + } + } + if longestPrefix != "" { + service := resourcePrefixServiceMap[longestPrefix] + if _, ok := deps[service]; !ok { + deps[service] = "_" + } + } + } + return deps +} + func (s *Step) Validate(rName, sName string) (es []error) { for k := range s.Vars { if _, exists := s.ResourceIdVars[k]; exists { diff --git a/mmv1/api/resource/step_test.go b/mmv1/api/resource/step_test.go new file mode 100644 index 000000000000..10ee96acfff2 --- /dev/null +++ b/mmv1/api/resource/step_test.go @@ -0,0 +1,142 @@ +package resource_test + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + + "github.com/GoogleCloudPlatform/magic-modules/mmv1/api/resource" +) + +func TestStep_TestServiceDependencies(t *testing.T) { + cases := []struct { + name string + step resource.Step + resourcePrefixServiceMap map[string]string + want map[string]string + }{ + { + name: "empty", + step: resource.Step{ + TestContextVars: map[string]string{}, + TestHCLText: "", + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{}, + }, + { + name: "compute bootstrapped", + step: resource.Step{ + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{ + "compute": "", + }, + }, + { + name: "kms bootstrapped", + step: resource.Step{ + TestContextVars: map[string]string{ + "kms_key": "kms.BootstrapKMSKey", + }, + TestHCLText: "", + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{ + "kms": "", + }, + }, + { + name: "servicenetworking bootstrapped", + step: resource.Step{ + TestContextVars: map[string]string{ + "network_name": "servicenetworking.BootstrapSharedServiceNetworkingConnection", + }, + TestHCLText: "", + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{ + "servicenetworking": "", + }, + }, + { + name: "hcl without prefixes", + step: resource.Step{ + TestContextVars: map[string]string{}, + TestHCLText: ` +resource "google_compute_instance" "foobar" { +} +resource "google_kms_crypto_key" "foobar" { +}`, + }, + resourcePrefixServiceMap: map[string]string{}, + want: map[string]string{}, + }, + { + name: "prefixes without hcl", + step: resource.Step{ + TestContextVars: map[string]string{}, + TestHCLText: "", + }, + resourcePrefixServiceMap: map[string]string{ + "google_compute_": "compute", + "google_kms_": "kms", + }, + want: map[string]string{}, + }, + { + name: "hcl with prefixes", + step: resource.Step{ + TestContextVars: map[string]string{}, + TestHCLText: ` +resource "google_compute_instance" "foobar" { +} +resource "google_kms_crypto_key" "foobar" { +}`, + }, + resourcePrefixServiceMap: map[string]string{ + "google_compute_": "compute", + "google_kms_": "kms", + }, + want: map[string]string{ + "compute": "_", + "kms": "_", + }, + }, + { + name: "hcl with prefixes plus bootstrapped", + step: resource.Step{ + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + "kms_key": "kms.BootstrapKMSKey", + }, + TestHCLText: ` +resource "google_compute_instance" "foobar" { +} +resource "google_kms_crypto_key" "foobar" { +}`, + }, + resourcePrefixServiceMap: map[string]string{ + "google_compute_": "compute", + "google_kms_": "kms", + }, + want: map[string]string{ + "compute": "", + "kms": "", + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := tc.step.TestServiceDependencies(tc.resourcePrefixServiceMap) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("TestServiceDependencies() mismatch (-want +got:\n%s", diff) + } + }) + } +} diff --git a/mmv1/api/resource_test.go b/mmv1/api/resource_test.go index 1523ac0359aa..f3b35c4913aa 100644 --- a/mmv1/api/resource_test.go +++ b/mmv1/api/resource_test.go @@ -1,4 +1,4 @@ -package api +package api_test import ( "os" @@ -9,12 +9,16 @@ import ( "strings" "testing" + "github.com/google/go-cmp/cmp" + + "github.com/GoogleCloudPlatform/magic-modules/mmv1/api" "github.com/GoogleCloudPlatform/magic-modules/mmv1/api/product" + "github.com/GoogleCloudPlatform/magic-modules/mmv1/api/resource" ) func TestResourceMinVersionObj(t *testing.T) { t.Parallel() - p := Product{ + p := api.Product{ Name: "test", Versions: []*product.Version{ &product.Version{ @@ -34,12 +38,12 @@ func TestResourceMinVersionObj(t *testing.T) { cases := []struct { description string - obj Resource + obj api.Resource expected string }{ { description: "resource minVersion is empty", - obj: Resource{ + obj: api.Resource{ Name: "test", MinVersion: "", ProductMetadata: &p, @@ -48,7 +52,7 @@ func TestResourceMinVersionObj(t *testing.T) { }, { description: "resource minVersion is not empty", - obj: Resource{ + obj: api.Resource{ Name: "test", MinVersion: "beta", ProductMetadata: &p, @@ -74,7 +78,7 @@ func TestResourceMinVersionObj(t *testing.T) { func TestResourceNotInVersion(t *testing.T) { t.Parallel() - p := Product{ + p := api.Product{ Name: "test", Versions: []*product.Version{ &product.Version{ @@ -94,13 +98,13 @@ func TestResourceNotInVersion(t *testing.T) { cases := []struct { description string - obj Resource + obj api.Resource input *product.Version expected bool }{ { description: "ga is in version if MinVersion is empty", - obj: Resource{ + obj: api.Resource{ Name: "test", MinVersion: "", ProductMetadata: &p, @@ -112,7 +116,7 @@ func TestResourceNotInVersion(t *testing.T) { }, { description: "ga is not in version if MinVersion is beta", - obj: Resource{ + obj: api.Resource{ Name: "test", MinVersion: "beta", ProductMetadata: &p, @@ -142,40 +146,40 @@ func TestResourceServiceVersion(t *testing.T) { cases := []struct { description string - obj Resource + obj api.Resource expected string }{ { description: "BaseUrl does not start with a version", - obj: Resource{ + obj: api.Resource{ BaseUrl: "test", }, expected: "", }, { description: "BaseUrl starts with / and does not include a version", - obj: Resource{ + obj: api.Resource{ BaseUrl: "/test", }, expected: "", }, { description: "BaseUrl starts with a version", - obj: Resource{ + obj: api.Resource{ BaseUrl: "v3/test", }, expected: "v3", }, { description: "BaseUrl starts with a / followed by version", - obj: Resource{ + obj: api.Resource{ BaseUrl: "/v3/test", }, expected: "v3", }, { description: "CaiBaseUrl does not start with a version", - obj: Resource{ + obj: api.Resource{ BaseUrl: "apis/serving.knative.dev/v1/namespaces/{{project}}/services", CaiBaseUrl: "projects/{{project}}/locations/{{location}}/services", }, @@ -183,7 +187,7 @@ func TestResourceServiceVersion(t *testing.T) { }, { description: "CaiBaseUrl starts with a version", - obj: Resource{ + obj: api.Resource{ BaseUrl: "apis/serving.knative.dev/v1/namespaces/{{project}}/services", CaiBaseUrl: "v1/projects/{{project}}/locations/{{location}}/services", }, @@ -239,34 +243,34 @@ func TestMagicianLocation(t *testing.T) { } // Check if package is under mmv1 - magicianPath := filepath.Join(dir, RELATIVE_MAGICIAN_LOCATION) + magicianPath := filepath.Join(dir, api.RELATIVE_MAGICIAN_LOCATION) relPath, err := filepath.Rel(magicianPath, pwd) if err != nil { t.Fatalf("Failed to get relative path: %v", err) } if strings.HasPrefix(relPath, "..") { - t.Errorf("Current package is not under %s. Path from magician dir to current dir: %s", RELATIVE_MAGICIAN_LOCATION, relPath) + t.Errorf("Current package is not under %s. Path from magician dir to current dir: %s", api.RELATIVE_MAGICIAN_LOCATION, relPath) } } func TestHasPostCreateComputedFields(t *testing.T) { cases := []struct { name, description string - resource Resource + resource api.Resource want bool }{ { name: "no properties", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", }, want: false, }, { name: "no computed properties", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "resource", }, @@ -276,9 +280,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "output-only property", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "field", Output: true, @@ -289,9 +293,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "output-only property in id_format", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "resource", Output: true, @@ -302,9 +306,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "output-only property in id_format with ignore_read", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "resource", Output: true, @@ -316,9 +320,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "default_from_api property", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "field", DefaultFromApi: true, @@ -329,9 +333,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "default_from_api property in id_format", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "resource", DefaultFromApi: true, @@ -342,9 +346,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "default_from_api property in id_format with ignore_read", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "resource", DefaultFromApi: true, @@ -356,9 +360,9 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "converts prop.name to snake case", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource_id}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "resourceId", Output: true, @@ -369,10 +373,10 @@ func TestHasPostCreateComputedFields(t *testing.T) { }, { name: "includes fields in self link that aren't in id format", - resource: Resource{ + resource: api.Resource{ IdFormat: "projects/{{project}}/resource/{{resource_id}}", SelfLink: "{{name}}", - Properties: []*Type{ + Properties: []*api.Type{ { Name: "name", Output: true, @@ -398,10 +402,10 @@ func TestHasPostCreateComputedFields(t *testing.T) { func TestResourceAddExtraFields(t *testing.T) { t.Parallel() - createTestResource := func(name, pn string) *Resource { - r := &Resource{ + createTestResource := func(name, pn string) *api.Resource { + r := &api.Resource{ Name: name, - ProductMetadata: &Product{ + ProductMetadata: &api.Product{ Name: "testproduct", }, } @@ -409,8 +413,8 @@ func TestResourceAddExtraFields(t *testing.T) { return r } - createTestType := func(name, typeStr string, options ...func(*Type)) *Type { - t := &Type{ + createTestType := func(name, typeStr string, options ...func(*api.Type)) *api.Type { + t := &api.Type{ Name: name, Type: typeStr, } @@ -418,24 +422,24 @@ func TestResourceAddExtraFields(t *testing.T) { option(t) } if t.ResourceMetadata == nil { - t.ResourceMetadata = &Resource{ + t.ResourceMetadata = &api.Resource{ Immutable: false, } } return t } - withWriteOnly := func(writeOnly bool) func(*Type) { - return func(t *Type) { t.WriteOnly = writeOnly } + withWriteOnly := func(writeOnly bool) func(*api.Type) { + return func(t *api.Type) { t.WriteOnly = writeOnly } } - withRequired := func(required bool) func(*Type) { - return func(t *Type) { t.Required = required } + withRequired := func(required bool) func(*api.Type) { + return func(t *api.Type) { t.Required = required } } - withDescription := func(desc string) func(*Type) { - return func(t *Type) { t.Description = desc } + withDescription := func(desc string) func(*api.Type) { + return func(t *api.Type) { t.Description = desc } } - withProperties := func(props []*Type) func(*Type) { - return func(t *Type) { t.Properties = props } + withProperties := func(props []*api.Type) func(*api.Type) { + return func(t *api.Type) { t.Properties = props } } t.Run("WriteOnly property adds companion fields", func(t *testing.T) { @@ -448,7 +452,7 @@ func TestResourceAddExtraFields(t *testing.T) { withDescription("A password field"), ) - props := []*Type{writeOnlyProp} + props := []*api.Type{writeOnlyProp} result := resource.AddExtraFields(props, nil) if len(result) != 3 { @@ -496,7 +500,7 @@ func TestResourceAddExtraFields(t *testing.T) { withDescription("A password field"), ) - props := []*Type{writeOnlyProp} + props := []*api.Type{writeOnlyProp} result := resource.AddExtraFields(props, nil) if len(result) != 1 { @@ -512,13 +516,13 @@ func TestResourceAddExtraFields(t *testing.T) { t.Parallel() resource := createTestResource("testresource", "terraform") - labelsType := &Type{ + labelsType := &api.Type{ Name: "labels", Type: "KeyValueLabels", Description: "Resource labels", } - props := []*Type{labelsType} + props := []*api.Type{labelsType} result := resource.AddExtraFields(props, nil) if len(result) != 3 { @@ -567,12 +571,12 @@ func TestResourceAddExtraFields(t *testing.T) { resource := createTestResource("testresource", "terraform") resource.ExcludeAttributionLabel = true - labelsType := &Type{ + labelsType := &api.Type{ Name: "labels", Type: "KeyValueLabels", } - props := []*Type{labelsType} + props := []*api.Type{labelsType} resource.AddExtraFields(props, nil) expectedDiff := "tpgresource.SetLabelsDiffWithoutAttributionLabel" @@ -585,14 +589,14 @@ func TestResourceAddExtraFields(t *testing.T) { t.Parallel() resource := createTestResource("testresource", "terraform") - parent := &Type{Name: "metadata"} + parent := &api.Type{Name: "metadata"} - labelsType := &Type{ + labelsType := &api.Type{ Name: "labels", Type: "KeyValueLabels", } - props := []*Type{labelsType} + props := []*api.Type{labelsType} resource.AddExtraFields(props, parent) expectedDiff := "tpgresource.SetMetadataLabelsDiff" @@ -605,13 +609,13 @@ func TestResourceAddExtraFields(t *testing.T) { t.Parallel() resource := createTestResource("testresource", "terraform") - annotationsType := &Type{ + annotationsType := &api.Type{ Name: "annotations", Type: "KeyValueAnnotations", Description: "Resource annotations", } - props := []*Type{annotationsType} + props := []*api.Type{annotationsType} result := resource.AddExtraFields(props, nil) if len(result) != 2 { @@ -648,9 +652,9 @@ func TestResourceAddExtraFields(t *testing.T) { resource := createTestResource("testresource", "terraform") nestedWriteOnly := createTestType("nestedPassword", "String", withWriteOnly(true)) - nestedObject := createTestType("config", "NestedObject", withProperties([]*Type{nestedWriteOnly})) + nestedObject := createTestType("config", "NestedObject", withProperties([]*api.Type{nestedWriteOnly})) - props := []*Type{nestedObject} + props := []*api.Type{nestedObject} result := resource.AddExtraFields(props, nil) if len(result) != 1 { @@ -670,9 +674,9 @@ func TestResourceAddExtraFields(t *testing.T) { t.Parallel() resource := createTestResource("testresource", "terraform") - emptyNestedObject := createTestType("config", "NestedObject", withProperties([]*Type{})) + emptyNestedObject := createTestType("config", "NestedObject", withProperties([]*api.Type{})) - props := []*Type{emptyNestedObject} + props := []*api.Type{emptyNestedObject} result := resource.AddExtraFields(props, nil) if len(result) != 1 { @@ -689,7 +693,7 @@ func TestResourceAddExtraFields(t *testing.T) { resource := createTestResource("testresource", "terraform") woProperty := createTestType("passwordWo", "String", withWriteOnly(true)) - props := []*Type{woProperty} + props := []*api.Type{woProperty} result := resource.AddExtraFields(props, nil) if len(result) != 1 { @@ -707,7 +711,7 @@ func TestResourceAddExtraFields(t *testing.T) { resource := createTestResource("testresource", "terraform") regularProp := createTestType("name", "String", withRequired(true)) - props := []*Type{regularProp} + props := []*api.Type{regularProp} result := resource.AddExtraFields(props, nil) if len(result) != 1 { @@ -729,9 +733,9 @@ func TestResourceAddExtraFields(t *testing.T) { regularProp := createTestType("name", "String") writeOnlyProp := createTestType("password", "String", withWriteOnly(true)) - labelsType := &Type{Name: "labels", Type: "KeyValueLabels"} + labelsType := &api.Type{Name: "labels", Type: "KeyValueLabels"} - props := []*Type{regularProp, writeOnlyProp, labelsType} + props := []*api.Type{regularProp, writeOnlyProp, labelsType} result := resource.AddExtraFields(props, nil) // Should have: name + password + passwordWo + passwordWoVersion + labels + terraformLabels + effectiveLabels = 7 @@ -752,3 +756,131 @@ func TestResourceAddExtraFields(t *testing.T) { } }) } + +func TestSample_TestServiceDependencies(t *testing.T) { + cases := []struct { + name string + resource api.Resource + want map[string]string + }{ + { + name: "empty", + resource: api.Resource{ + ProductMetadata: &api.Product{Name: "Apigee"}, + Samples: []*resource.Sample{ + { + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{}, + TestHCLText: "", + }, + }, + }, + }, + Runtime: api.Runtime{ + ResourcePrefixServiceMap: map[string]string{}, + }, + }, + want: map[string]string{}, + }, + { + name: "no conflict", + resource: api.Resource{ + ProductMetadata: &api.Product{Name: "Apigee"}, + Samples: []*resource.Sample{ + { + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + }, + }, + { + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + }, + }, + }, + Runtime: api.Runtime{ + ResourcePrefixServiceMap: map[string]string{}, + }, + }, + want: map[string]string{ + "compute": "", + }, + }, + { + name: "underscore vs empty string conflict", + resource: api.Resource{ + ProductMetadata: &api.Product{Name: "Apigee"}, + Samples: []*resource.Sample{ + { + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + }, + }, + { + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{}, + TestHCLText: `resource "google_compute_instance"`, + }, + }, + }, + }, + Runtime: api.Runtime{ + ResourcePrefixServiceMap: map[string]string{ + "google_compute_": "compute", + }, + }, + }, + want: map[string]string{ + "compute": "", + }, + }, + { + name: "remove current product", + resource: api.Resource{ + ProductMetadata: &api.Product{Name: "Compute"}, + Samples: []*resource.Sample{ + { + Steps: []*resource.Step{ + { + TestContextVars: map[string]string{ + "network": "compute.BootstrapSubnet", + }, + TestHCLText: "", + }, + }, + }, + }, + Runtime: api.Runtime{ + ResourcePrefixServiceMap: map[string]string{}, + }, + }, + want: map[string]string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := tc.resource.TestServiceDependencies() + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("TestServiceDependencies() mismatch (-want +got:\n%s", diff) + } + }) + } +} diff --git a/tpgtools/serializable/serializable_test.go b/mmv1/api/runtime.go similarity index 55% rename from tpgtools/serializable/serializable_test.go rename to mmv1/api/runtime.go index 73fa51816be7..c9a05e25fb04 100644 --- a/tpgtools/serializable/serializable_test.go +++ b/mmv1/api/runtime.go @@ -1,5 +1,4 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// +// Copyright 2026 Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -12,21 +11,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -package serializable - -import ( - "testing" -) +package api -func TestListOfResources(t *testing.T) { - services, err := ListOfResources("test_specs") - if err != nil { - t.Errorf("received error: %v", err) - } - if len(services) != 1 { - t.Errorf("expected 1 service, got: %v", len(services)) - } - if len(services[0].Resources) != 1 { - t.Errorf("expected 1 resource, got: %v", len(services[0].Resources)) - } +// Runtime holds metadata about the current generation runtime. +type Runtime struct { + // ResourcePrefixServiceMap contains entries mapping product resource prefixes (like google_compute_) to + // the service package that the resource is in. + ResourcePrefixServiceMap map[string]string } diff --git a/mmv1/cmd/BUILD.bazel b/mmv1/cmd/BUILD.bazel index 835cbc632aa4..25c060c78a5f 100644 --- a/mmv1/cmd/BUILD.bazel +++ b/mmv1/cmd/BUILD.bazel @@ -2,14 +2,13 @@ load("@rules_go//go:def.bzl", "go_binary", "go_library") go_library( name = "cmd_lib", - data = ["//mmv1/templates"], # keep srcs = ["main.go"], + data = ["//mmv1/templates"], # keep importpath = "github.com/GoogleCloudPlatform/magic-modules/mmv1/cmd", visibility = ["//visibility:private"], deps = [ "//mmv1/api", "//mmv1/provider", - "@rules_go//go/runfiles", ], ) diff --git a/mmv1/loader/BUILD.bazel b/mmv1/loader/BUILD.bazel index f91e2894b4d9..6175eba7557b 100644 --- a/mmv1/loader/BUILD.bazel +++ b/mmv1/loader/BUILD.bazel @@ -11,6 +11,8 @@ go_library( visibility = ["//visibility:public"], deps = [ "//mmv1/api", + "//mmv1/api/resource", + "//mmv1/api/utils", "//mmv1/google", "@com_github_golang_glog//:glog", "@org_golang_x_exp//slices", diff --git a/mmv1/loader/loader.go b/mmv1/loader/loader.go index 5d0f5c7914b5..df810f451a56 100644 --- a/mmv1/loader/loader.go +++ b/mmv1/loader/loader.go @@ -102,6 +102,48 @@ func (l *Loader) LoadProducts() { } l.Products = l.batchLoadProducts(allProductFiles) + + // Set up ResourcePrefixServiceMap now that all products are loaded. + runtime := api.Runtime{ + // Hardcode a few unusually-named handwritten resources. These are among the oldest resources + // in the provider; we shouldn't be adding more to this list. + ResourcePrefixServiceMap: map[string]string{ + "google_project": "resourcemanager", + "google_folder": "resourcemanager", + "google_organization": "resourcemanager", + "google_service_account": "resourcemanager", + }, + } + prefixCount := map[string]int{} + for _, p := range l.Products { + prefix := fmt.Sprintf("google_%s_", p.TerraformName()) + runtime.ResourcePrefixServiceMap[prefix] = strings.ToLower(p.ApiName) + prefixCount[prefix] += 1 + if prefixCount[prefix] > 1 { + delete(runtime.ResourcePrefixServiceMap, prefix) + } + // Always add resources with legacy_name + for _, r := range p.Objects { + if r.LegacyName != "" && !strings.HasPrefix(r.LegacyName, prefix) { + runtime.ResourcePrefixServiceMap[r.LegacyName] = strings.ToLower(p.ApiName) + } + } + } + // For products that share a prefix, add the individual resources instead. + for _, p := range l.Products { + prefix := fmt.Sprintf("google_%s_", p.TerraformName()) + if prefixCount[prefix] > 1 { + for _, r := range p.Objects { + runtime.ResourcePrefixServiceMap[r.TerraformName()] = strings.ToLower(p.ApiName) + } + } + } + for _, p := range l.Products { + p.Runtime = runtime + for _, r := range p.Objects { + r.Runtime = runtime + } + } } func (l *Loader) batchLoadProducts(productNames []string) map[string]*api.Product { @@ -347,7 +389,7 @@ func (l *Loader) loadResource(product *api.Product, baseResourcePath string, ove // Convert Examples to Samples in memory after overrides are applied if len(resource.Examples) > 0 { - + var convertedSamples []*apiresource.Sample for _, e := range resource.Examples { // Create an in-memory custom wrapper over the fs for legacy template files if e.ConfigPath == "" { @@ -383,8 +425,9 @@ func (l *Loader) loadResource(product *api.Product, baseResourcePath string, ove TGCSkipTest: e.TGCSkipTest, Steps: steps, } - resource.Samples = append(resource.Samples, sample) + convertedSamples = append(convertedSamples, sample) } + resource.Samples = append(convertedSamples, resource.Samples...) resource.Examples = nil } diff --git a/mmv1/openapi_generate/BUILD.bazel b/mmv1/openapi_generate/BUILD.bazel index 56acf74bfe97..63c9da388a5a 100644 --- a/mmv1/openapi_generate/BUILD.bazel +++ b/mmv1/openapi_generate/BUILD.bazel @@ -21,5 +21,8 @@ go_test( srcs = ["parser_test.go"], embed = [":openapi_generate"], embedsrcs = ["test_data/test_api.yaml"], - deps = ["@com_github_getkin_kin_openapi//openapi3"], + deps = [ + "//mmv1/api", + "@com_github_getkin_kin_openapi//openapi3", + ], ) diff --git a/mmv1/openapi_generate/parser.go b/mmv1/openapi_generate/parser.go index 8c9227084db3..250d79e8ed7c 100644 --- a/mmv1/openapi_generate/parser.go +++ b/mmv1/openapi_generate/parser.go @@ -416,6 +416,7 @@ func parseOpenApi(resourcePath, resourceName string, op *openapi3.Operation) []a returnArray := []any{} seenRefs := make(map[string]bool) + seenPointers := make(map[*openapi3.Schema]bool) parameters := []*api.Type{} var idParam string @@ -423,7 +424,7 @@ func parseOpenApi(resourcePath, resourceName string, op *openapi3.Operation) []a if strings.Contains(strings.ToLower(param.Value.Name), strings.ToLower(resourceName)) { idParam = param.Value.Name } - paramObj := WriteObject(param.Value.Name, param.Value.Schema, propType(param.Value.Schema), true, seenRefs) + paramObj := WriteObject(param.Value.Name, param.Value.Schema, propType(param.Value.Schema), true, seenRefs, seenPointers) description := param.Value.Description if strings.TrimSpace(description) == "" { description = "No description" @@ -439,7 +440,12 @@ func parseOpenApi(resourcePath, resourceName string, op *openapi3.Operation) []a parameters = append(parameters, ¶mObj) } - properties := buildProperties(op.RequestBody.Value.Content["application/json"].Schema.Value.Properties, op.RequestBody.Value.Content["application/json"].Schema.Value.Required, seenRefs) + var properties []*api.Type + if op.RequestBody != nil && op.RequestBody.Value != nil && op.RequestBody.Value.Content != nil { + if mediaType, ok := op.RequestBody.Value.Content["application/json"]; ok && mediaType != nil && mediaType.Schema != nil && mediaType.Schema.Value != nil { + properties = buildProperties(mediaType.Schema.Value.Properties, mediaType.Schema.Value.Required, seenRefs, seenPointers) + } + } returnArray = append(returnArray, parameters) returnArray = append(returnArray, properties) @@ -449,14 +455,25 @@ func parseOpenApi(resourcePath, resourceName string, op *openapi3.Operation) []a } func propType(prop *openapi3.SchemaRef) openapi3.Types { - if len(prop.Value.AllOf) > 0 { + if prop.Value == nil { + return openapi3.Types{"object"} + } + if len(prop.Value.AllOf) > 0 && prop.Value.AllOf[0].Value != nil && prop.Value.AllOf[0].Value.Type != nil { return *prop.Value.AllOf[0].Value.Type - } else { - return *prop.Value.Type } + if prop.Value.Type == nil { + if len(prop.Value.Properties) > 0 { + return openapi3.Types{"object"} + } + if prop.Value.Items != nil { + return openapi3.Types{"array"} + } + return openapi3.Types{"object"} + } + return *prop.Value.Type } -func WriteObject(name string, obj *openapi3.SchemaRef, objType openapi3.Types, urlParam bool, seenRefs map[string]bool) api.Type { +func WriteObject(name string, obj *openapi3.SchemaRef, objType openapi3.Types, urlParam bool, seenRefs map[string]bool, seenPointers map[*openapi3.Schema]bool) api.Type { var field api.Type switch name { @@ -488,6 +505,25 @@ func WriteObject(name string, obj *openapi3.SchemaRef, objType openapi3.Types, u seenRefs = newSeenRefs } + if obj.Value != nil { + if seenPointers[obj.Value] { + var field api.Type + field.Name = name + field.Type = "String" + field.CustomExpand = "templates/terraform/custom_expand/json_schema.tmpl" + field.CustomFlatten = "templates/terraform/custom_flatten/json_schema.tmpl" + field.Description = "Recursive field represented as JSON" + return field + } + // Copy map to isolate branches + newSeenPointers := make(map[*openapi3.Schema]bool) + for k, v := range seenPointers { + newSeenPointers[k] = v + } + newSeenPointers[obj.Value] = true + seenPointers = newSeenPointers + } + if len(obj.Value.AllOf) > 0 { obj = obj.Value.AllOf[0] objType = *obj.Value.Type @@ -538,15 +574,15 @@ func WriteObject(name string, obj *openapi3.SchemaRef, objType openapi3.Types, u field.KeyName = "TODO: CHANGEME" var valueType api.Type valueType.Type = "NestedObject" - valueType.Properties = buildProperties(obj.Value.AdditionalProperties.Schema.Value.Properties, obj.Value.AdditionalProperties.Schema.Value.Required, seenRefs) + valueType.Properties = buildProperties(obj.Value.AdditionalProperties.Schema.Value.Properties, obj.Value.AdditionalProperties.Schema.Value.Required, seenRefs, seenPointers) field.ValueType = &valueType } else { - field.Properties = buildProperties(obj.Value.Properties, obj.Value.Required, seenRefs) + field.Properties = buildProperties(obj.Value.Properties, obj.Value.Required, seenRefs, seenPointers) } case "array": field.Type = "Array" var subField api.Type - typ := *obj.Value.Items.Value.Type + typ := propType(obj.Value.Items) switch typ[0] { case "string": subField.Type = "String" @@ -558,7 +594,7 @@ func WriteObject(name string, obj *openapi3.SchemaRef, objType openapi3.Types, u subField.Type = "Boolean" case "object": subField.Type = "NestedObject" - subField.Properties = buildProperties(obj.Value.Items.Value.Properties, obj.Value.Items.Value.Required, seenRefs) + subField.Properties = buildProperties(obj.Value.Items.Value.Properties, obj.Value.Items.Value.Required, seenRefs, seenPointers) } field.ItemType = &subField default: @@ -597,11 +633,11 @@ func WriteObject(name string, obj *openapi3.SchemaRef, objType openapi3.Types, u return field } -func buildProperties(props openapi3.Schemas, required []string, seenRefs map[string]bool) []*api.Type { +func buildProperties(props openapi3.Schemas, required []string, seenRefs map[string]bool, seenPointers map[*openapi3.Schema]bool) []*api.Type { properties := []*api.Type{} for _, k := range slices.Sorted(maps.Keys(props)) { prop := props[k] - propObj := WriteObject(k, prop, propType(prop), false, seenRefs) + propObj := WriteObject(k, prop, propType(prop), false, seenRefs, seenPointers) if slices.Contains(required, k) { propObj.Required = true } diff --git a/mmv1/openapi_generate/parser_test.go b/mmv1/openapi_generate/parser_test.go index 9f8645d0fb45..25f582320f9b 100644 --- a/mmv1/openapi_generate/parser_test.go +++ b/mmv1/openapi_generate/parser_test.go @@ -25,7 +25,7 @@ func TestMapType(t *testing.T) { } petSchema := doc.Paths.Map()["/pets"].Post.RequestBody.Value.Content["application/json"].Schema - mmObject := WriteObject("pet", petSchema, propType(petSchema), false, make(map[string]bool)) + mmObject := WriteObject("pet", petSchema, propType(petSchema), false, make(map[string]bool), make(map[*openapi3.Schema]bool)) if mmObject.KeyName == "" || mmObject.Type != "Map" { t.Error("Failed to parse map type") } diff --git a/mmv1/products/accessapproval/FolderSettings.yaml b/mmv1/products/accessapproval/FolderSettings.yaml index c820317332e7..6cd860ea7a5a 100644 --- a/mmv1/products/accessapproval/FolderSettings.yaml +++ b/mmv1/products/accessapproval/FolderSettings.yaml @@ -29,6 +29,9 @@ update_verb: PATCH legacy_name: google_folder_access_approval_settings import_format: - folders/{{folder_id}}/accessApprovalSettings +include_in_tgc_next: true +tgc_tests: + - name: 'TestAccAccessApprovalSettings/folder' custom_code: constants: templates/terraform/constants/access_approval.go.tmpl pre_create: templates/terraform/update_mask.go.tmpl diff --git a/mmv1/products/accesscontextmanager/AccessLevelCondition.yaml b/mmv1/products/accesscontextmanager/AccessLevelCondition.yaml index 42b7a12b160b..ba454af384d3 100644 --- a/mmv1/products/accesscontextmanager/AccessLevelCondition.yaml +++ b/mmv1/products/accesscontextmanager/AccessLevelCondition.yaml @@ -50,7 +50,7 @@ immutable: true mutex: '{{access_policy_id}}' import_format: - '{{access_level}}' - # no unique way to specify +# no unique way to specify exclude_import: true timeouts: insert_minutes: 20 diff --git a/mmv1/products/activedirectory/Domain.yaml b/mmv1/products/activedirectory/Domain.yaml index fc64dba621bc..a67788f497ca 100644 --- a/mmv1/products/activedirectory/Domain.yaml +++ b/mmv1/products/activedirectory/Domain.yaml @@ -26,7 +26,7 @@ self_link: '{{name}}' create_url: 'projects/{{project}}/locations/global/domains?domainName={{domain_name}}' update_verb: 'PATCH' update_mask: true - # equivalent to {{name}}, but makes sweepers work +# equivalent to {{name}}, but makes sweepers work delete_url: 'projects/{{project}}/locations/global/domains/{{domain_name}}' import_format: - '{{project}} {{name}}' @@ -41,7 +41,7 @@ async: type: 'OpAsync' operation: base_url: '{{op_id}}' - # It takes about 35-40 mins to get the resource created + # It takes about 35-40 mins to get the resource created timeouts: insert_minutes: 60 update_minutes: 60 diff --git a/mmv1/products/activedirectory/DomainTrust.yaml b/mmv1/products/activedirectory/DomainTrust.yaml index 93771ad0c432..47c33dbf2ef4 100644 --- a/mmv1/products/activedirectory/DomainTrust.yaml +++ b/mmv1/products/activedirectory/DomainTrust.yaml @@ -27,7 +27,7 @@ self_link: 'projects/{{project}}/locations/global/domains/{{domain}}' create_url: 'projects/{{project}}/locations/global/domains/{{domain}}:attachTrust' update_url: 'projects/{{project}}/locations/global/domains/{{domain}}:reconfigureTrust' update_verb: 'POST' - # Resource custom delete function needs to be modified any time when the resource schema is edited +# Resource custom delete function needs to be modified any time when the resource schema is edited delete_url: 'projects/{{project}}/locations/global/domains/{{domain}}:detachTrust' delete_verb: 'POST' import_format: @@ -55,14 +55,14 @@ custom_code: encoder: 'templates/terraform/encoders/active_directory_domain_trust.go.tmpl' update_encoder: 'templates/terraform/update_encoder/active_directory_domain_trust.go.tmpl' decoder: 'templates/terraform/decoders/unwrap_resource.go.tmpl' - # Delete function needs to be modified any time when the resource schema is edited + # Delete function needs to be modified any time when the resource schema is edited custom_delete: 'templates/terraform/custom_delete/active_directory_domain_trust.go.tmpl' examples: - name: 'active_directory_domain_trust_basic' primary_resource_id: 'ad-domain-trust' - # Fine-grained resource need different autogenerated tests, as - # we need to check destroy during a test step where the parent resource - # still exists and we need to validate that child resource has been deleted + # Fine-grained resource need different autogenerated tests, as + # we need to check destroy during a test step where the parent resource + # still exists and we need to validate that child resource has been deleted exclude_test: true parameters: - name: 'domain' diff --git a/mmv1/products/alloydb/Backup.yaml b/mmv1/products/alloydb/Backup.yaml index e8c3c321e253..7977ff9d63d0 100644 --- a/mmv1/products/alloydb/Backup.yaml +++ b/mmv1/products/alloydb/Backup.yaml @@ -61,7 +61,7 @@ examples: alloydb_instance_name: 'alloydb-instance' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' ignore_read_extra: - 'reconciling' - 'update_time' @@ -85,7 +85,7 @@ examples: alloydb_instance_name: 'alloydb-instance' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' ignore_read_extra: - 'reconciling' - 'update_time' diff --git a/mmv1/products/alloydb/Cluster.yaml b/mmv1/products/alloydb/Cluster.yaml index 33c815bd0c1f..0efeb8253587 100644 --- a/mmv1/products/alloydb/Cluster.yaml +++ b/mmv1/products/alloydb/Cluster.yaml @@ -59,6 +59,8 @@ custom_code: pre_create: 'templates/terraform/pre_create/alloydb_cluster.go.tmpl' pre_update: 'templates/terraform/pre_update/alloydb_cluster.go.tmpl' pre_delete: 'templates/terraform/pre_delete/alloydb_cluster.go.tmpl' +deletion_policy_default: "DEFAULT" +deletion_policy_custom_docs: true # Skipping the sweeper because we need to force-delete clusters. exclude_sweeper: true include_in_tgc_next: true @@ -76,7 +78,7 @@ examples: alloydb_instance_name: 'alloydb-instance' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "alloydb-1")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "alloydb-1")' ignore_read_extra: - 'deletion_protection' - name: 'alloydb_cluster_after_upgrade' @@ -86,7 +88,7 @@ examples: alloydb_instance_name: 'alloydb-instance' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "alloydb-1")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "alloydb-1")' ignore_read_extra: - 'deletion_protection' - name: 'alloydb_cluster_full' @@ -105,7 +107,7 @@ examples: alloydb_instance_name: 'alloydb-instance' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "alloydb-instance-basic")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "alloydb-instance-basic")' ignore_read_extra: - 'deletion_protection' - 'reconciling' @@ -128,7 +130,7 @@ examples: alloydb_secondary_cluster_name: 'alloydb-secondary-cluster' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' ignore_read_extra: - 'deletion_protection' exclude_docs: true @@ -138,9 +140,17 @@ virtual_fields: Policy to determine if the cluster should be deleted forcefully. Deleting a cluster forcefully, deletes the cluster and all its associated instances within the cluster. Deleting a Secondary cluster with a secondary instance REQUIRES setting deletion_policy = "FORCE" otherwise an error is returned. This is needed as there is no support to delete just the secondary instance, and the only way to delete secondary instance is to delete the associated secondary cluster forcefully which also deletes the secondary instance. - Possible values: DEFAULT, FORCE + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". + + Possible values: DEFAULT, FORCE, PREVENT, ABANDON, DELETE type: String - default_value: "DEFAULT" + # excluded from generation due to Universal Deletion Policy + exclude: true - name: 'deletion_protection' description: | Whether Terraform will be prevented from destroying the cluster. diff --git a/mmv1/products/alloydb/Instance.yaml b/mmv1/products/alloydb/Instance.yaml index 0343e7e0d70c..992041a65db1 100644 --- a/mmv1/products/alloydb/Instance.yaml +++ b/mmv1/products/alloydb/Instance.yaml @@ -88,7 +88,7 @@ examples: alloydb_instance_name: 'alloydb-instance' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' ignore_read_extra: - 'reconciling' - 'update_time' @@ -102,7 +102,7 @@ examples: alloydb_secondary_instance_name: 'alloydb-secondary-instance' network_name: 'alloydb-secondary-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' ignore_read_extra: - 'reconciling' - 'update_time' diff --git a/mmv1/products/alloydb/User.yaml b/mmv1/products/alloydb/User.yaml index ee44ebe9a4f6..6b39113461e7 100644 --- a/mmv1/products/alloydb/User.yaml +++ b/mmv1/products/alloydb/User.yaml @@ -64,7 +64,7 @@ examples: alloydb_user_pass: 'user_secret' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' # for backward compatible alloydb_user_name: '"user1" + randomSuffix' ignore_read_extra: @@ -91,7 +91,7 @@ examples: alloydb_user_name: 'user2@foo.com' network_name: 'alloydb-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1")' # for backward compatible alloydb_user_name: '"user2@foo.com" + randomSuffix' exclude_docs: true diff --git a/mmv1/products/apigee/DataCollector.yaml b/mmv1/products/apigee/DataCollector.yaml new file mode 100644 index 000000000000..6aa133ecd0af --- /dev/null +++ b/mmv1/products/apigee/DataCollector.yaml @@ -0,0 +1,105 @@ +# Copyright 2024 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: 'DataCollector' +description: | + A `DataCollector` collects and stores data from the runtime for use in + Analytics custom reports or API monetization. Data collectors are scoped + to an Apigee organization. +references: + guides: + 'Creating a data collector': 'https://cloud.google.com/apigee/docs/api-platform/analytics/custom-reports' + api: 'https://cloud.google.com/apigee/docs/reference/apis/apigee/rest/v1/organizations.datacollectors' +docs: +base_url: '{{org_id}}/datacollectors' +self_link: '{{org_id}}/datacollectors/{{data_collector_id}}' +create_url: '{{org_id}}/datacollectors?dataCollectorId={{data_collector_id}}' +update_url: '{{org_id}}/datacollectors/{{data_collector_id}}' +update_verb: 'PATCH' +update_mask: true +delete_url: '{{org_id}}/datacollectors/{{data_collector_id}}' +import_format: + - '{{org_id}}/datacollectors/{{data_collector_id}}' + - '{{org_id}}/{{data_collector_id}}' +timeouts: + insert_minutes: 1 + update_minutes: 1 + delete_minutes: 1 +custom_code: + custom_import: 'templates/terraform/custom_import/apigee_data_collector.go.tmpl' +examples: + - name: 'apigee_data_collector_basic' + vars: + network_name: 'apigee-network' + range_name: 'apigee-range' + data_collector_id: 'dc_my_data_collector' + exclude_test: true + - name: 'apigee_data_collector_basic_test' + primary_resource_id: 'apigee_data_collector' + test_env_vars: + org_id: 'ORG_ID' + billing_account: 'BILLING_ACCT' + exclude_docs: true + external_providers: ["time"] +parameters: + - name: 'orgId' + type: String + description: | + The Apigee Organization associated with the Apigee data collector, + in the format `organizations/{{org_name}}`. + url_param_only: true + required: true + immutable: true + - name: 'dataCollectorId' + type: String + description: | + The ID for the data collector. Must begin with `dc_`. + url_param_only: true + required: true + immutable: true + validation: + regex: '^dc_[a-zA-Z0-9_]+$' +properties: + - name: 'name' + type: String + description: | + The resource name of the data collector, in the format + `organizations/{{org_name}}/datacollectors/{{data_collector_id}}`. + output: true + - name: 'description' + type: String + description: | + A description of the data collector. + - name: 'type' + type: Enum + description: | + The type of data this data collector will collect. + required: true + immutable: true + enum_values: + - 'BOOLEAN' + - 'DATETIME' + - 'FLOAT' + - 'INTEGER' + - 'STRING' + - name: 'createdAt' + type: String + description: | + The time at which the data collector was created in milliseconds since the epoch. + output: true + - name: 'lastModifiedAt' + type: String + description: | + The time at which the data collector was last modified in milliseconds since the epoch. + output: true diff --git a/mmv1/products/apigee/EnvKeystore.yaml b/mmv1/products/apigee/EnvKeystore.yaml index 1e6f7c97fe94..eaa7da3780c6 100644 --- a/mmv1/products/apigee/EnvKeystore.yaml +++ b/mmv1/products/apigee/EnvKeystore.yaml @@ -29,7 +29,7 @@ immutable: true import_format: - '{{env_id}}/keystores/{{name}}' - '{{env_id}}/{{name}}' - # Resource creation race +# Resource creation race timeouts: insert_minutes: 1 update_minutes: 20 diff --git a/mmv1/products/apigee/EnvReferences.yaml b/mmv1/products/apigee/EnvReferences.yaml index 6ba464c81ad5..96b3462f893c 100644 --- a/mmv1/products/apigee/EnvReferences.yaml +++ b/mmv1/products/apigee/EnvReferences.yaml @@ -28,7 +28,7 @@ delete_url: '{{env_id}}/references/{{name}}' import_format: - '{{env_id}}/references/{{name}}' - '{{env_id}}/{{name}}' - # Resource creation race +# Resource creation race timeouts: insert_minutes: 1 update_minutes: 20 diff --git a/mmv1/products/apigee/Envgroup.yaml b/mmv1/products/apigee/Envgroup.yaml index 576f3fbf0a2b..7a5ade7bc062 100644 --- a/mmv1/products/apigee/Envgroup.yaml +++ b/mmv1/products/apigee/Envgroup.yaml @@ -48,15 +48,15 @@ examples: vars: envgroup_name: 'my-envgroup' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_environment_group_basic_test' primary_resource_id: 'apigee_environment_group' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] parameters: diff --git a/mmv1/products/apigee/EnvgroupAttachment.yaml b/mmv1/products/apigee/EnvgroupAttachment.yaml index ac75d8abae38..9ac6ebb195a9 100644 --- a/mmv1/products/apigee/EnvgroupAttachment.yaml +++ b/mmv1/products/apigee/EnvgroupAttachment.yaml @@ -46,8 +46,8 @@ custom_code: exclude_sweeper: true examples: - name: 'apigee_environment_group_attachment_basic' - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. vars: project_id: 'my-project' envgroup_name: 'my-envgroup' @@ -62,7 +62,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] parameters: diff --git a/mmv1/products/apigee/Environment.yaml b/mmv1/products/apigee/Environment.yaml index d99561cd20df..53f2e11ed89c 100644 --- a/mmv1/products/apigee/Environment.yaml +++ b/mmv1/products/apigee/Environment.yaml @@ -52,15 +52,15 @@ examples: vars: environment_name: 'my-environment' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_environment_basic_test' primary_resource_id: 'apigee_environment' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_environment_basic_deployment_apiproxy_type_test' @@ -69,7 +69,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_environment_basic_properties_test' @@ -88,7 +88,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_environment_client_ip_resolution_config_test' @@ -97,7 +97,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] parameters: diff --git a/mmv1/products/apigee/Instance.yaml b/mmv1/products/apigee/Instance.yaml index c71be6099289..5d963ac6384a 100644 --- a/mmv1/products/apigee/Instance.yaml +++ b/mmv1/products/apigee/Instance.yaml @@ -53,53 +53,53 @@ examples: vars: instance_name: 'my-instance-name' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_instance_basic_test' primary_resource_id: 'apigee_instance' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_instance_cidr_range' vars: instance_name: 'my-instance-name' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_instance_cidr_range_test' primary_resource_id: 'apigee_instance' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_instance_ip_range' vars: instance_name: 'my-instance-name' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_instance_ip_range_test' primary_resource_id: 'apigee_instance' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_instance_full' vars: instance_name: 'my-instance-name' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_instance_full_test' primary_resource_id: 'apigee_instance' min_version: 'beta' @@ -107,7 +107,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_instance_service_attachment_basic_test' @@ -116,7 +116,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] parameters: diff --git a/mmv1/products/apigee/InstanceAttachment.yaml b/mmv1/products/apigee/InstanceAttachment.yaml index 942b765976ea..f7f30d0531b7 100644 --- a/mmv1/products/apigee/InstanceAttachment.yaml +++ b/mmv1/products/apigee/InstanceAttachment.yaml @@ -55,15 +55,15 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_instance_attachment_basic_test' primary_resource_id: 'apigee_instance_attachment' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] parameters: diff --git a/mmv1/products/apigee/KeystoresAliasesSelfSignedCert.yaml b/mmv1/products/apigee/KeystoresAliasesSelfSignedCert.yaml index 57f5912b5872..b3f44b3026f1 100644 --- a/mmv1/products/apigee/KeystoresAliasesSelfSignedCert.yaml +++ b/mmv1/products/apigee/KeystoresAliasesSelfSignedCert.yaml @@ -38,8 +38,8 @@ custom_code: custom_import: 'templates/terraform/custom_import/apigee_env_keystore_alias_self_signed_cert.go.tmpl' exclude_sweeper: true examples: - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_env_keystore_alias_self_signed_cert' primary_resource_id: 'apigee_environment_keystore_ss_alias' vars: diff --git a/mmv1/products/apigee/NatAddress.yaml b/mmv1/products/apigee/NatAddress.yaml index 916e33d2be46..062bd640446e 100644 --- a/mmv1/products/apigee/NatAddress.yaml +++ b/mmv1/products/apigee/NatAddress.yaml @@ -53,15 +53,15 @@ examples: vars: nat_address_name: 'my-nat-address' exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. + # This is a more verbose version of the above that creates all + # the resources needed for the acceptance test. - name: 'apigee_nat_address_basic_test' primary_resource_id: 'apigee_nat_address' test_env_vars: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' exclude_docs: true - # Resource creation race + # Resource creation race skip_vcr: true external_providers: ["time"] - name: 'apigee_nat_address_with_activate' diff --git a/mmv1/products/apigee/Space.yaml b/mmv1/products/apigee/Space.yaml index 93b4fcee3420..6409402af26c 100644 --- a/mmv1/products/apigee/Space.yaml +++ b/mmv1/products/apigee/Space.yaml @@ -44,8 +44,8 @@ examples: external_providers: ["time"] - name: "apigee_space_basic" exclude_test: true - # This is a more verbose version of the above that creates all - # the resources needed for the acceptance test. +# This is a more verbose version of the above that creates all +# the resources needed for the acceptance test. parameters: - name: "orgId" type: String diff --git a/mmv1/products/artifactregistry/Repository.yaml b/mmv1/products/artifactregistry/Repository.yaml index 26c6ef220356..fdd3a0589325 100644 --- a/mmv1/products/artifactregistry/Repository.yaml +++ b/mmv1/products/artifactregistry/Repository.yaml @@ -43,7 +43,7 @@ include_in_tgc_next: true iam_policy: method_name_separator: ':' allowed_iam_role: 'roles/artifactregistry.reader' - # TODO: Change to repository_id in 4.0 + # TODO: Change to repository_id in 4.0 parent_resource_attribute: 'repository' base_url: 'projects/{{project}}/locations/{{location}}/repositories/{{name}}' self_link: 'projects/{{project}}/locations/{{location}}/repositories/{{name}}' @@ -88,7 +88,7 @@ examples: repository_id: 'my-repository' kms_key_name: 'kms-key' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' - name: 'artifact_registry_repository_virtual' primary_resource_id: 'my-repo' vars: diff --git a/mmv1/products/backupdr/BackupPlan.yaml b/mmv1/products/backupdr/BackupPlan.yaml index 39cccd01c1d7..e00be8b6fe29 100644 --- a/mmv1/products/backupdr/BackupPlan.yaml +++ b/mmv1/products/backupdr/BackupPlan.yaml @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +--- name: 'BackupPlan' base_url: projects/{{project}}/locations/{{location}}/backupPlans create_url: projects/{{project}}/locations/{{location}}/backupPlans/?backup_plan_id={{backup_plan_id}} @@ -261,6 +262,8 @@ properties: This is only applicable for CloudSql resource. Days for which logs will be stored. This value should be greater than or equal to minimum enforced log retention duration of the backup vault. - name: 'diskBackupPlanProperties' type: NestedObject + update_mask_fields: + - 'disk_backup_plan_properties.guest_flush' description: | Defines optional disk related properties for backups generated by this plan. properties: @@ -272,3 +275,17 @@ properties: backup. When set to true, the system will attempt to ensure application-consistent backups. When set to false, the system will create crash-consistent backups. + - name: 'computeInstanceBackupPlanProperties' + type: NestedObject + update_mask_fields: + - 'compute_instance_backup_plan_properties.guest_flush' + description: | + Defines optional compute instance related properties for backups generated by this plan. + properties: + - name: 'guestFlush' + type: Boolean + required: true + description: | + Indicates whether to perform a guest flush operation before taking a + compute instance backup. When set to true, the system will attempt + to ensure application-consistent backups. diff --git a/mmv1/products/backupdr/BackupPlanAssociation.yaml b/mmv1/products/backupdr/BackupPlanAssociation.yaml index 7c3f8db8afb3..827342a00719 100644 --- a/mmv1/products/backupdr/BackupPlanAssociation.yaml +++ b/mmv1/products/backupdr/BackupPlanAssociation.yaml @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +--- name: 'BackupPlanAssociation' base_url: projects/{{project}}/locations/{{location}}/backupPlanAssociations create_url: projects/{{project}}/locations/{{location}}/backupPlanAssociations/?backup_plan_association_id={{backup_plan_association_id}} diff --git a/mmv1/products/backupdr/BackupVault.yaml b/mmv1/products/backupdr/BackupVault.yaml index 9d60bacf2105..f98dd445ef3b 100644 --- a/mmv1/products/backupdr/BackupVault.yaml +++ b/mmv1/products/backupdr/BackupVault.yaml @@ -58,7 +58,7 @@ examples: test_env_vars: project: 'PROJECT_NAME' test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' parameters: - name: 'location' type: String diff --git a/mmv1/products/backupdr/RestoreWorkload.yaml b/mmv1/products/backupdr/RestoreWorkload.yaml index 2665e2c3e9ab..528c0cb675f6 100644 --- a/mmv1/products/backupdr/RestoreWorkload.yaml +++ b/mmv1/products/backupdr/RestoreWorkload.yaml @@ -303,13 +303,16 @@ properties: - name: 'diskEncryptionKey' type: NestedObject description: 'Optional. Encrypts or decrypts a disk using a customer-supplied encryption key.' + immutable: true properties: - name: 'rawKey' type: String description: 'Optional. Specifies a 256-bit customer-supplied encryption key.' + sensitive: true - name: 'rsaEncryptedKey' type: String description: 'Optional. RSA-wrapped 2048-bit customer-supplied encryption key.' + sensitive: true - name: 'kmsKeyName' type: String description: 'Optional. The name of the encryption key that is stored in Google Cloud KMS.' @@ -360,11 +363,14 @@ properties: - name: 'instanceEncryptionKey' type: NestedObject description: 'Optional. Encrypts suspended data for an instance with a customer-managed encryption key.' + immutable: true properties: - name: 'rawKey' type: String + sensitive: true - name: 'rsaEncryptedKey' type: String + sensitive: true - name: 'kmsKeyName' type: String - name: 'kmsKeyServiceAccount' @@ -708,11 +714,14 @@ properties: - name: 'diskEncryptionKey' type: NestedObject description: 'Optional. Encrypts the disk using a customer-supplied encryption key.' + immutable: true properties: - name: 'rawKey' type: String + sensitive: true - name: 'rsaEncryptedKey' type: String + sensitive: true - name: 'kmsKeyName' type: String - name: 'kmsKeyServiceAccount' diff --git a/mmv1/products/beyondcorp/SecurityGateway.yaml b/mmv1/products/beyondcorp/SecurityGateway.yaml index 22cc9e87e7f4..c8e415ef1585 100644 --- a/mmv1/products/beyondcorp/SecurityGateway.yaml +++ b/mmv1/products/beyondcorp/SecurityGateway.yaml @@ -246,4 +246,4 @@ properties: allow_empty_object: true description: Settings related to Cloud Logging. properties: - [] # Meant to be an empty object with no properties for now. + [] # Meant to be an empty object with no properties for now. diff --git a/mmv1/products/bigquery/DatasetAccess.yaml b/mmv1/products/bigquery/DatasetAccess.yaml index 8e51f2331fbf..8596ee17bd8f 100644 --- a/mmv1/products/bigquery/DatasetAccess.yaml +++ b/mmv1/products/bigquery/DatasetAccess.yaml @@ -45,7 +45,7 @@ timeouts: update_minutes: 20 delete_minutes: 20 exclude_identity_from_identity_import: true - # the identity values aren't used for identity import +# the identity values aren't used for identity import identity: - role - userByEmail @@ -76,7 +76,7 @@ examples: vars: dataset_id: 'example_dataset' account_name: 'bqowner' - # not importable + # not importable test_vars_overrides: # for backward compatible account_name: '"bqowner" + randomSuffix' @@ -87,14 +87,14 @@ examples: dataset_id: 'example_dataset' dataset_id2: 'example_dataset2' table_id: 'example_table' - # not importable + # not importable exclude_test: true - name: 'bigquery_dataset_access_authorized_dataset' primary_resource_id: 'access' vars: private: 'private' public: 'public' - # not importable + # not importable test_vars_overrides: # for backward compatible private: '"private" + randomSuffix' @@ -107,7 +107,7 @@ examples: private_dataset: 'private_dataset' public_dataset: 'public_dataset' public_routine: 'public_routine' - # not importable + # not importable exclude_test: true parameters: properties: diff --git a/mmv1/products/bigquery/Job.yaml b/mmv1/products/bigquery/Job.yaml index 69ae81a65562..77bff4787fe8 100644 --- a/mmv1/products/bigquery/Job.yaml +++ b/mmv1/products/bigquery/Job.yaml @@ -95,7 +95,7 @@ examples: primary_resource_id: 'job' vars: job_id: 'job_load' - # Keep small(er) to avoid downstream acctest having too-long a bucket name + # Keep small(er) to avoid downstream acctest having too-long a bucket name bucket_name: 'bq-geojson' test_env_vars: project: 'PROJECT_NAME' @@ -117,7 +117,7 @@ examples: - 'etag' - 'load.0.destination_table.0.table_id' - 'status.0.state' - # there are a lot of examples for this resource, so omitting some that are similar to others + # there are a lot of examples for this resource, so omitting some that are similar to others exclude_docs: true - name: 'bigquery_job_copy' primary_resource_id: 'job' @@ -128,7 +128,7 @@ examples: test_env_vars: project: 'PROJECT_NAME' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-bootstrap-bigquery-job-key1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-bootstrap-bigquery-job-key1").CryptoKey.Name' # for backward compatible account_name: '"bqowner" + randomSuffix' ignore_read_extra: @@ -143,7 +143,7 @@ examples: test_env_vars: project: 'PROJECT_NAME' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-bootstrap-bigquery-job-key2").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-bootstrap-bigquery-job-key2").CryptoKey.Name' # for backward compatible account_name: '"bqowner" + randomSuffix' ignore_read_extra: @@ -152,7 +152,7 @@ examples: - 'copy.0.source_tables.0.table_id' - 'copy.0.source_tables.1.table_id' - 'status.0.state' - # there are a lot of examples for this resource, so omitting some that are similar to others + # there are a lot of examples for this resource, so omitting some that are similar to others exclude_docs: true - name: 'bigquery_job_extract' primary_resource_id: 'job' @@ -177,7 +177,7 @@ examples: - 'etag' - 'extract.0.source_table.0.table_id' - 'status.0.state' - # there are a lot of examples for this resource, so omitting some that are similar to others + # there are a lot of examples for this resource, so omitting some that are similar to others exclude_docs: true - name: 'bigquery_job_query_reservation' exclude_docs: true diff --git a/mmv1/products/bigqueryconnection/Connection.yaml b/mmv1/products/bigqueryconnection/Connection.yaml index 345fb064c20e..59fb9078945a 100644 --- a/mmv1/products/bigqueryconnection/Connection.yaml +++ b/mmv1/products/bigqueryconnection/Connection.yaml @@ -145,7 +145,7 @@ examples: kms_key_name: 'projects/project/locations/us-central1/keyRings/us-central1/cryptoKeys/bq-key' test_vars_overrides: 'deletion_protection': 'false' - 'kms_key_name': 'acctest.BootstrapKMSKey(t).CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKey(t).CryptoKey.Name' # for backward compatible username: '"user" + randomSuffix' oics_vars_overrides: @@ -163,8 +163,8 @@ examples: username: '"user" + randomSuffix' password: '"password"' ignore_read_extra: - # username and password are not returned by the API - - 'configuration.0.authentication.0.username_password.0.username' + # The plaintext password is redacted by the API on read, so it cannot + # be verified against the original config. - 'configuration.0.authentication.0.username_password.0.password' external_providers: ["random", "time"] # Random provider diff --git a/mmv1/products/bigquerydatatransfer/Config.yaml b/mmv1/products/bigquerydatatransfer/Config.yaml index b7aef36e1dbb..5caf86c44804 100644 --- a/mmv1/products/bigquerydatatransfer/Config.yaml +++ b/mmv1/products/bigquerydatatransfer/Config.yaml @@ -239,7 +239,7 @@ properties: - 'sensitive_params.0.secretAccessKeyWo' conflicts: - 'sensitive_params.0.secretAccessKeyWo' - - name: 'secretAccessKeyWo' # Wo is convention for write-only properties + - name: 'secretAccessKeyWo' # Wo is convention for write-only properties type: String description: | The Secret Access Key of the AWS account transferring data from. diff --git a/mmv1/products/certificatemanager/CertificateMapEntry.yaml b/mmv1/products/certificatemanager/CertificateMapEntry.yaml index e3cbc0f1c030..97b6e0d448d6 100644 --- a/mmv1/products/certificatemanager/CertificateMapEntry.yaml +++ b/mmv1/products/certificatemanager/CertificateMapEntry.yaml @@ -52,7 +52,7 @@ examples: parameters: - name: 'name' type: String - # url_param_only: true + # url_param_only: true description: | A user-defined name of the Certificate Map Entry. Certificate Map Entry names must be unique globally and match pattern diff --git a/mmv1/products/ces/App.yaml b/mmv1/products/ces/App.yaml index 78e4b392ff84..8aef2f96231c 100644 --- a/mmv1/products/ces/App.yaml +++ b/mmv1/products/ces/App.yaml @@ -13,7 +13,9 @@ --- name: App -description: Description +description: Customer Engagement Suite App +references: + api: https://docs.cloud.google.com/customer-engagement-ai/conversational-agents/ps/reference/rest/v1/projects.locations.apps base_url: projects/{{project}}/locations/{{location}}/apps self_link: projects/{{project}}/locations/{{location}}/apps/{{name}} create_url: projects/{{project}}/locations/{{location}}/apps?appId={{app_id}} @@ -461,6 +463,11 @@ properties: - name: timeZone type: String description: The time zone of the app from the time zone database, e.g., America/Los_Angeles, Europe/Paris. + - name: toolExecutionMode + type: String + description: |- + The tool execution mode for the app. + See the [API reference](https://docs.cloud.google.com/customer-engagement-ai/conversational-agents/ps/reference/rpc/google.cloud.ces.v1#google.cloud.ces.v1.App.ToolExecutionMode) for more details. - name: updateTime type: String description: Timestamp when the app was last updated. diff --git a/mmv1/products/ces/AppVersion.yaml b/mmv1/products/ces/AppVersion.yaml index 46161ac72820..04185058cce5 100644 --- a/mmv1/products/ces/AppVersion.yaml +++ b/mmv1/products/ces/AppVersion.yaml @@ -1498,6 +1498,11 @@ properties: based on the LLM classification. output: true properties: + - name: failOpen + type: Boolean + description: |- + Determines the behavior when the guardrail encounters an LLM error. + output: true - name: customPolicy type: NestedObject description: |- diff --git a/mmv1/products/ces/Deployment.yaml b/mmv1/products/ces/Deployment.yaml index 2e78f1d0b012..dc858939d189 100644 --- a/mmv1/products/ces/Deployment.yaml +++ b/mmv1/products/ces/Deployment.yaml @@ -29,6 +29,12 @@ examples: app_display_name: my-app app_id: app-id deployment_display_name: my-deployment + - name: ces_deployment_full + primary_resource_id: my-deployment + vars: + app_display_name: my-app + app_id: app-id + deployment_display_name: my-deployment parameters: - name: location type: String @@ -69,6 +75,8 @@ properties: TWILIO GOOGLE_TELEPHONY_PLATFORM CONTACT_CENTER_AS_A_SERVICE + FIVE9 + CONTACT_CENTER_INTEGRATION - name: disableBargeInControl type: Boolean description: |- @@ -103,21 +111,47 @@ properties: description: |- The modality of the web widget. Possible values: - UNKNOWN_MODALITY + MODALITY_UNSPECIFIED CHAT_AND_VOICE VOICE_ONLY CHAT_ONLY + CHAT_VOICE_AND_VIDEO - name: theme type: String description: |- The theme of the web widget. Possible values: - UNKNOWN_THEME + THEME_UNSPECIFIED LIGHT DARK - name: webWidgetTitle type: String description: The title of the web widget. + - name: securitySettings + type: NestedObject + description: The security settings of the web widget. + properties: + - name: enablePublicAccess + type: Boolean + description: |- + Indicates whether public access to the web widget is enabled. If true, the web widget will be publicly accessible. If false, the web widget must be integrated with your own authentication and authorization system to return valid credentials for accessing the CES agent. + send_empty_value: true + - name: enableOriginCheck + type: Boolean + description: |- + Indicates whether origin check for the web widget is enabled. If true, the web widget will check the origin of the website that loads the web widget and only allow it to be loaded in the same origin or any of the allowed origins. + send_empty_value: true + - name: allowedOrigins + type: Array + description: |- + The origins that are allowed to host the web widget. An origin is defined by RFC 6454. If empty, all origins are allowed. A maximum of 100 origins is allowed. Example: "https://example.com" + item_type: + type: String + - name: enableRecaptcha + type: Boolean + description: |- + Indicates whether reCAPTCHA verification for the web widget is enabled. + send_empty_value: true - name: createTime type: String description: Timestamp when this deployment was created. diff --git a/mmv1/products/ces/Guardrail.yaml b/mmv1/products/ces/Guardrail.yaml index cda963012b5f..2a70abdf4ae4 100644 --- a/mmv1/products/ces/Guardrail.yaml +++ b/mmv1/products/ces/Guardrail.yaml @@ -44,6 +44,13 @@ examples: app_id: app-id guardrail_display_name: my-guardrail guardrail_id: guardrail-id + - name: ces_guardrail_llm_prompt_security_fail_open + primary_resource_id: ces_guardrail_llm_prompt_security_fail_open + vars: + app_display_name: my-app + app_id: app-id + guardrail_display_name: my-guardrail + guardrail_id: guardrail-id - name: ces_guardrail_code_callback primary_resource_id: ces_guardrail_code_callback vars: @@ -322,6 +329,14 @@ properties: Guardrail that blocks the conversation if the input is considered unsafe based on the LLM classification. properties: + - name: failOpen + type: Boolean + description: |- + Determines the behavior when the guardrail encounters an LLM error. + - If true: the guardrail is bypassed. + - If false (default): the guardrail triggers/blocks. + Note: If a custom policy is provided, this field is ignored in favor of + the policy's 'failOpen' configuration. - name: customPolicy type: NestedObject description: |- diff --git a/mmv1/products/chronicle/DataTable.yaml b/mmv1/products/chronicle/DataTable.yaml index 74626a2aa8ad..edc2c72d49ce 100644 --- a/mmv1/products/chronicle/DataTable.yaml +++ b/mmv1/products/chronicle/DataTable.yaml @@ -23,6 +23,8 @@ import_format: update_verb: PATCH update_mask: true +deletion_policy_default: "DEFAULT" +deletion_policy_custom_docs: true references: guides: 'Google SecOps Guides': 'https://cloud.google.com/chronicle/docs/secops/secops-overview' @@ -52,9 +54,17 @@ virtual_fields: The policy governing the deletion of the data table. If set to `FORCE`, allows the deletion of the data table even if it contains rows. If set to `DEFAULT`,or if the field is omitted, the data table must be empty before it can be deleted. - Possible values: DEFAULT, FORCE + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". + + Possible values: DEFAULT, FORCE, PREVENT, ABANDON, DELETE type: String - default_value: "DEFAULT" + # excluded from generation due to Universal Deletion Policy + exclude: true parameters: - name: location diff --git a/mmv1/products/chronicle/NativeDashboard.yaml b/mmv1/products/chronicle/NativeDashboard.yaml index dfcc9a1acaed..275d334b26a1 100644 --- a/mmv1/products/chronicle/NativeDashboard.yaml +++ b/mmv1/products/chronicle/NativeDashboard.yaml @@ -17,7 +17,7 @@ description: A configuration for a native dashboard within a Google SecOps (Chro references: guides: 'Google SecOps Guides': 'https://cloud.google.com/chronicle/docs/secops/secops-overview' - api: 'https://cloud.google.com/chronicle/docs/reference/rest/v1beta/projects.locations.instances.nativeDashboards' + api: 'https://cloud.google.com/chronicle/docs/reference/rest/v1/projects.locations.instances.nativeDashboards' base_url: projects/{{project}}/locations/{{location}}/instances/{{instance}}/nativeDashboards self_link: 'projects/{{project}}/locations/{{location}}/instances/{{instance}}/nativeDashboards/{{dashboard_id}}' create_url: projects/{{project}}/locations/{{location}}/instances/{{instance}}/nativeDashboards @@ -28,11 +28,9 @@ import_format: update_mask: true update_verb: PATCH -min_version: 'beta' examples: - name: chronicle_nativedashboard_basic primary_resource_id: my_basic_dashboard - min_version: 'beta' ignore_read_extra: - "last_viewed_time" vars: diff --git a/mmv1/products/chronicle/Rule.yaml b/mmv1/products/chronicle/Rule.yaml index fa65eb4e0513..3a1ae2fdbb08 100644 --- a/mmv1/products/chronicle/Rule.yaml +++ b/mmv1/products/chronicle/Rule.yaml @@ -27,7 +27,8 @@ import_format: update_verb: PATCH update_mask: true autogen_status: UnVsZQ== - +deletion_policy_default: "DEFAULT" +deletion_policy_custom_docs: true examples: - name: 'chronicle_rule_basic' primary_resource_id: example @@ -61,11 +62,19 @@ virtual_fields: If deletion_policy = "FORCE", any retrohunts and any detections associated with the rule will also be deleted. If deletion_policy = "DEFAULT", the call will only succeed if the rule has no associated retrohunts, including completed retrohunts, and no - associated detections. Regardless of this field's value, the rule - deployment associated with this rule will also be deleted. - Possible values: DEFAULT, FORCE + associated detections. Regardless of being set to "FORCE" the rule + deployment associated with this rule will also be deleted if deletion is successful. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". + + Possible values: DEFAULT, FORCE, PREVENT, ABANDON, DELETE type: String - default_value: "DEFAULT" + # excluded from generation due to Universal Deletion Policy + exclude: true parameters: - name: location diff --git a/mmv1/products/cloudbuildv2/Repository.yaml b/mmv1/products/cloudbuildv2/Repository.yaml index d8cc058b0c22..f8283344ad4a 100644 --- a/mmv1/products/cloudbuildv2/Repository.yaml +++ b/mmv1/products/cloudbuildv2/Repository.yaml @@ -41,8 +41,8 @@ exclude_tgc: true legacy_long_form_project: true include_in_tgc_next: true examples: -# These tests depend on secrets stored in a separate project, so we prefer not -# to show them in the docs. + # These tests depend on secrets stored in a separate project, so we prefer not + # to show them in the docs. - name: 'cloudbuildv2_repository_ghe' primary_resource_id: 'primary' vars: @@ -86,7 +86,7 @@ parameters: description: The location for the resource url_param_only: true immutable: true - # EXTRACT_FROM_FIELD_IF_EMPTY + # EXTRACT_FROM_FIELD_IF_EMPTY default_from_api: true - name: 'parent_connection' type: ResourceRef diff --git a/mmv1/products/cloudfunctions2/Function.yaml b/mmv1/products/cloudfunctions2/Function.yaml index a8492c52ca3e..3a7c182c22dc 100644 --- a/mmv1/products/cloudfunctions2/Function.yaml +++ b/mmv1/products/cloudfunctions2/Function.yaml @@ -73,7 +73,7 @@ examples: test_vars_overrides: 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -91,7 +91,7 @@ examples: 'zip_path': '"./test-fixtures/function-source-pubsub.zip"' 'primary_resource_id': '"terraform-test"' 'location': '"us-central1"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -108,7 +108,7 @@ examples: 'primary_resource_id': '"terraform-test"' 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -129,7 +129,7 @@ examples: test_vars_overrides: 'zip_path': '"./test-fixtures/function-source-eventarc-gcs.zip"' 'primary_resource_id': '"terraform-test"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -149,7 +149,7 @@ examples: test_vars_overrides: 'zip_path': '"./test-fixtures/function-source-eventarc-gcs.zip"' 'primary_resource_id': '"terraform-test"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -165,7 +165,7 @@ examples: test_vars_overrides: 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -185,7 +185,7 @@ examples: test_vars_overrides: 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step # for backward compatible secret: '"secret" + randomSuffix' ignore_read_extra: @@ -206,7 +206,7 @@ examples: test_vars_overrides: 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step # for backward compatible secret: '"secret" + randomSuffix' ignore_read_extra: @@ -224,7 +224,7 @@ examples: test_vars_overrides: 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step # for backward compatible pool: '"workerpool" + randomSuffix' ignore_read_extra: @@ -244,16 +244,16 @@ examples: test_env_vars: project: 'PROJECT_NAME' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step # for backward compatible kms_service_name: '"cloudkms.googleapis.com" + randomSuffix' ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' - # the example file is written in a repetitive way to help acc tests, so exclude + # the example file is written in a repetitive way to help acc tests, so exclude exclude_docs: true skip_vcr: true - name: 'cloudfunctions2_cmek_docs' @@ -268,7 +268,7 @@ examples: unencoded-ar-repo: 'ar-repo' kms_key_name: 'cmek-key' project: 'my-project-name' - # this example file will cause IAM conflicts between tests if used to make a test + # this example file will cause IAM conflicts between tests if used to make a test test_vars_overrides: # for backward compatible kms_service_name: '"cloudkms.googleapis.com" + randomSuffix' @@ -288,7 +288,7 @@ examples: 'zip_path': '"./test-fixtures/function-source-pubsub.zip"' 'primary_resource_id': '"terraform-test"' 'location': '"europe-west6"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -307,7 +307,7 @@ examples: 'zip_path': '"./test-fixtures/function-source-pubsub.zip"' 'primary_resource_id': '"terraform-test"' 'location': '"europe-west6"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' @@ -322,7 +322,7 @@ examples: test_vars_overrides: 'location': '"us-central1"' 'zip_path': '"./test-fixtures/function-source.zip"' - # ignore these fields during import step + # ignore these fields during import step ignore_read_extra: - 'build_config.0.source.0.storage_source.0.object' - 'build_config.0.source.0.storage_source.0.bucket' diff --git a/mmv1/products/cloudrun/Service.yaml b/mmv1/products/cloudrun/Service.yaml index f7eec0094d5f..4edfa4adde72 100644 --- a/mmv1/products/cloudrun/Service.yaml +++ b/mmv1/products/cloudrun/Service.yaml @@ -33,6 +33,7 @@ import_format: datasource_experimental: generate: true exclude_test: true +generate_list_resource: true timeouts: insert_minutes: 20 update_minutes: 20 @@ -69,95 +70,118 @@ sweeper: - region: "us-central1" - region: "europe-west1" - region: "europe-north1" -examples: +samples: - name: 'cloud_run_service_basic' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - test_env_vars: - project: 'PROJECT_NAME' + steps: + - name: 'cloud_run_service_basic' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + test_env_vars: + project: 'PROJECT_NAME' - name: 'cloud_run_service_gpu' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - test_env_vars: - project: 'PROJECT_NAME' + steps: + - name: 'cloud_run_service_gpu' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + test_env_vars: + project: 'PROJECT_NAME' - name: 'cloud_run_service_sql' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - cloud_run_sql_name: 'cloudrun-sql' - deletion_protection: 'true' - test_vars_overrides: - 'deletion_protection': 'false' - oics_vars_overrides: - 'deletion_protection': 'false' - ignore_read_extra: - - 'autogenerate_revision_name' + steps: + - name: 'cloud_run_service_sql' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + cloud_run_sql_name: 'cloudrun-sql' + vars: + deletion_protection: 'true' + test_vars_overrides: + 'deletion_protection': 'false' + oics_vars_overrides: + 'deletion_protection': 'false' + ignore_read_extra: + - 'autogenerate_revision_name' - name: 'cloud_run_service_noauth' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - test_env_vars: - project: 'PROJECT_NAME' + steps: + - name: 'cloud_run_service_noauth' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + test_env_vars: + project: 'PROJECT_NAME' - name: 'cloud_run_service_multiple_environment_variables' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - test_env_vars: - project: 'PROJECT_NAME' - ignore_read_extra: - - 'autogenerate_revision_name' - exclude_docs: true + exclude_basic_doc: true + steps: + - name: 'cloud_run_service_multiple_environment_variables' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + test_env_vars: + project: 'PROJECT_NAME' + ignore_read_extra: + - 'autogenerate_revision_name' - name: 'cloud_run_service_secret_environment_variables' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - secret_id: 'secret' - test_vars_overrides: - # for backward compatible - secret_id: '"secret" + randomSuffix' - test_env_vars: - project: 'PROJECT_NAME' - ignore_read_extra: - - 'autogenerate_revision_name' - exclude_docs: true + exclude_basic_doc: true + steps: + - name: 'cloud_run_service_secret_environment_variables' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + secret_id: 'secret' + test_vars_overrides: + # for backward compatible + secret_id: '"secret" + randomSuffix' + test_env_vars: + project: 'PROJECT_NAME' + ignore_read_extra: + - 'autogenerate_revision_name' - name: 'cloud_run_service_secret_volumes' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - secret_id: 'secret' - test_vars_overrides: - # for backward compatible - secret_id: '"secret" + randomSuffix' - test_env_vars: - project: 'PROJECT_NAME' - ignore_read_extra: - - 'autogenerate_revision_name' - exclude_docs: true + exclude_basic_doc: true + steps: + - name: 'cloud_run_service_secret_volumes' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + secret_id: 'secret' + test_vars_overrides: + # for backward compatible + secret_id: '"secret" + randomSuffix' + test_env_vars: + project: 'PROJECT_NAME' + ignore_read_extra: + - 'autogenerate_revision_name' - name: 'cloud_run_service_probes' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' + steps: + - name: 'cloud_run_service_probes' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' - name: 'cloud_run_service_readiness_probe' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv-rp' - test_env_vars: - project: 'PROJECT_NAME' + steps: + - name: 'cloud_run_service_readiness_probe' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv-rp' + test_env_vars: + project: 'PROJECT_NAME' - name: 'cloud_run_service_multicontainer' primary_resource_id: 'default' min_version: 'beta' - vars: - cloud_run_service_name: 'cloudrun-srv' - test_env_vars: - project: 'PROJECT_NAME' + steps: + - name: 'cloud_run_service_multicontainer' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + test_env_vars: + project: 'PROJECT_NAME' - name: 'cloud_run_service_iap' primary_resource_id: 'default' - vars: - cloud_run_service_name: 'cloudrun-srv' - test_env_vars: - project: 'PROJECT_NAME' + steps: + - name: 'cloud_run_service_iap' + resource_id_vars: + cloud_run_service_name: 'cloudrun-srv' + test_env_vars: + project: 'PROJECT_NAME' virtual_fields: - name: 'autogenerate_revision_name' description: | diff --git a/mmv1/products/colab/NotebookExecution.yaml b/mmv1/products/colab/NotebookExecution.yaml index 375400d569c2..516bec94e893 100644 --- a/mmv1/products/colab/NotebookExecution.yaml +++ b/mmv1/products/colab/NotebookExecution.yaml @@ -31,6 +31,7 @@ async: operation: import_format: - 'projects/{{project}}/locations/{{location}}/notebookExecutionJobs/{{notebook_execution_job_id}}' +include_in_tgc_next: true custom_code: post_create: 'templates/terraform/post_create/colab_notebook_execution.go.tmpl' examples: @@ -80,7 +81,7 @@ examples: project_id: 'PROJECT_NAME' service_account: 'SERVICE_ACCT' test_vars_overrides: - key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + key_name: 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible secret: '"secret" + randomSuffix' parameters: @@ -146,6 +147,7 @@ properties: required: true description: 'The base64-encoded contents of the input notebook file.' custom_flatten: 'templates/terraform/custom_flatten/colab_notebook_execution_direct_content.go.tmpl' + tgc_ignore_terraform_custom_flatten: true - name: executionTimeout type: String description: 'Max running time of the execution job in seconds (default 86400s / 24 hrs).' diff --git a/mmv1/products/colab/Runtime.yaml b/mmv1/products/colab/Runtime.yaml index 48af9f23987c..0c9160b7f5fb 100644 --- a/mmv1/products/colab/Runtime.yaml +++ b/mmv1/products/colab/Runtime.yaml @@ -53,7 +53,7 @@ examples: runtime_name: 'colab-runtime' key_name: 'my-crypto-key' test_vars_overrides: - key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + key_name: 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' ignore_read_extra: - 'desired_state' - 'auto_upgrade' diff --git a/mmv1/products/colab/RuntimeTemplate.yaml b/mmv1/products/colab/RuntimeTemplate.yaml index 9cf71c45743e..a35e641a57a7 100644 --- a/mmv1/products/colab/RuntimeTemplate.yaml +++ b/mmv1/products/colab/RuntimeTemplate.yaml @@ -43,6 +43,7 @@ iam_policy: - 'projects/{{project}}/locations/{{location}}/notebookRuntimeTemplates/{{runtime_template}}' - '{{runtime_template}}' include_in_tgc_next: true +custom_code: examples: - name: 'colab_runtime_template_basic' primary_resource_id: 'runtime-template' @@ -58,7 +59,7 @@ examples: network_name: 'colab-test-default' key_name: 'my-crypto-key' test_vars_overrides: - key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + key_name: 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' parameters: - name: 'location' type: String diff --git a/mmv1/products/colab/Schedule.yaml b/mmv1/products/colab/Schedule.yaml index a16dc6b9f3c4..a8d8db1a581f 100644 --- a/mmv1/products/colab/Schedule.yaml +++ b/mmv1/products/colab/Schedule.yaml @@ -80,7 +80,7 @@ examples: location: 'REGION' service_account: 'SERVICE_ACCT' test_vars_overrides: - key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + key_name: 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # Tests use a (relatively static) future date so that VCR cassettes can stay valid for a long time start_time: 'time.Date(time.Now().Year(), 12, 31, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, 1).Format(time.RFC3339)' end_time: 'time.Date(time.Now().Year(), 12, 31, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, 10).Format(time.RFC3339)' diff --git a/mmv1/products/compute/Address.yaml b/mmv1/products/compute/Address.yaml index 5608ec93911e..f63b63978a0b 100644 --- a/mmv1/products/compute/Address.yaml +++ b/mmv1/products/compute/Address.yaml @@ -79,7 +79,7 @@ examples: primary_resource_id: 'internal_with_shared_loadbalancer_vip' vars: address_name: 'my-internal-address' - # It is almost identical to internal_with_gce_endpoint + # It is almost identical to internal_with_gce_endpoint exclude_docs: true # TODO: Remove this example when instance is supported - name: 'instance_with_ip' diff --git a/mmv1/products/compute/Autoscaler.yaml b/mmv1/products/compute/Autoscaler.yaml index 8ca1a6398322..3c9c677262a6 100644 --- a/mmv1/products/compute/Autoscaler.yaml +++ b/mmv1/products/compute/Autoscaler.yaml @@ -57,8 +57,8 @@ examples: instance_template_name: 'my-instance-template' target_pool_name: 'my-target-pool' igm_name: 'my-igm' - # Add test_vars_overrides and oics_vars_overrides to fix the failing test, - # which is caused by upgradting terraform-plugin-sdk to 2.24.0. + # Add test_vars_overrides and oics_vars_overrides to fix the failing test, + # which is caused by upgradting terraform-plugin-sdk to 2.24.0. provider_name: 'google-beta' provider_alias: '' test_vars_overrides: @@ -153,6 +153,16 @@ properties: and time the startup process. api_name: coolDownPeriodSec default_value: 60 + - name: 'stabilizationPeriod' + type: Integer + description: | + The number of seconds that the autoscaler waits for load stabilization + before making scale-in decisions. + + This might appear as a delay in scaling in but it is an important mechanism + for your application to not have fluctuating size due to short term load + fluctuations. + api_name: stabilizationPeriodSec - name: 'mode' type: String description: | diff --git a/mmv1/products/compute/GlobalForwardingRule.yaml b/mmv1/products/compute/GlobalForwardingRule.yaml index dddf2b7d9891..e95a6139285a 100644 --- a/mmv1/products/compute/GlobalForwardingRule.yaml +++ b/mmv1/products/compute/GlobalForwardingRule.yaml @@ -430,10 +430,10 @@ properties: For Private Service Connect forwarding rules that forward traffic to Google APIs, a network must be provided. default_from_api: true - # TODO: When implementing new types enable converting the - # manifest input from a single value to a range of form NN-NN. The API - # accepts a single value, e.g. '80', but the API stores and returns - # '80-80'. This causes idempotency false positive. + # TODO: When implementing new types enable converting the + # manifest input from a single value to a range of form NN-NN. The API + # accepts a single value, e.g. '80', but the API stores and returns + # '80-80'. This causes idempotency false positive. custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl' resource: 'Network' imports: 'selfLink' diff --git a/mmv1/products/compute/HaVpnGateway.yaml b/mmv1/products/compute/HaVpnGateway.yaml index 01cb268c2a35..23a6d47c169b 100644 --- a/mmv1/products/compute/HaVpnGateway.yaml +++ b/mmv1/products/compute/HaVpnGateway.yaml @@ -77,7 +77,7 @@ examples: network2_name: '"network2" + randomSuffix' exclude_test: true exclude_docs: true - # Multiple fine-grained resources + # Multiple fine-grained resources skip_vcr: true - name: 'compute_ha_vpn_gateway_encrypted_interconnect' primary_resource_id: 'vpn-gateway' diff --git a/mmv1/products/compute/Image.yaml b/mmv1/products/compute/Image.yaml index fae50465cd4e..2a438ca9d7b4 100644 --- a/mmv1/products/compute/Image.yaml +++ b/mmv1/products/compute/Image.yaml @@ -152,6 +152,7 @@ properties: After you encrypt an image with a customer-supplied key, you must provide the same key if you use the image later (e.g. to create a disk from the image) + immutable: true properties: - name: 'kmsKeySelfLink' type: String @@ -283,6 +284,7 @@ properties: description: | The customer-supplied encryption key of the source disk. Required if the source disk is protected by a customer-supplied encryption key. + immutable: true properties: - name: 'rawKey' type: String @@ -333,6 +335,7 @@ properties: description: | The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key. + immutable: true properties: - name: 'rawKey' type: String @@ -456,6 +459,7 @@ properties: description: | The customer-supplied encryption key of the source snapshot. Required if the source snapshot is protected by a customer-supplied encryption key. + immutable: true properties: - name: 'rawKey' type: String diff --git a/mmv1/products/compute/Instance.yaml b/mmv1/products/compute/Instance.yaml index 193b3cc410dd..44408087682c 100644 --- a/mmv1/products/compute/Instance.yaml +++ b/mmv1/products/compute/Instance.yaml @@ -110,6 +110,7 @@ properties: description: | Encrypts or decrypts a disk using a customer-supplied encryption key. + immutable: true properties: - name: 'rawKey' type: String @@ -117,12 +118,14 @@ properties: Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. + sensitive: true - name: 'rsaEncryptedKey' type: String description: | Specifies an RFC 4648 base64 encoded, RSA-wrapped 2048-bit customer-supplied encryption key to either encrypt or decrypt this resource. + sensitive: true - name: 'sha256' type: String description: | @@ -210,6 +213,7 @@ properties: encryption keys, so you cannot create disks for instances in a managed instance group if the source images are encrypted with your own keys. + immutable: true properties: - name: 'rawKey' type: String @@ -217,6 +221,7 @@ properties: Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. + sensitive: true - name: 'sha256' type: String description: | @@ -495,6 +500,34 @@ properties: CIDR range for this alias IP range. If left unspecified, the primary range of the subnetwork will be used. + - name: 'aliasIpv6Ranges' + type: Array + description: | + An array of alias IPv6 ranges for this network interface. Can + only be specified for network interfaces on subnet-mode + networks. + min_version: beta + item_type: + type: NestedObject + properties: + - name: 'ipCidrRange' + type: String + description: | + The IP CIDR range represented by this alias IPv6 range. + This IP CIDR range must belong to the specified + subnetwork and cannot contain IP addresses reserved by + system or used by other network interfaces. This range + may be a single IP address (e.g. 2001:db8:1234:5678::), + a netmask (e.g. /96) or a CIDR format string + (e.g. 2001:db8:1234:5678::/96). + - name: 'subnetworkRangeName' + type: String + description: | + Optional subnetwork secondary range name specifying + the secondary range from which to allocate the IP + CIDR range for this alias IPv6 range. If left + unspecified, the primary range of the subnetwork will + be used. - name: 'internalIpv6PrefixLength' type: String description: | diff --git a/mmv1/products/compute/InstanceGroupManager.yaml b/mmv1/products/compute/InstanceGroupManager.yaml index 4720d32165c5..7901b86e3b62 100644 --- a/mmv1/products/compute/InstanceGroupManager.yaml +++ b/mmv1/products/compute/InstanceGroupManager.yaml @@ -164,7 +164,7 @@ properties: group. The group uses this template to create all new instances in the managed instance group. required: true - # kind is internal transport detail + # kind is internal transport detail custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl' resource: 'InstanceTemplate' imports: 'selfLink' diff --git a/mmv1/products/compute/MachineImage.yaml b/mmv1/products/compute/MachineImage.yaml index 4cb8dd122bf6..a382b07c0b2a 100644 --- a/mmv1/products/compute/MachineImage.yaml +++ b/mmv1/products/compute/MachineImage.yaml @@ -109,6 +109,7 @@ properties: provide the same key if you use the machine image later (e.g. to create a instance from the image) min_version: beta + immutable: true properties: - name: rawKey type: String @@ -116,6 +117,7 @@ properties: Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. min_version: beta + sensitive: true - name: sha256 type: String description: | diff --git a/mmv1/products/compute/ManagedSslCertificate.yaml b/mmv1/products/compute/ManagedSslCertificate.yaml index a31eaf52f343..e4976af4be64 100644 --- a/mmv1/products/compute/ManagedSslCertificate.yaml +++ b/mmv1/products/compute/ManagedSslCertificate.yaml @@ -46,8 +46,8 @@ immutable: true timeouts: insert_minutes: 30 update_minutes: 30 - # Deletes can take 20-30 minutes to complete, since they depend - # on the provisioning process either succeeding or failing completely. + # Deletes can take 20-30 minutes to complete, since they depend + # on the provisioning process either succeeding or failing completely. delete_minutes: 30 async: actions: ['create', 'delete', 'update'] @@ -83,7 +83,7 @@ examples: - name: 'managed_ssl_certificate_recreation' primary_resource_id: 'cert' external_providers: ["random", "time"] - # Random provider + # Random provider skip_vcr: true parameters: properties: diff --git a/mmv1/products/compute/NetworkEndpointGroup.yaml b/mmv1/products/compute/NetworkEndpointGroup.yaml index 55dcdfb51dee..bdd0818f9d3c 100644 --- a/mmv1/products/compute/NetworkEndpointGroup.yaml +++ b/mmv1/products/compute/NetworkEndpointGroup.yaml @@ -118,6 +118,7 @@ properties: - 'INTERNET_FQDN_PORT' - 'SERVERLESS' - 'PRIVATE_SERVICE_CONNECT' + - 'GCE_VM_IP_DEDICATED_BACKEND' - name: 'size' type: Integer description: Number of network endpoints in the network endpoint group. diff --git a/mmv1/products/compute/OrganizationSecurityPolicyAssociation.yaml b/mmv1/products/compute/OrganizationSecurityPolicyAssociation.yaml index ce773cfacfc1..1ac73f7aefa7 100644 --- a/mmv1/products/compute/OrganizationSecurityPolicyAssociation.yaml +++ b/mmv1/products/compute/OrganizationSecurityPolicyAssociation.yaml @@ -38,7 +38,7 @@ timeouts: custom_code: post_create: 'templates/terraform/post_create/org_security_policy_association.go.tmpl' post_delete: 'templates/terraform/post_create/org_security_policy_association.go.tmpl' - # TODO: Remove once b/154369201 is closed. + # TODO: Remove once b/154369201 is closed. test_check_destroy: 'templates/terraform/custom_check_destroy/skip_delete_during_test.go.tmpl' read_error_transform: 'transformSecurityPolicyAssociationReadError' examples: @@ -48,6 +48,12 @@ examples: short_name: "my-short-name" test_env_vars: org_id: 'ORG_TARGET' + - name: 'organization_security_policy_association_excluded' + primary_resource_id: 'policy' + vars: + short_name: "my-short-name-excluded" + test_env_vars: + org_id: 'ORG_TARGET' parameters: - name: 'policyId' type: String diff --git a/mmv1/products/compute/RegionAutoscaler.yaml b/mmv1/products/compute/RegionAutoscaler.yaml index 9c7c9f411f66..614a8c05ce20 100644 --- a/mmv1/products/compute/RegionAutoscaler.yaml +++ b/mmv1/products/compute/RegionAutoscaler.yaml @@ -132,6 +132,16 @@ properties: and time the startup process. api_name: coolDownPeriodSec default_value: 60 + - name: 'stabilizationPeriod' + type: Integer + description: | + The number of seconds that the autoscaler waits for load stabilization + before making scale-in decisions. + + This might appear as a delay in scaling in but it is an important mechanism + for your application to not have fluctuating size due to short term load + fluctuations. + api_name: stabilizationPeriodSec - name: 'mode' type: String description: | diff --git a/mmv1/products/compute/RegionBackendService.yaml b/mmv1/products/compute/RegionBackendService.yaml index 057fa35c3194..847a0f92a9d7 100644 --- a/mmv1/products/compute/RegionBackendService.yaml +++ b/mmv1/products/compute/RegionBackendService.yaml @@ -74,12 +74,6 @@ examples: primary_resource_id: 'default' vars: region_backend_service_name: 'tf-test-region-service-external' - - name: 'region_backend_service_cache' - primary_resource_id: 'default' - min_version: 'beta' - vars: - region_backend_service_name: 'region-service' - health_check_name: 'rbs-health-check' - name: 'region_backend_service_ilb_round_robin' primary_resource_id: 'default' vars: diff --git a/mmv1/products/compute/RegionInstanceGroupManager.yaml b/mmv1/products/compute/RegionInstanceGroupManager.yaml index 5037bc480c1c..1a0eb51bb389 100644 --- a/mmv1/products/compute/RegionInstanceGroupManager.yaml +++ b/mmv1/products/compute/RegionInstanceGroupManager.yaml @@ -169,7 +169,7 @@ properties: group. The group uses this template to create all new instances in the managed instance group. required: true - # kind is internal transport detail + # kind is internal transport detail custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl' resource: 'InstanceTemplate' imports: 'selfLink' diff --git a/mmv1/products/compute/RegionInstantSnapshot.yaml b/mmv1/products/compute/RegionInstantSnapshot.yaml index 0c1ff0340b92..88330bf48e60 100644 --- a/mmv1/products/compute/RegionInstantSnapshot.yaml +++ b/mmv1/products/compute/RegionInstantSnapshot.yaml @@ -52,6 +52,7 @@ sweeper: url_substitutions: - region: "us-central1" include_in_tgc_next: true +cai_resource_kind: InstantSnapshot examples: - name: 'region_instant_snapshot_basic' primary_resource_id: 'default' diff --git a/mmv1/products/compute/RegionSslCertificate.yaml b/mmv1/products/compute/RegionSslCertificate.yaml index ce09ff526c67..12da0a34f267 100644 --- a/mmv1/products/compute/RegionSslCertificate.yaml +++ b/mmv1/products/compute/RegionSslCertificate.yaml @@ -68,7 +68,7 @@ examples: - name: 'region_ssl_certificate_random_provider' primary_resource_id: 'default' external_providers: ["random", "time"] - # Uses id.UniqueId + # Uses id.UniqueId skip_vcr: true - name: 'region_ssl_certificate_target_https_proxies' primary_resource_id: 'default' diff --git a/mmv1/products/compute/RegionSslPolicy.yaml b/mmv1/products/compute/RegionSslPolicy.yaml index c4ed866b4ec3..ba2c6baa83ac 100644 --- a/mmv1/products/compute/RegionSslPolicy.yaml +++ b/mmv1/products/compute/RegionSslPolicy.yaml @@ -43,6 +43,15 @@ custom_code: constants: 'templates/terraform/constants/region_ssl_policy.tmpl' custom_diff: - 'regionSslPolicyCustomizeDiff' +examples: + - name: 'region_ssl_policy_basic' + primary_resource_id: 'region-ssl-policy' + vars: + region_ssl_policy_name: 'region-ssl-policy' + - name: 'region_ssl_policy_post_quantum' + primary_resource_id: 'post-quantum-region-ssl-policy' + vars: + post_quantum_region_ssl_policy_name: 'post-quantum-region-ssl-policy' parameters: - name: 'region' type: ResourceRef @@ -129,6 +138,22 @@ properties: send_empty_value: true item_type: type: String + - name: 'postQuantumKeyExchange' + type: Enum + description: | + One of `DEFAULT`, `ENABLED`, or `DEFERRED`. Controls whether the load balancer negotiates + X25519MLKEM768 key exchange when clients advertise support for it. + When set to `DEFAULT`, or if no SSL Policy is attached to + the target proxy, the load balancer disallows X25519MLKEM768 key + exchange before October 2026, and allows it afterward. When set to + `ENABLED`, the load balancer allows X25519MLKEM768 key + exchange. When set to `DEFERRED`, the load balancer + disallows X25519MLKEM768 key exchange until October 2027, and allows + it afterward. + enum_values: + - 'DEFAULT' + - 'ENABLED' + - 'DEFERRED' - name: 'fingerprint' type: Fingerprint description: | diff --git a/mmv1/products/compute/Router.yaml b/mmv1/products/compute/Router.yaml index 5f967cff60eb..99dcad90acb4 100644 --- a/mmv1/products/compute/Router.yaml +++ b/mmv1/products/compute/Router.yaml @@ -46,7 +46,7 @@ custom_diff: - 'resourceComputeRouterCustomDiff' sweeper: prefixes: - - "swg-autogen-router" # Secure Web Proxy(SWP) auto-generated router prefix. + - "swg-autogen-router" # Secure Web Proxy(SWP) auto-generated router prefix. url_substitutions: - region: "us-central1" - region: "us-east1" @@ -125,13 +125,13 @@ properties: description: | A reference to the network to which this router belongs. immutable: true - # TODO: Figure out the story for interfaces/bgpPeers. Right - # now in Terraform we have three separate resources: router, - # router_interface, and router_peer. Decide whether we want to keep that - # pattern for the other providers, keep it unique for Terraform, or add - # these fields to the Terraform resource (and then within that, decide - # whether to deprecate router_interface and router_peer or leave them - # alone). + # TODO: Figure out the story for interfaces/bgpPeers. Right + # now in Terraform we have three separate resources: router, + # router_interface, and router_peer. Decide whether we want to keep that + # pattern for the other providers, keep it unique for Terraform, or add + # these fields to the Terraform resource (and then within that, decide + # whether to deprecate router_interface and router_peer or leave them + # alone). custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl' resource: 'Network' imports: 'selfLink' @@ -172,7 +172,7 @@ properties: This enum field has the one valid value: ALL_SUBNETS send_empty_value: true - # TODO: #324 enum? + # TODO: #324 enum? item_type: type: String - name: 'advertisedIpRanges' diff --git a/mmv1/products/compute/SecurityPolicyRule.yaml b/mmv1/products/compute/SecurityPolicyRule.yaml index 18874b47d1ed..5d3f9f3ddd0c 100644 --- a/mmv1/products/compute/SecurityPolicyRule.yaml +++ b/mmv1/products/compute/SecurityPolicyRule.yaml @@ -81,6 +81,7 @@ examples: vars: sec_policy_name: 'policyruletest' backend_name: 'backendpolicy' + network_name: 'test-network' test_vars_overrides: # for backward compatible sec_policy_name: '"policyruletest" + randomSuffix' @@ -129,19 +130,19 @@ properties: description: | Textual representation of an expression in Common Expression Language syntax. The application context of the containing message determines which well-known feature set of CEL is supported. required: true - # >> These fields are not yet supported, following the global security policy resource. - # name: 'title' - # type: String - # description: | - # Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression. - # name: 'description' - # type: String - # description: | - # Optional. Description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI. - # name: 'location' - # type: String - # description: | - # Optional. String indicating the location of the expression for error reporting, e.g. a file name and a position in the file. + # >> These fields are not yet supported, following the global security policy resource. + # name: 'title' + # type: String + # description: | + # Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression. + # name: 'description' + # type: String + # description: | + # Optional. Description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI. + # name: 'location' + # type: String + # description: | + # Optional. String indicating the location of the expression for error reporting, e.g. a file name and a position in the file. - name: 'exprOptions' type: NestedObject description: | diff --git a/mmv1/products/compute/ServiceAttachment.yaml b/mmv1/products/compute/ServiceAttachment.yaml index 172592950f9b..b455f6a4ac9e 100644 --- a/mmv1/products/compute/ServiceAttachment.yaml +++ b/mmv1/products/compute/ServiceAttachment.yaml @@ -280,7 +280,7 @@ properties: An array of projects that are not allowed to connect to this service attachment. send_empty_value: true - is_missing_in_cai: true # Ignored in TGC tests due to timing issues in CAI updates where the field disappears in intermediate steps. + is_missing_in_cai: true # Ignored in TGC tests due to timing issues in CAI updates where the field disappears in intermediate steps. item_type: type: String - name: 'consumerAcceptLists' diff --git a/mmv1/products/compute/Snapshot.yaml b/mmv1/products/compute/Snapshot.yaml index 7ebc4b6f4280..2f1a66d7250b 100644 --- a/mmv1/products/compute/Snapshot.yaml +++ b/mmv1/products/compute/Snapshot.yaml @@ -113,6 +113,7 @@ parameters: If you do not provide an encryption key when creating the snapshot, then the snapshot will be encrypted using an automatically generated key and you do not need to provide a key to use the snapshot later. + immutable: true properties: - name: 'rawKey' type: String @@ -154,6 +155,7 @@ parameters: if the source snapshot is protected by a customer-supplied encryption key. ignore_read: true + immutable: true properties: - name: 'rawKey' type: String diff --git a/mmv1/products/compute/SslCertificate.yaml b/mmv1/products/compute/SslCertificate.yaml index 8121066ee530..c6ef0df22c08 100644 --- a/mmv1/products/compute/SslCertificate.yaml +++ b/mmv1/products/compute/SslCertificate.yaml @@ -66,7 +66,7 @@ examples: - name: 'ssl_certificate_random_provider' primary_resource_id: 'default' external_providers: ["random", "time"] - # Uses id.UniqueId + # Uses id.UniqueId skip_vcr: true - name: 'ssl_certificate_target_https_proxies' primary_resource_id: 'default' diff --git a/mmv1/products/compute/SslPolicy.yaml b/mmv1/products/compute/SslPolicy.yaml index 64954449e8c1..2a788246cefa 100644 --- a/mmv1/products/compute/SslPolicy.yaml +++ b/mmv1/products/compute/SslPolicy.yaml @@ -50,6 +50,10 @@ examples: production_ssl_policy_name: 'production-ssl-policy' nonprod_ssl_policy_name: 'nonprod-ssl-policy' custom_ssl_policy_name: 'custom-ssl-policy' + - name: 'ssl_policy_post_quantum' + primary_resource_id: 'post-quantum-ssl-policy' + vars: + post_quantum_ssl_policy_name: 'post-quantum-ssl-policy' parameters: properties: - name: 'creationTimestamp' @@ -128,6 +132,22 @@ properties: is_set: true item_type: type: String + - name: 'postQuantumKeyExchange' + type: Enum + description: | + One of `DEFAULT`, `ENABLED`, or `DEFERRED`. Controls whether the load balancer + negotiates X25519MLKEM768 key exchange when clients advertise support for it. + When set to `DEFAULT`, or if no SSL Policy is attached to + the target proxy, the load balancer disallows X25519MLKEM768 key + exchange before October 2026, and allows it afterward. When set to + `ENABLED`, the load balancer allows X25519MLKEM768 key + exchange. When set to `DEFERRED`, the load balancer + disallows X25519MLKEM768 key exchange until October 2027, and allows + it afterward. + enum_values: + - 'DEFAULT' + - 'ENABLED' + - 'DEFERRED' - name: 'fingerprint' type: String description: | diff --git a/mmv1/products/compute/Subnetwork.yaml b/mmv1/products/compute/Subnetwork.yaml index 9b6e49de488b..d02827a9799e 100644 --- a/mmv1/products/compute/Subnetwork.yaml +++ b/mmv1/products/compute/Subnetwork.yaml @@ -44,6 +44,7 @@ references: base_url: projects/{{project}}/regions/{{region}}/subnetworks immutable: true has_self_link: true +bypass_clientside_update_check: true collection_url_key: items iam_policy: allowed_iam_role: roles/compute.networkUser @@ -55,6 +56,7 @@ id_format: projects/{{project}}/regions/{{region}}/subnetworks/{{name}} custom_diff: - customdiff.ForceNewIfChange("ip_cidr_range", IsShrinkageIpCidr) - sendSecondaryIpRangeIfEmptyDiff + - resourceComputeSubnetworkSecondaryIpRangeCustomDiff sweeper: url_substitutions: - region: us-west2 @@ -174,6 +176,15 @@ examples: vars: network_name: network-ipv6-only subnetwork_name: subnet-ipv6-only + - name: subnetwork_with_secondary_ipv6_range + primary_resource_id: subnetwork_with_secondary_ipv6_range + vars: + network_name: network-with-secondary-ranges + subnetwork_name: subnet-with-secondary-ranges + pap_name: pap-for-secondary-ranges + pdp_name: pdp-for-secondary-ranges + sub_pdp_name: sub-pdp-for-secondary-ranges + min_version: 'beta' virtual_fields: - name: send_secondary_ip_range_if_empty type: Boolean @@ -333,6 +344,25 @@ properties: E.g. `networkconnectivity.googleapis.com/projects/{project}/locations/global/internalRanges/{rangeId}` resource: InternalRange imports: selfLink + - name: ipVersion + type: Enum + description: | + The IP version of the secondary range. If not specified, IPV4 is used. + default_from_api: true + min_version: 'beta' + enum_values: + - IPV4 + - IPV6 + - name: ipCollection + type: ResourceRef + description: | + Reference to a Public Delegated Prefix (PDP) for BYOIP. + This field should be specified for configuring BYOGUA internal IPv6 secondary range. + When specified along with the ip_cidr_range, the ip_cidr_range must lie within the PDP referenced by the `ipCollection` field. + When specified without the ip_cidr_range, the range is auto-allocated from the PDP referenced by the `ipCollection` field. + min_version: 'beta' + resource: PublicDelegatedPrefix + imports: selfLink - name: privateIpGoogleAccess type: Boolean description: | @@ -563,3 +593,5 @@ properties: enum_values: - ARP_ALL_RANGES - ARP_PRIMARY_RANGE + - ARP_BROADCAST_PRIMARY_RANGE + - ARP_BROADCAST_PRIMARY_RANGE_WITH_LEARNING diff --git a/mmv1/products/compute/UrlMap.yaml b/mmv1/products/compute/UrlMap.yaml index 6496942a65e8..fc46f1aa8f67 100644 --- a/mmv1/products/compute/UrlMap.yaml +++ b/mmv1/products/compute/UrlMap.yaml @@ -256,7 +256,7 @@ examples: ignore_read_extra: - 'metadata' - 'metadata_startup_script' - # Very similar to external_http_lb_mig_backend_custom_header + # Very similar to external_http_lb_mig_backend_custom_header exclude_test: true exclude_docs: true - name: 'url_map_path_template_match' diff --git a/mmv1/products/config/Deployment.yaml b/mmv1/products/config/Deployment.yaml new file mode 100644 index 000000000000..b88ef69f71dd --- /dev/null +++ b/mmv1/products/config/Deployment.yaml @@ -0,0 +1,156 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: 'Deployment' +description: | + A group of Google Cloud resources described by a Terraform blueprint. +references: + api: 'https://cloud.google.com/infrastructure-manager/docs/reference/rest/v1/projects.locations.deployments' +docs: +id_format: 'projects/{{project}}/locations/{{location}}/deployments/{{name}}' +base_url: 'projects/{{project}}/locations/{{location}}/deployments' +self_link: 'projects/{{project}}/locations/{{location}}/deployments/{{name}}' +create_url: 'projects/{{project}}/locations/{{location}}/deployments?deploymentId={{name}}' +update_verb: 'PATCH' +update_mask: true +import_format: + - 'projects/{{project}}/locations/{{location}}/deployments/{{name}}' +delete_url: 'projects/{{project}}/locations/{{location}}/deployments/{{name}}?force={{force_destroy}}' +timeouts: + insert_minutes: 20 + update_minutes: 20 + delete_minutes: 20 +autogen_async: true +async: + actions: ['create', 'delete', 'update'] + type: 'OpAsync' + operation: + base_url: '{{op_id}}' + result: + resource_inside_response: false + +virtual_fields: + - name: 'force_destroy' + type: Boolean + default_value: false + description: "If true, deletes the deployment and its nested resources." + +examples: + - name: 'config_deployment_basic' + primary_resource_id: 'default' + exclude_test: true # Acceptance tests are handwritten in resource_config_deployment_test.go due to complex prerequisites (IAM, fixtures). + vars: + deployment_name: 'my-deployment' + service_account_email: 'my-service-account@my-project.iam.gserviceaccount.com' + +parameters: + - name: 'location' + type: String + description: "The location for the resource" + url_param_only: true + required: true + immutable: true + +properties: + - name: 'name' + type: String + description: "The user-specified ID of the deployment." + url_param_only: true + required: true + immutable: true + + - name: 'serviceAccount' + type: String + description: "Required. User-specified Service Account (SA) credentials to be used when actuating resources." + required: true + + - name: 'terraformBlueprint' + type: NestedObject + description: "A bundle of HCL files in a GCS bucket or Git repo." + required: true + properties: + - name: 'gcsSource' + type: String + description: "URI of a GCS object containing the zipped Terraform blueprint." + exactly_one_of: ['gcsSource', 'gitSource'] + - name: 'gitSource' + type: NestedObject + description: "Public Git repository containing the blueprint." + exactly_one_of: ['gcsSource', 'gitSource'] + properties: + - name: 'repo' + type: String + description: "Repository URL." + required: true + - name: 'directory' + type: String + description: "Subdirectory within the repo." + - name: 'ref' + type: String + description: "Git reference (branch or tag)." + - name: 'inputValues' + type: Map + description: "Input variables for the Terraform blueprint." + key_name: 'variable_name' + value_type: + type: NestedObject + properties: + - name: 'inputValue' + type: String + description: "The value of the variable." + required: true + custom_expand: 'templates/terraform/custom_expand/config_input_value.go.tmpl' + custom_flatten: 'templates/terraform/custom_flatten/config_input_value.go.tmpl' + + - name: 'labels' + type: KeyValueLabels + description: "Optional. User-defined metadata for the deployment." + + - name: 'annotations' + type: KeyValueAnnotations + description: "Optional. Arbitrary key-value metadata storage." + + - name: 'tfVersionConstraint' + type: String + description: "Optional constraint on the Terraform version." + + - name: 'artifactsGcsBucket' + type: String + description: "Location for Cloud Build logs and artifacts." + + - name: 'workerPool' + type: String + description: "Custom Cloud Build worker pool resource name." + + - name: 'importExistingResources' + type: Boolean + description: "If true, attempts to automatically import resources on 409 conflict." + + - name: 'quotaValidation' + type: Enum + description: "Controls quota checks." + enum_values: + - 'ENABLED' + - 'ENFORCED' + + # Output only fields + - name: 'state' + type: String + description: "Output only. Current state of the deployment." + output: true + + - name: 'latestRevision' + type: String + description: "Output only. Revision name most recently applied." + output: true diff --git a/tpgtools/api/recaptchaenterprise/samples/minimal_key.yaml b/mmv1/products/config/product.yaml old mode 100755 new mode 100644 similarity index 70% rename from tpgtools/api/recaptchaenterprise/samples/minimal_key.yaml rename to mmv1/products/config/product.yaml index a86566d55267..3032abbb8a8f --- a/tpgtools/api/recaptchaenterprise/samples/minimal_key.yaml +++ b/mmv1/products/config/product.yaml @@ -1,23 +1,21 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# +# Copyright 2026 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -name: minimal_key -description: A minimal test of recaptcha enterprise key -type: key + +--- +name: 'Config' +display_name: 'Infrastructure Manager' versions: -- ga -- beta -resource: samples/minimal.key.json -variables: -- name: project - type: project + - name: 'ga' + base_url: 'https://config.googleapis.com/v1/' +scopes: + - 'https://www.googleapis.com/auth/cloud-platform' diff --git a/mmv1/products/contactcenterinsights/EncryptionSpec.yaml b/mmv1/products/contactcenterinsights/EncryptionSpec.yaml new file mode 100644 index 000000000000..3aaef469b7d9 --- /dev/null +++ b/mmv1/products/contactcenterinsights/EncryptionSpec.yaml @@ -0,0 +1,73 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: 'EncryptionSpec' +description: | + Initializes a location-level encryption key specification. +references: + guides: + 'Official Documentation': 'https://docs.cloud.google.com/contact-center/insights/docs/cmek' + api: 'https://docs.cloud.google.com/contact-center/insights/docs/reference/rest/v1/projects.locations.encryptionSpec' + +base_url: 'projects/{{project}}/locations/{{location}}/encryptionSpec' +self_link: 'projects/{{project}}/locations/{{location}}/encryptionSpec' + +create_url: 'projects/{{project}}/locations/{{location}}/encryptionSpec:initialize' + +exclude_delete: true +immutable: true + +async: + actions: ['create'] + operation: + base_url: '{{op_id}}' + +custom_code: + pre_create: 'templates/terraform/pre_create/contactcenterinsights_encryption_spec_pre_create.go.tmpl' + pre_read: 'templates/terraform/pre_create/contactcenterinsights_set_endpoint.go.tmpl' + +parameters: + - name: 'location' + type: String + required: true + ignore_read: true + url_param_only: true + description: | + The location in which the encryptionSpec is to be initialized. + +properties: + - name: 'kmsKey' + type: String + required: true + immutable: true + description: | + The name of customer-managed encryption key that is used to secure a resource and its sub-resources. + If empty, the resource is secured by the default Google encryption key. + Only the key in the same location as this resource is allowed to be used for encryption. + Format: projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{key} + +examples: + - name: "contact_center_insights_encryption_spec_basic" + primary_resource_id: "my-encryption-spec" + min_version: "beta" + exclude_import_test: true + vars: + project_id: 'my-proj' + kms_keyring: 'my-keyring' + kms_key: 'my-key' + test_env_vars: + org_id: 'ORG_ID' + billing_acct: 'BILLING_ACCT' + external_providers: + - "time" diff --git a/mmv1/products/container/Cluster.yaml b/mmv1/products/container/Cluster.yaml index 998305868941..52f1cc480556 100644 --- a/mmv1/products/container/Cluster.yaml +++ b/mmv1/products/container/Cluster.yaml @@ -68,6 +68,79 @@ properties: - name: 'gpuDriverVersion' type: 'String' description: 'Mode for how the GPU driver is installed.' + - name: 'taint' + type: 'Array' + api_name: 'taints' + description: 'Taints to be applied to nodes in the pool.' + ignore_read: true + item_type: + type: 'NestedObject' + properties: + - name: 'key' + type: 'String' + description: 'The key of the taint.' + ignore_read: true + - name: 'value' + type: 'String' + description: 'The value of the taint.' + ignore_read: true + - name: 'effect' + type: 'String' + description: 'The effect of the taint.' + ignore_read: true + - name: 'nodeConfig' + type: 'NestedObject' + description: 'Configuration for the nodes in the pool.' + properties: + - name: 'guest_accelerator' + type: 'Array' + api_name: 'accelerators' + description: 'A list of hardware accelerators to be attached to each node.' + ignore_read: true + item_type: + type: 'NestedObject' + properties: + - name: 'count' + type: 'Integer' + description: 'The number of the accelerator cards exposed to an instance.' + ignore_read: true + - name: 'type' + type: 'String' + description: 'The accelerator type resource to expose to this instance. E.g. nvidia-tesla-k80.' + ignore_read: true + - name: 'gpuPartitionSize' + type: 'String' + description: 'Size of partitions to create on the GPU. Supported values are described in the NVIDIA mig user guide.' + ignore_read: true + - name: 'gpuDriverInstallationConfig' + type: 'NestedObject' + description: 'Configuration for GPU driver installation.' + ignore_read: true + properties: + - name: 'gpuDriverVersion' + type: 'String' + description: 'Mode for how the GPU driver is installed.' + - name: 'taint' + type: 'Array' + api_name: 'taints' + description: 'Taints to be applied to nodes in the pool.' + ignore_read: true + item_type: + type: 'NestedObject' + properties: + - name: 'key' + type: 'String' + description: 'The key of the taint.' + ignore_read: true + - name: 'value' + type: 'String' + description: 'The value of the taint.' + ignore_read: true + - name: 'effect' + type: 'String' + description: 'The effect of the taint.' + ignore_read: true + - name: 'ipAllocationPolicy' type: 'NestedObject' properties: @@ -94,6 +167,12 @@ properties: type: 'String' description: 'The selected network policy provider.' is_missing_in_cai: true + - name: minMasterVersion + type: String + ignore_read: true + - name: nodeVersion + type: String + ignore_read: true tgc_tests: - name: TestAccContainerCluster_withDatabaseEncryption skip: Bug in the API, https://github.com/hashicorp/terraform-provider-google/issues/26882 diff --git a/mmv1/products/container/NodePool.yaml b/mmv1/products/container/NodePool.yaml index 07a7742e266e..95a0a70aa5c0 100644 --- a/mmv1/products/container/NodePool.yaml +++ b/mmv1/products/container/NodePool.yaml @@ -31,10 +31,14 @@ properties: type: 'Integer' description: 'The initial node count for the pool.' ignore_read: true - - name: 'NamePrefix' + - name: 'namePrefix' type: 'String' description: 'The prefix of the node pool name.' ignore_read: true + - name: 'version' + type: 'String' + description: 'The version of the node pool.' + ignore_read: true - name: 'nodeConfig' type: 'NestedObject' description: 'Configuration for the nodes in the pool.' @@ -91,6 +95,26 @@ properties: type: 'Boolean' description: 'Enable PTP KVM time sync.' is_missing_in_cai: true + - name: 'taint' + type: 'Array' + api_name: 'taints' + description: 'Taints to be applied to nodes in the pool.' + ignore_read: true + item_type: + type: 'NestedObject' + properties: + - name: 'key' + type: 'String' + description: 'The key of the taint.' + ignore_read: true + - name: 'value' + type: 'String' + description: 'The value of the taint.' + ignore_read: true + - name: 'effect' + type: 'String' + description: 'The effect of the taint.' + ignore_read: true - name: 'networkConfig' type: 'NestedObject' description: 'Networking configuration for this NodePool.' diff --git a/mmv1/products/containerattached/Cluster.yaml b/mmv1/products/containerattached/Cluster.yaml index e93a3c8a045c..1af4ac423bc8 100644 --- a/mmv1/products/containerattached/Cluster.yaml +++ b/mmv1/products/containerattached/Cluster.yaml @@ -45,6 +45,7 @@ custom_code: constants: 'templates/terraform/constants/containerattached_cluster_diff.go.tmpl' pre_update: 'templates/terraform/pre_update/containerattached_update.go.tmpl' pre_delete: 'templates/terraform/pre_delete/container_attached_deletion_policy.go.tmpl' +deletion_policy_custom_docs: true examples: - name: 'container_attached_cluster_basic' primary_resource_id: 'primary' @@ -71,9 +72,18 @@ examples: - 'deletion_policy' virtual_fields: - name: 'deletion_policy' - description: 'Policy to determine what flags to send on delete. Possible values: DELETE, DELETE_IGNORE_ERRORS' + description: | + Policy to determine what flags to send on delete. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + + Possible values: DELETE, DELETE_IGNORE_ERRORS, PREVENT, ABANDON'. Defaults to 'DELETE'. type: String - default_value: "DELETE" + # excluded from generation due to Universal Deletion Policy + exclude: true parameters: properties: - name: 'location' diff --git a/mmv1/products/databasemigrationservice/ConnectionProfile.yaml b/mmv1/products/databasemigrationservice/ConnectionProfile.yaml index dad36c97ad2a..cc3a7c2a905d 100644 --- a/mmv1/products/databasemigrationservice/ConnectionProfile.yaml +++ b/mmv1/products/databasemigrationservice/ConnectionProfile.yaml @@ -201,6 +201,14 @@ properties: - RDS - AURORA - ALLOYDB + - name: role + type: Enum + description: | + The connection profile role. + default_from_api: true + enum_values: + - SOURCE + - DESTINATION - name: mysql type: NestedObject description: | @@ -287,7 +295,7 @@ properties: - name: cloudSqlId type: String description: | - If the source is a Cloud SQL database, use this field to provide the Cloud SQL instance ID of the source. + If the connection profile is a Cloud SQL database, use this field to provide the Cloud SQL instance ID. - name: postgresql type: NestedObject description: | @@ -305,23 +313,17 @@ properties: The IP or hostname of the source MySQL database. required_with: - postgresql.0.port - - postgresql.0.username - - postgresql.0.password - name: port type: Integer description: | The network port of the source MySQL database. required_with: - postgresql.0.host - - postgresql.0.username - - postgresql.0.password - name: username type: String description: | The username that Database Migration Service will use to connect to the database. The value is encrypted when stored in Database Migration Service. required_with: - - postgresql.0.host - - postgresql.0.port - postgresql.0.password - name: password type: String @@ -329,17 +331,20 @@ properties: Input only. The password for the user that Database Migration Service will be using to connect to the database. This field is not returned on request, and the value is encrypted when stored in Database Migration Service. immutable: true - required_with: - - postgresql.0.host - - postgresql.0.port - - postgresql.0.username sensitive: true custom_flatten: templates/terraform/custom_flatten/database_migration_service_connection_profile_postgresql_password.go.tmpl + required_with: + - postgresql.0.username - name: passwordSet type: Boolean description: | Output only. Indicates If this connection profile password is stored. output: true + - name: database + type: String + description: | + The name of the specific database within the host. + default_from_api: true - name: ssl type: NestedObject description: | @@ -385,11 +390,11 @@ properties: - name: cloudSqlId type: String description: | - If the source is a Cloud SQL database, use this field to provide the Cloud SQL instance ID of the source. + If the connection profile is a Cloud SQL database, use this field to provide the Cloud SQL instance ID. - name: alloydbClusterId type: String description: | - If the connected database is an AlloyDB instance, use this field to provide the AlloyDB cluster ID. + If the connection profile is an AlloyDB instance, use this field to provide the AlloyDB cluster ID. - name: networkArchitecture type: Enum description: | @@ -398,6 +403,16 @@ properties: enum_values: - NETWORK_ARCHITECTURE_OLD_CSQL_PRODUCER - NETWORK_ARCHITECTURE_NEW_CSQL_PRODUCER + - name: privateConnectivity + type: NestedObject + description: | + Private connectivity. + properties: + - name: privateConnection + type: String + required: true + description: | + Required. The resource name (URI) of the private connection. - name: oracle type: NestedObject description: | diff --git a/mmv1/products/databasemigrationservice/MigrationJob.yaml b/mmv1/products/databasemigrationservice/MigrationJob.yaml index cf5c1aa3beb3..63bfdc1d3968 100644 --- a/mmv1/products/databasemigrationservice/MigrationJob.yaml +++ b/mmv1/products/databasemigrationservice/MigrationJob.yaml @@ -246,6 +246,20 @@ properties: - MIN - OPTIMAL - MAX + - name: postgresHomogeneousConfig + type: NestedObject + description: | + PostgreSQL to PostgreSQL configuration. + properties: + - name: isNativeLogical + type: Boolean + required: true + description: | + Whether the migration uses native logical replication. + - name: maxAdditionalSubscriptions + type: Integer + description: | + Maximum number of additional subscriptions to use for the migration job. - name: dumpPath type: String description: | @@ -269,7 +283,7 @@ properties: Cloud SQL console or using Cloud SQL APIs. send_empty_value: true allow_empty_object: true - exactly_one_of: + conflicts: - reverseSshConnectivity - vpcPeeringConnectivity properties: [] @@ -277,7 +291,7 @@ properties: type: NestedObject description: | The details of the VPC network that the source database is located in. - exactly_one_of: + conflicts: - staticIpConnectivity - vpcPeeringConnectivity properties: @@ -304,7 +318,7 @@ properties: type: NestedObject description: | The details of the VPC network that the source database is located in. - exactly_one_of: + conflicts: - staticIpConnectivity - reverseSshConnectivity properties: diff --git a/mmv1/products/databasemigrationservice/PrivateConnection.yaml b/mmv1/products/databasemigrationservice/PrivateConnection.yaml index 8fe217d1486b..547a0b775d60 100644 --- a/mmv1/products/databasemigrationservice/PrivateConnection.yaml +++ b/mmv1/products/databasemigrationservice/PrivateConnection.yaml @@ -33,9 +33,12 @@ timeouts: delete_minutes: 60 autogen_async: true async: - actions: ['create', 'delete', 'update'] + actions: ['create', 'delete'] type: 'OpAsync' operation: + timeouts: + insert_minutes: 60 + delete_minutes: 60 base_url: '{{op_id}}' result: resource_inside_response: false @@ -50,6 +53,23 @@ examples: test_vars_overrides: # for backward compatible create_without_validation: '"false" + randomSuffix' + network_name: '"my-network" + randomSuffix' + private_connection_id: '"my-connection" + randomSuffix' + - name: 'database_migration_service_private_connection_psc' + primary_resource_id: 'default' + vars: + private_connection_id: 'my-connection' + attachment_name: 'my-attachment' + create_without_validation: 'false' + network_name: 'my-network' + subnetwork_name: 'my-subnetwork' + test_vars_overrides: + # for backward compatible + create_without_validation: '"false" + randomSuffix' + attachment_name: '"my-attachment" + randomSuffix' + private_connection_id: '"my-connection" + randomSuffix' + network_name: '"my-network" + randomSuffix' + subnetwork_name: '"my-subnetwork" + randomSuffix' parameters: - name: 'privateConnectionId' type: String @@ -109,7 +129,8 @@ properties: description: | The VPC Peering configuration is used to create VPC peering between databasemigrationservice and the consumer's VPC. - required: true + exactly_one_of: + - 'pscInterfaceConfig' properties: - name: 'vpcName' type: String @@ -122,3 +143,17 @@ properties: description: | A free subnet for peering. (CIDR of /29) required: true + - name: 'pscInterfaceConfig' + type: NestedObject + description: | + The PSC Interface configuration is used to create PSC Interface + between DMS's internal VPC and the consumer's PSC. + exactly_one_of: + - 'vpcPeeringConfig' + properties: + - name: 'networkAttachment' + type: String + description: | + Fully qualified name of the Network Attachment that DMS will connect to. + Format: projects/{project}/regions/{region}/networkAttachments/{name} + required: true diff --git a/mmv1/products/datacatalog/Tag.yaml b/mmv1/products/datacatalog/Tag.yaml index 809c03405deb..6ae9254e2a36 100644 --- a/mmv1/products/datacatalog/Tag.yaml +++ b/mmv1/products/datacatalog/Tag.yaml @@ -98,7 +98,7 @@ examples: 'force_delete': 'true' oics_vars_overrides: 'force_delete': 'true' - # omitting doc as it is almost identical to the case of data_catalog_entry_tag_basic + # omitting doc as it is almost identical to the case of data_catalog_entry_tag_basic exclude_docs: true parameters: - name: 'parent' diff --git a/mmv1/products/dataform/Repository.yaml b/mmv1/products/dataform/Repository.yaml index 2e727e26363d..eb38e451ac43 100644 --- a/mmv1/products/dataform/Repository.yaml +++ b/mmv1/products/dataform/Repository.yaml @@ -37,6 +37,7 @@ iam_policy: min_version: 'beta' custom_code: pre_delete: 'templates/terraform/pre_delete/dataform_repository.go.tmpl' +deletion_policy_custom_docs: true examples: - name: 'dataform_repository' primary_resource_id: 'dataform_repository' @@ -92,11 +93,17 @@ virtual_fields: - name: 'deletion_policy' type: Enum description: | - Policy to control how the repository and its child resources are deleted. When set to `FORCE`, any child resources of this repository will also be deleted. Possible values: `DELETE`, `FORCE`. Defaults to `DELETE`. - default_value: 'DELETE' - enum_values: - - 'DELETE' - - 'FORCE' + Policy to control how the repository and its child resources are deleted. + When set to `FORCE`, any child resources of this repository will also be deleted. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + + Possible values: `DELETE`, `FORCE`, 'PREVENT', 'ABANDON'. Defaults to `DELETE`. + # excluded from generation due to Universal Deletion Policy + exclude: true parameters: - name: 'region' type: String diff --git a/mmv1/products/datafusion/Instance.yaml b/mmv1/products/datafusion/Instance.yaml index 4b9f7853b08c..1653ca4f3b48 100644 --- a/mmv1/products/datafusion/Instance.yaml +++ b/mmv1/products/datafusion/Instance.yaml @@ -396,6 +396,72 @@ properties: enum_values: - 'ENABLED' - 'DISABLED' + - name: 'maintenancePolicy' + type: NestedObject + description: | + Configure the maintenance policy for this instance. + properties: + - name: 'maintenanceWindow' + type: NestedObject + description: | + The maintenance window of the instance. + properties: + - name: 'recurringTimeWindow' + type: NestedObject + description: | + The recurring time window of the maintenance window. + required: true + properties: + - name: 'window' + type: NestedObject + description: | + The window representing the start and end time of recurrences. This field ignores the date components of the provided timestamps. Only the time of day and duration between start and end time are relevant. + required: true + properties: + - name: 'startTime' + type: String + description: | + The start time of the time window provided in RFC 3339 format. + required: true + - name: 'endTime' + type: String + description: | + The end time of the time window provided in RFC 3339 format. + required: true + - name: 'recurrence' + type: String + description: | + An RRULE with format RFC-5545 for how this window reccurs. They go on for the span of time between the start and end time. The only supported FREQ value is "WEEKLY". To have something repeat every weekday, use: "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR". + required: true + + - name: 'maintenanceEvents' + type: Array + description: | + The maintenance events for this instance. + output: true + item_type: + type: NestedObject + properties: + - name: 'startTime' + type: String + description: | + The start time of the maintenance event provided in RFC 3339 format. + output: true + - name: 'endTime' + type: String + description: | + The end time of the maintenance event provided in RFC 3339 format. + output: true + - name: 'state' + type: Enum + description: | + The state of the maintenance event. + output: true + enum_values: + - 'STATE_UNSPECIFIED' + - 'SCHEDULED' + - 'STARTED' + - 'COMPLETED' - name: 'tags' type: KeyValuePairs description: | diff --git a/mmv1/products/datalineage/Config.yaml b/mmv1/products/datalineage/Config.yaml index ad5e654671db..5a0971c64896 100644 --- a/mmv1/products/datalineage/Config.yaml +++ b/mmv1/products/datalineage/Config.yaml @@ -47,7 +47,8 @@ examples: - name: 'data_lineage_config_project' primary_resource_id: 'default' test_env_vars: - project: 'PROJECT_NAME' + org_id: 'ORG_ID' + external_providers: ["time"] - name: 'data_lineage_config_folder' primary_resource_id: 'default' vars: diff --git a/mmv1/products/dataplex/Glossary.yaml b/mmv1/products/dataplex/Glossary.yaml index 2f160f372368..825d7b2eb060 100644 --- a/mmv1/products/dataplex/Glossary.yaml +++ b/mmv1/products/dataplex/Glossary.yaml @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +--- name: 'Glossary' description: | Represents a collection of categories and terms defined by the user. Glossary is a top level resource and is the GCP parent resource of all the categories and terms within it. diff --git a/mmv1/products/dataplex/GlossaryCategory.yaml b/mmv1/products/dataplex/GlossaryCategory.yaml index eda13276c32e..574f0aab78b3 100644 --- a/mmv1/products/dataplex/GlossaryCategory.yaml +++ b/mmv1/products/dataplex/GlossaryCategory.yaml @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +--- name: 'GlossaryCategory' description: | Represents a collection of categories and terms within a Glossary that are related to each other. diff --git a/mmv1/products/dataplex/GlossaryTerm.yaml b/mmv1/products/dataplex/GlossaryTerm.yaml index 4ca74e48a0b2..d03e685703bb 100644 --- a/mmv1/products/dataplex/GlossaryTerm.yaml +++ b/mmv1/products/dataplex/GlossaryTerm.yaml @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +--- name: 'GlossaryTerm' description: | Represents a collection of terms within a Glossary that are related to each other. diff --git a/mmv1/products/dataproc/Batch.yaml b/mmv1/products/dataproc/Batch.yaml index 28916a3bd7c9..1b09944bb3bb 100644 --- a/mmv1/products/dataproc/Batch.yaml +++ b/mmv1/products/dataproc/Batch.yaml @@ -55,7 +55,7 @@ examples: project_name: PROJECT_NAME test_vars_overrides: prevent_destroy: "false" - subnetwork_name: acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-spark-test-network", "dataproc-spark-test-subnetwork") + subnetwork_name: BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-spark-test-network", "dataproc-spark-test-subnetwork") - name: dataproc_batch_spark_full primary_resource_id: example_batch_spark ignore_read_extra: @@ -68,7 +68,7 @@ examples: test_env_vars: project_name: PROJECT_NAME test_vars_overrides: - kms_key_name: acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-batch-key1").CryptoKey.Name + kms_key_name: kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-batch-key1").CryptoKey.Name prevent_destroy: "false" - name: dataproc_batch_sparksql primary_resource_id: example_batch_sparsql @@ -81,7 +81,7 @@ examples: project_name: PROJECT_NAME test_vars_overrides: prevent_destroy: "false" - subnetwork_name: acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-sparksql-test-network", "dataproc-sparksql-test-subnetwork") + subnetwork_name: BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-sparksql-test-network", "dataproc-sparksql-test-subnetwork") - name: dataproc_batch_pyspark primary_resource_id: example_batch_pyspark ignore_read_extra: @@ -93,7 +93,7 @@ examples: project_name: PROJECT_NAME test_vars_overrides: prevent_destroy: "false" - subnetwork_name: acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-pyspark-test-network", "dataproc-pyspark-test-subnetwork") + subnetwork_name: BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-pyspark-test-network", "dataproc-pyspark-test-subnetwork") - name: dataproc_batch_sparkr primary_resource_id: example_batch_sparkr ignore_read_extra: @@ -105,7 +105,7 @@ examples: project_name: PROJECT_NAME test_vars_overrides: prevent_destroy: "false" - subnetwork_name: acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-pyspark-test-network", "dataproc-pyspark-test-subnetwork") + subnetwork_name: BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-pyspark-test-network", "dataproc-pyspark-test-subnetwork") - name: dataproc_batch_autotuning primary_resource_id: example_batch_autotuning ignore_read_extra: @@ -117,7 +117,7 @@ examples: project_name: PROJECT_NAME test_vars_overrides: prevent_destroy: "false" - subnetwork_name: acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-autotuning-test-network", "dataproc-autotuning-test-subnetwork") + subnetwork_name: BootstrapSubnetWithFirewallForDataprocBatches(t, "dataproc-autotuning-test-network", "dataproc-autotuning-test-subnetwork") parameters: - name: location type: String diff --git a/mmv1/products/dataproc/SessionTemplate.yaml b/mmv1/products/dataproc/SessionTemplate.yaml index 6ad6722330dc..14b18d11c295 100644 --- a/mmv1/products/dataproc/SessionTemplate.yaml +++ b/mmv1/products/dataproc/SessionTemplate.yaml @@ -43,7 +43,7 @@ examples: test_env_vars: project_name: 'PROJECT_NAME' test_vars_overrides: - 'subnetwork_name': 'acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "jupyer-session-test-network", "jupyter-session-test-subnetwork")' + 'subnetwork_name': 'BootstrapSubnetWithFirewallForDataprocBatches(t, "jupyer-session-test-network", "jupyter-session-test-subnetwork")' 'prevent_destroy': 'false' ignore_read_extra: - 'runtime_config.0.properties' @@ -58,9 +58,9 @@ examples: test_env_vars: project_name: 'PROJECT_NAME' test_vars_overrides: - 'subnetwork_name': 'acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "jupyer-session-test-network", "jupyter-session-test-subnetwork")' + 'subnetwork_name': 'BootstrapSubnetWithFirewallForDataprocBatches(t, "jupyer-session-test-network", "jupyter-session-test-subnetwork")' 'prevent_destroy': 'false' - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-session-template-key1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-session-template-key1").CryptoKey.Name' ignore_read_extra: - 'runtime_config.0.properties' - name: 'dataproc_session_templates_spark_connect' @@ -72,7 +72,7 @@ examples: test_env_vars: project_name: 'PROJECT_NAME' test_vars_overrides: - 'subnetwork_name': 'acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "spark-connect-session-test-network", "spark-connect-session-test-subnetwork")' + 'subnetwork_name': 'BootstrapSubnetWithFirewallForDataprocBatches(t, "spark-connect-session-test-network", "spark-connect-session-test-subnetwork")' 'prevent_destroy': 'false' ignore_read_extra: - 'runtime_config.0.properties' diff --git a/mmv1/products/datastream/PrivateConnection.yaml b/mmv1/products/datastream/PrivateConnection.yaml index 9ce58699aaa1..5ec507cfb14b 100644 --- a/mmv1/products/datastream/PrivateConnection.yaml +++ b/mmv1/products/datastream/PrivateConnection.yaml @@ -27,6 +27,8 @@ create_url: 'projects/{{project}}/locations/{{location}}/privateConnections?priv immutable: true import_format: - 'projects/{{project}}/locations/{{location}}/privateConnections/{{private_connection_id}}' +deletion_policy_custom_docs: true +deletion_policy_default: "FORCE" timeouts: insert_minutes: 30 update_minutes: 30 @@ -43,6 +45,7 @@ custom_code: post_create: 'templates/terraform/post_create/private_connection.go.tmpl' pre_delete: 'templates/terraform/pre_delete/private_connection.go.tmpl' post_import: 'templates/terraform/post_import/private_connection.go.tmpl' + tgc_decoder: 'templates/tgc_next/decoders/datastream_private_connection.go.tmpl' include_in_tgc_next: true schema_version: 1 state_upgraders: true @@ -81,9 +84,14 @@ virtual_fields: The deletion policy for the private connection. Setting `FORCE` will also delete any child routes that belong to this private connection. Setting `DEFAULT` will fail the delete if child routes exist. Defaults to `FORCE` for backwards compatibility. - Possible values: `DEFAULT`, `FORCE`. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". type: String - default_value: "FORCE" + exclude: true parameters: - name: 'privateConnectionId' type: String @@ -165,6 +173,7 @@ properties: A free subnet for peering. (CIDR of /29) required: true - name: 'pscInterfaceConfig' + is_missing_in_cai: true type: NestedObject description: | The PSC Interface configuration is used to create PSC Interface diff --git a/mmv1/products/datastream/Stream.yaml b/mmv1/products/datastream/Stream.yaml index 1d6d3d55fa14..6ae8b95f7c6d 100644 --- a/mmv1/products/datastream/Stream.yaml +++ b/mmv1/products/datastream/Stream.yaml @@ -70,7 +70,7 @@ examples: 'deletion_protection': 'false' external_providers: ["random", "time"] exclude_docs: true - # Random provider + # Random provider skip_vcr: true - name: 'datastream_stream_full' primary_resource_id: 'default' @@ -86,11 +86,11 @@ examples: stream_cmek: 'kms-name' test_vars_overrides: 'deletion_protection': 'false' - 'stream_cmek': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'stream_cmek': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' oics_vars_overrides: 'deletion_protection': 'false' external_providers: ["random", "time"] - # Random provider + # Random provider skip_vcr: true - name: 'datastream_stream_postgresql' primary_resource_id: 'default' @@ -143,7 +143,7 @@ examples: stream_id: 'stream' test_vars_overrides: 'deletion_protection': 'false' - # Requires SQLServer Configuration + # Requires SQLServer Configuration # for backward compatible database_name: '"db" + randomSuffix' # for backward compatible @@ -167,7 +167,7 @@ examples: stream_id: 'stream' test_vars_overrides: 'deletion_protection': 'false' - # Requires MySQL Configuration + # Requires MySQL Configuration # for backward compatible database_name: '"db" + randomSuffix' # for backward compatible @@ -207,11 +207,11 @@ examples: bigquery_destination_table_kms_key_name: 'bigquery-kms-name' test_vars_overrides: 'deletion_protection': 'false' - 'bigquery_destination_table_kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'bigquery_destination_table_kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' oics_vars_overrides: 'deletion_protection': 'false' external_providers: ["random", "time"] - # Random provider + # Random provider skip_vcr: true - name: 'datastream_stream_bigquery_cross_project_source_hierachy' primary_resource_id: 'default' @@ -231,7 +231,7 @@ examples: oics_vars_overrides: 'deletion_protection': 'false' external_providers: ["random", "time"] - # Random provider + # Random provider skip_vcr: true - name: 'datastream_stream_bigquery_append_only' primary_resource_id: 'default' @@ -248,7 +248,7 @@ examples: oics_vars_overrides: 'deletion_protection': 'false' external_providers: ["random", "time"] - # Random provider + # Random provider skip_vcr: true - name: 'datastream_stream_bigquery_blmt' primary_resource_id: 'default' diff --git a/mmv1/products/deploymentmanager/Deployment.yaml b/mmv1/products/deploymentmanager/Deployment.yaml index ee6d72287a11..d9b3044c9a65 100644 --- a/mmv1/products/deploymentmanager/Deployment.yaml +++ b/mmv1/products/deploymentmanager/Deployment.yaml @@ -42,7 +42,7 @@ delete_url: 'projects/{{project}}/global/deployments/{{name}}?deletePolicy={{del immutable: true import_format: - 'projects/{{project}}/deployments/{{name}}' - # Very long to support very long deployments +# Very long to support very long deployments timeouts: insert_minutes: 60 update_minutes: 60 @@ -100,7 +100,7 @@ parameters: enum_values: - 'ABANDON' - 'DELETE' - # Custom Update + # Custom Update - name: 'preview' type: Boolean description: | diff --git a/mmv1/products/dialogflow/ConversationProfile.yaml b/mmv1/products/dialogflow/ConversationProfile.yaml index 8c3e62575eac..c1c710c17cc8 100644 --- a/mmv1/products/dialogflow/ConversationProfile.yaml +++ b/mmv1/products/dialogflow/ConversationProfile.yaml @@ -38,6 +38,7 @@ custom_code: pre_delete: 'templates/terraform/pre_create/dialogflow_set_endpoint.go.tmpl' post_create: 'templates/terraform/post_create/set_computed_name.tmpl' custom_import: 'templates/terraform/custom_import/self_link_as_name_set_project_and_location.go.tmpl' + test_check_destroy: 'templates/terraform/test_check_destroy/dialogflow_conversation_profile.go.tmpl' exclude_sweeper: true examples: - name: 'dialogflow_conversation_profile_basic' @@ -60,13 +61,13 @@ parameters: type: String url_param_only: true description: | - desc + The location of the conversation profile. required: true properties: - name: 'name' type: String description: | - name + Identifier. The unique identifier of this conversation profile. output: true - name: 'displayName' type: String @@ -213,7 +214,7 @@ properties: - type: NestedObject name: 'sections' description: | - he customized sections chosen to return when requesting a summary of a conversation. + The customized sections chosen to return when requesting a summary of a conversation. properties: - type: Array name: 'sectionTypes' @@ -243,7 +244,7 @@ properties: name: 'agent' required: true description: | - he name of a Dialogflow virtual agent used for end user side intent detection and suggestion. Format: projects//locations//agent. + The name of a Dialogflow virtual agent used for end user side intent detection and suggestion. Format: projects//locations//agent. - type: NestedObject name: 'humanAgentSideConfig' description: | @@ -388,7 +389,7 @@ properties: - type: NestedObject name: 'sections' description: | - he customized sections chosen to return when requesting a summary of a conversation. + The customized sections chosen to return when requesting a summary of a conversation. properties: - type: Array name: 'sectionTypes' @@ -444,7 +445,7 @@ properties: name: 'agent' required: true description: | - he name of a Dialogflow virtual agent used for end user side intent detection and suggestion. Format: projects//locations//agent. + The name of a Dialogflow virtual agent used for end user side intent detection and suggestion. Format: projects//locations//agent. - type: NestedObject name: 'humanAgentSideConfig' description: | @@ -495,7 +496,7 @@ properties: - type: NestedObject name: 'messageAnalysisConfig' description: | - desc + Configuration for analyzing conversation messages. properties: - type: Boolean name: 'enableEntityExtraction' @@ -600,7 +601,7 @@ properties: - AUDIO_ENCODING_AMR - AUDIO_ENCODING_AMR_WB - AUDIO_ENCODING_OGG_OPUS - - AUDIOENCODING_SPEEX_WITH_HEADER_BYTE + - AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE - type: Integer name: 'sampleRateHertz' description: | @@ -617,7 +618,7 @@ properties: - type: Boolean name: 'useTimeoutBasedEndpointing' description: | - Use timeout based endpointing, interpreting endpointer sensitivy as seconds of timeout value. + Use timeout based endpointing, interpreting endpointer sensitivity as seconds of timeout value. - type: String name: 'languageCode' description: | @@ -672,6 +673,47 @@ properties: - SSML_VOICE_GENDER_MALE - SSML_VOICE_GENDER_FEMALE - SSML_VOICE_GENDER_NEUTRAL + - type: NestedObject + name: 'sipConfig' + min_version: beta + description: | + Configuration for SIP. + properties: + - type: Boolean + name: 'createConversationOnTheFly' + description: | + Asks Dialogflow Telephony to create the conversation provided in the SIP header on the fly when the call comes in. + send_empty_value: true + - type: Boolean + name: 'inactiveStart' + description: | + Starts the conversation with inactive SDP directives + send_empty_value: true + - type: String + name: 'maxAudioRecordingDuration' + description: | + Max duration for audio recording. Overrides the default value of 15 min. Max value is 8 hours. + - type: Boolean + name: 'allowVirtualAgentInteraction' + description: | + Allows interactions with a Dialogflow virtual agent even if the call is connected for SIPREC purposes. + send_empty_value: true + - type: Boolean + name: 'keepConversationRunning' + description: | + Keeps the conversation running even if the call is disconnected. + send_empty_value: true + - type: Array + name: 'copyInboundCallLegHeaders' + description: | + List of inbound call leg headers to be copied to outbound call legs created later. + item_type: + type: String + - type: Boolean + name: 'ignoreReinviteMediaDirection' + description: | + Ignores any media direction in the reINVITE SDP offer. Reuse the previous media direction. + send_empty_value: true - type: NestedObject name: 'newRecognitionResultNotificationConfig' description: | diff --git a/mmv1/products/dialogflow/SipTrunk.yaml b/mmv1/products/dialogflow/SipTrunk.yaml new file mode 100644 index 000000000000..24ea013c345c --- /dev/null +++ b/mmv1/products/dialogflow/SipTrunk.yaml @@ -0,0 +1,102 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- !ruby/object:Api::Resource +name: 'SipTrunk' +base_url: 'projects/{{project}}/locations/{{location}}/sipTrunks' +create_url: 'projects/{{project}}/locations/{{location}}/sipTrunks' +update_verb: 'PATCH' +update_mask: true +description: | + SipTrunk is the resource that represents a SIP trunk to connect to the Google Telephony Platform SIP trunking service. +references: + api: 'https://cloud.google.com/dialogflow/es/docs/reference/rest/v2/projects.locations.sipTrunks' +id_format: '{{name}}' +self_link: '{{name}}' +import_format: + - '{{name}}' +custom_code: + pre_create: 'templates/terraform/pre_create/dialogflow_set_endpoint.go.tmpl' + pre_read: 'templates/terraform/pre_create/dialogflow_set_endpoint.go.tmpl' + pre_update: 'templates/terraform/pre_create/dialogflow_set_endpoint.go.tmpl' + pre_delete: 'templates/terraform/pre_create/dialogflow_set_endpoint.go.tmpl' + custom_import: 'templates/terraform/custom_import/self_link_as_name_set_project_and_location.go.tmpl' +parameters: + - name: 'location' + type: String + url_param_only: true + description: | + The location of the SIP trunk. + required: true + immutable: true +properties: + - type: String + name: 'name' + description: | + Identifier. The unique identifier of the SIP trunk. + output: true + - type: Array + name: 'expectedHostname' + description: | + Required. The expected hostnames in the peer certificate from the partner that is used for TLS authentication. + required: true + item_type: + type: String + - type: String + name: 'displayName' + description: | + Optional. Human-readable alias for this trunk. + - type: Array + name: 'connections' + description: | + Output only. The connections of the SIP trunk. + output: true + item_type: + type: NestedObject + properties: + - type: String + name: 'connectionId' + description: | + Output only. The unique identifier of the connection. + output: true + - type: String + name: 'state' + description: | + Output only. The state of the connection. + output: true + - type: String + name: 'updateTime' + description: | + Output only. The last update time of the connection. + output: true + - type: NestedObject + name: 'errorDetails' + description: | + Output only. The error details of the connection. + output: true + properties: + - type: String + name: 'code' + description: | + Output only. The error code. + output: true + - type: String + name: 'message' + description: | + Output only. The error message. + output: true +examples: + - name: 'dialogflow_sip_trunk_basic' + primary_resource_id: 'basic_trunk' + vars: + trunk_name: 'basic-trunk' diff --git a/mmv1/products/dialogflowcx/Flow.yaml b/mmv1/products/dialogflowcx/Flow.yaml index 2eab19e025e9..9cef7379b7cd 100644 --- a/mmv1/products/dialogflowcx/Flow.yaml +++ b/mmv1/products/dialogflowcx/Flow.yaml @@ -839,8 +839,8 @@ properties: allow_empty_object: true send_empty_value: true properties: [] # Meant to be an empty object with no properties. - # Although ResponseMessage has a field named "toolCall", we can't include it here because it references the Tool resource, which hasn't been available on Terraform. - # See https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3beta1/ResponseMessage + # Although ResponseMessage has a field named "toolCall", we can't include it here because it references the Tool resource, which hasn't been available on Terraform. + # See https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3beta1/ResponseMessage - name: 'webhook' type: String description: | diff --git a/mmv1/products/dialogflowcx/Page.yaml b/mmv1/products/dialogflowcx/Page.yaml index d20ef5fb368f..9c3170aba075 100644 --- a/mmv1/products/dialogflowcx/Page.yaml +++ b/mmv1/products/dialogflowcx/Page.yaml @@ -1351,8 +1351,8 @@ properties: allow_empty_object: true send_empty_value: true properties: [] # Meant to be an empty object with no properties. - # Although ResponseMessage has a field named "toolCall", we can't include it here because it references the Tool resource, which hasn't been available on Terraform. - # See https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3beta1/ResponseMessage + # Although ResponseMessage has a field named "toolCall", we can't include it here because it references the Tool resource, which hasn't been available on Terraform. + # See https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3beta1/ResponseMessage - name: 'webhook' type: String description: | diff --git a/mmv1/products/discoveryengine/CmekConfig.yaml b/mmv1/products/discoveryengine/CmekConfig.yaml index 95d32f3f1891..682fd4716c97 100644 --- a/mmv1/products/discoveryengine/CmekConfig.yaml +++ b/mmv1/products/discoveryengine/CmekConfig.yaml @@ -57,7 +57,7 @@ examples: cmek_config_id: 'cmek-config-id' kms_key_name: 'kms-key-name' test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us", "tftest-shared-key-5").CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us", "tftest-shared-key-5").CryptoKey.Name' ignore_read_extra: - 'project' # Skipping test because cmek configs are expensive to provision and teardown. diff --git a/mmv1/products/discoveryengine/DataStore.yaml b/mmv1/products/discoveryengine/DataStore.yaml index 7a4bc870485e..81a328e5d024 100644 --- a/mmv1/products/discoveryengine/DataStore.yaml +++ b/mmv1/products/discoveryengine/DataStore.yaml @@ -62,7 +62,7 @@ examples: data_store_id: 'data-store-id' kms_key_name: 'kms-key' test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' - name: 'discoveryengine_datastore_document_processing_config' primary_resource_id: 'document_processing_config' vars: diff --git a/mmv1/products/dlp/DeidentifyTemplate.yaml b/mmv1/products/dlp/DeidentifyTemplate.yaml index 8ff5250fb9d6..bf607cbf6fc3 100644 --- a/mmv1/products/dlp/DeidentifyTemplate.yaml +++ b/mmv1/products/dlp/DeidentifyTemplate.yaml @@ -191,7 +191,7 @@ properties: send_empty_value: true allow_empty_object: true properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#allinfotypes + # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#allinfotypes [] - name: 'allText' type: NestedObject @@ -202,7 +202,7 @@ properties: send_empty_value: true allow_empty_object: true properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#alltext + # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#alltext [] - name: 'infoTypeTransformations' type: NestedObject @@ -618,15 +618,15 @@ properties: description: | Common alphabets. enum_values: - # Unused. + # Unused. - 'FFX_COMMON_NATIVE_ALPHABET_UNSPECIFIED' - # [0-9] (radix of 10) + # [0-9] (radix of 10) - 'NUMERIC' - # [0-9A-F] (radix of 16) + # [0-9A-F] (radix of 16) - 'HEXADECIMAL' - # [0-9A-Z] (radix of 36) + # [0-9A-Z] (radix of 36) - 'UPPER_CASE_ALPHA_NUMERIC' - # [0-9A-Za-z] (radix of 62) + # [0-9A-Za-z] (radix of 62) - 'ALPHA_NUMERIC' - name: 'customAlphabet' type: String @@ -1046,17 +1046,17 @@ properties: type: Enum description: The part of the time to keep. enum_values: - # [0-9999] + # [0-9999] - 'YEAR' - # [1-12] + # [1-12] - 'MONTH' - # [1-31] + # [1-31] - 'DAY_OF_MONTH' - # [1-7] + # [1-7] - 'DAY_OF_WEEK' - # [1-53] + # [1-53] - 'WEEK_OF_YEAR' - # [0-23] + # [0-23] - 'HOUR_OF_DAY' - name: 'redactConfig' type: NestedObject @@ -1067,7 +1067,7 @@ properties: send_empty_value: true allow_empty_object: true properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#redactconfig + # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#redactconfig [] - name: 'cryptoHashConfig' type: NestedObject @@ -1246,7 +1246,7 @@ properties: description: | Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow the value "24:00:00" for scenarios like business closing time. validation: - # "An API may choose to allow the value "24:00:00" for scenarios like business closing time." + # "An API may choose to allow the value "24:00:00" for scenarios like business closing time." function: 'validation.IntBetween(0, 24)' - name: 'minutes' type: Integer @@ -1263,7 +1263,7 @@ properties: API may allow the value 60 if it allows leap-seconds. validation: - # "An API may allow the value 60 if it allows leap-seconds." + # "An API may allow the value 60 if it allows leap-seconds." function: 'validation.IntBetween(0, 60)' - name: 'nanos' type: Integer @@ -1362,7 +1362,7 @@ properties: description: | Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow the value "24:00:00" for scenarios like business closing time. validation: - # "An API may choose to allow the value "24:00:00" for scenarios like business closing time." + # "An API may choose to allow the value "24:00:00" for scenarios like business closing time." function: 'validation.IntBetween(0, 24)' - name: 'minutes' type: Integer @@ -1378,7 +1378,7 @@ properties: normally be from 0 to 59. An API may allow the value 60 if it allows leap-seconds. validation: - # "An API may allow the value 60 if it allows leap-seconds." + # "An API may allow the value 60 if it allows leap-seconds." function: 'validation.IntBetween(0, 60)' - name: 'nanos' type: Integer @@ -1435,7 +1435,7 @@ properties: send_empty_value: true allow_empty_object: true properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#redactconfig + # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#redactconfig [] - name: 'characterMaskConfig' type: NestedObject @@ -2498,7 +2498,7 @@ properties: send_empty_value: true allow_empty_object: true properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#redactconfig + # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#redactconfig [] - name: 'characterMaskConfig' type: NestedObject @@ -2668,13 +2668,13 @@ properties: description: | Common alphabets. Only one of this, `custom_alphabet` or `radix` must be specified. enum_values: - # [0-9] (radix of 10) + # [0-9] (radix of 10) - 'NUMERIC' - # [0-9A-F] (radix of 16) + # [0-9A-F] (radix of 16) - 'HEXADECIMAL' - # [0-9A-Z] (radix of 36) + # [0-9A-Z] (radix of 36) - 'UPPER_CASE_ALPHA_NUMERIC' - # [0-9A-Za-z] (radix of 62) + # [0-9A-Za-z] (radix of 62) - 'ALPHA_NUMERIC' - name: 'customAlphabet' type: String @@ -3030,7 +3030,7 @@ properties: send_empty_value: true allow_empty_object: true properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#DeidentifyTemplate.ReplaceWithInfoTypeConfig + # Meant to be an empty object with no properties - see here : https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates#DeidentifyTemplate.ReplaceWithInfoTypeConfig [] - name: 'timePartConfig' type: NestedObject @@ -3043,17 +3043,17 @@ properties: description: The part of the time to keep. required: true enum_values: - # [0-9999] + # [0-9999] - 'YEAR' - # [1-12] + # [1-12] - 'MONTH' - # [1-31] + # [1-31] - 'DAY_OF_MONTH' - # [1-7] + # [1-7] - 'DAY_OF_WEEK' - # [1-53] + # [1-53] - 'WEEK_OF_YEAR' - # [0-23] + # [0-23] - 'HOUR_OF_DAY' - name: 'cryptoHashConfig' type: NestedObject diff --git a/mmv1/products/eventarc/Channel.yaml b/mmv1/products/eventarc/Channel.yaml index 88b4827b4aca..80116ae46038 100644 --- a/mmv1/products/eventarc/Channel.yaml +++ b/mmv1/products/eventarc/Channel.yaml @@ -31,6 +31,7 @@ async: result: resource_inside_response: true autogen_async: true +custom_code: description: | The Eventarc Channel resource error_retry_predicates: @@ -48,7 +49,7 @@ examples: project: 'PROJECT_NAME' project_number: 'PROJECT_NUMBER' test_vars_overrides: - 'key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-channel-key").CryptoKey.Name' + 'key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-channel-key").CryptoKey.Name' - name: eventarc_channel primary_resource_id: primary vars: diff --git a/mmv1/products/eventarc/Pipeline.yaml b/mmv1/products/eventarc/Pipeline.yaml index c28e660888bb..72ddeacc53c5 100644 --- a/mmv1/products/eventarc/Pipeline.yaml +++ b/mmv1/products/eventarc/Pipeline.yaml @@ -27,6 +27,7 @@ references: api: https://cloud.google.com/eventarc/docs/reference/rest/v1/projects.locations.pipelines description: | The Eventarc Pipeline resource +custom_code: async: actions: ['create', 'update', 'delete'] operation: @@ -52,7 +53,7 @@ examples: test_env_vars: project_id: 'PROJECT_NAME' test_vars_overrides: - 'network_attachment_name': 'acctest.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", acctest.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", acctest.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' + 'network_attachment_name': 'compute.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", compute.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", compute.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' - name: eventarc_pipeline_with_workflow_destination primary_resource_id: primary vars: @@ -69,7 +70,7 @@ examples: project_id: 'PROJECT_NAME' service_account: 'SERVICE_ACCT' test_vars_overrides: - 'network_attachment_name': 'acctest.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", acctest.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", acctest.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' + 'network_attachment_name': 'compute.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", compute.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", compute.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' - name: eventarc_pipeline_with_oauth_and_protobuf_format primary_resource_id: primary vars: @@ -79,7 +80,7 @@ examples: project_id: 'PROJECT_NAME' service_account: 'SERVICE_ACCT' test_vars_overrides: - 'network_attachment_name': 'acctest.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", acctest.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", acctest.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' + 'network_attachment_name': 'compute.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", compute.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", compute.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' - name: eventarc_pipeline_with_cmek_and_avro_format primary_resource_id: primary bootstrap_iam: @@ -92,8 +93,8 @@ examples: test_env_vars: project_id: 'PROJECT_NAME' test_vars_overrides: - 'network_attachment_name': 'acctest.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", acctest.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", acctest.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' - 'key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-pipeline-key").CryptoKey.Name' + 'network_attachment_name': 'compute.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-pipeline-na", compute.BootstrapSubnet(t, "tf-bootstrap-eventarc-pipeline-subnet", compute.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-pipeline-network")))' + 'key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-pipeline-key").CryptoKey.Name' parameters: - name: location type: String diff --git a/mmv1/products/eventarc/Trigger.yaml b/mmv1/products/eventarc/Trigger.yaml index db10fc431bc1..3e3f885a0f54 100644 --- a/mmv1/products/eventarc/Trigger.yaml +++ b/mmv1/products/eventarc/Trigger.yaml @@ -39,6 +39,7 @@ sweeper: url_substitutions: - region: "us-central1" - region: "europe-west1" +custom_code: examples: - name: eventarc_trigger_with_cloud_run_destination primary_resource_id: primary @@ -52,7 +53,7 @@ examples: trigger_name: some-trigger network_attachment_name: network-attachment test_vars_overrides: - 'network_attachment_name': 'acctest.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-trigger-na", acctest.BootstrapSubnet(t, "tf-bootstrap-eventarc-trigger-subnet", acctest.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-trigger-network")))' + 'network_attachment_name': 'compute.BootstrapNetworkAttachment(t, "tf-bootstrap-eventarc-trigger-na", compute.BootstrapSubnet(t, "tf-bootstrap-eventarc-trigger-subnet", compute.BootstrapSharedTestNetwork(t, "tf-bootstrap-eventarc-trigger-network")))' test_env_vars: project_id: 'PROJECT_NAME' service_account: 'SERVICE_ACCT' @@ -71,7 +72,7 @@ examples: project_id: 'PROJECT_NAME' service_account: 'SERVICE_ACCT' test_vars_overrides: - 'key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-trigger-key").CryptoKey.Name' + 'key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-trigger-key").CryptoKey.Name' exclude_docs: true - name: eventarc_trigger_with_workflow_destination primary_resource_id: primary diff --git a/mmv1/products/firebase/AndroidApp.yaml b/mmv1/products/firebase/AndroidApp.yaml index 6a35168fa7ab..998739a6d6dd 100644 --- a/mmv1/products/firebase/AndroidApp.yaml +++ b/mmv1/products/firebase/AndroidApp.yaml @@ -81,14 +81,6 @@ examples: ignore_read_extra: - 'project' - 'deletion_policy' -virtual_fields: - - name: 'deletion_policy' - description: | - (Optional) Set to `ABANDON` to allow the AndroidApp to be untracked from terraform state - rather than deleted upon `terraform destroy`. This is useful because the AndroidApp may be - serving traffic. Set to `DELETE` to delete the AndroidApp. Defaults to `DELETE`. - type: String - default_value: "DELETE" parameters: properties: - name: 'name' diff --git a/mmv1/products/firebase/AppleApp.yaml b/mmv1/products/firebase/AppleApp.yaml index b594bcfa85cb..c0f95eeb8058 100644 --- a/mmv1/products/firebase/AppleApp.yaml +++ b/mmv1/products/firebase/AppleApp.yaml @@ -72,7 +72,7 @@ examples: display_name: 'Display Name Full' bundle_id: 'apple.app.12345' app_store_id: '12345' - # Has to be a 10-digit number. + # Has to be a 10-digit number. team_id: '9987654321' api_key_name: 'api-key' test_env_vars: @@ -86,14 +86,6 @@ examples: ignore_read_extra: - 'project' - 'deletion_policy' -virtual_fields: - - name: 'deletion_policy' - description: | - (Optional) Set to `ABANDON` to allow the Apple to be untracked from terraform state - rather than deleted upon `terraform destroy`. This is useful because the Apple may be - serving traffic. Set to `DELETE` to delete the Apple. Defaults to `DELETE`. - type: String - default_value: "DELETE" parameters: properties: - name: 'name' diff --git a/mmv1/products/firebase/WebApp.yaml b/mmv1/products/firebase/WebApp.yaml index 5f2271e3c5f4..5061a0c7bcbe 100644 --- a/mmv1/products/firebase/WebApp.yaml +++ b/mmv1/products/firebase/WebApp.yaml @@ -79,14 +79,6 @@ examples: ignore_read_extra: - 'project' - 'deletion_policy' -virtual_fields: - - name: 'deletion_policy' - description: | - Set to `ABANDON` to allow the WebApp to be untracked from terraform state - rather than deleted upon `terraform destroy`. This is useful becaue the WebApp may be - serving traffic. Set to `DELETE` to delete the WebApp. Default to `DELETE` - type: String - default_value: "DELETE" parameters: properties: - name: 'name' diff --git a/mmv1/products/firebaseappcheck/AppAttestConfig.yaml b/mmv1/products/firebaseappcheck/AppAttestConfig.yaml index dcdb15db1980..3a36f2f88e16 100644 --- a/mmv1/products/firebaseappcheck/AppAttestConfig.yaml +++ b/mmv1/products/firebaseappcheck/AppAttestConfig.yaml @@ -49,7 +49,7 @@ examples: project_id: 'PROJECT_NAME' test_vars_overrides: 'team_id': '"9987654321"' - # Need the time_sleep resource + # Need the time_sleep resource # for backward compatible bundle_id: '"bundle.id.appattest" + randomSuffix' external_providers: ["random", "time"] @@ -66,7 +66,7 @@ examples: test_vars_overrides: 'team_id': '"9987654321"' 'token_ttl': '"7200s"' - # Need the time_sleep resource + # Need the time_sleep resource # for backward compatible bundle_id: '"bundle.id.appattest" + randomSuffix' external_providers: ["random", "time"] diff --git a/mmv1/products/firebaseappcheck/DebugToken.yaml b/mmv1/products/firebaseappcheck/DebugToken.yaml index 208299ef1eaf..33d4d04c6d2e 100644 --- a/mmv1/products/firebaseappcheck/DebugToken.yaml +++ b/mmv1/products/firebaseappcheck/DebugToken.yaml @@ -50,7 +50,7 @@ examples: test_vars_overrides: # Don't add prefix. This string is a random UUID4 'token': '"5E728315-E121-467F-BCA1-1FE71130BB98"' - # Need the time_sleep resource + # Need the time_sleep resource # for backward compatible display_name: '"Debug Token" + randomSuffix' external_providers: ["random", "time"] diff --git a/mmv1/products/firebaseappcheck/DeviceCheckConfig.yaml b/mmv1/products/firebaseappcheck/DeviceCheckConfig.yaml index c22740ecb9ae..1b3252eb5d22 100644 --- a/mmv1/products/firebaseappcheck/DeviceCheckConfig.yaml +++ b/mmv1/products/firebaseappcheck/DeviceCheckConfig.yaml @@ -54,7 +54,7 @@ examples: 'private_key_path': '"test-fixtures/private-key-2.p8"' 'team_id': '"9987654321"' 'token_ttl': '"7200s"' - # Need the time_sleep resource + # Need the time_sleep resource # for backward compatible bundle_id: '"bundle.id.devicecheck" + randomSuffix' # for backward compatible diff --git a/mmv1/products/firebaseappcheck/PlayIntegrityConfig.yaml b/mmv1/products/firebaseappcheck/PlayIntegrityConfig.yaml index 2867c7e58931..2487df6a4362 100644 --- a/mmv1/products/firebaseappcheck/PlayIntegrityConfig.yaml +++ b/mmv1/products/firebaseappcheck/PlayIntegrityConfig.yaml @@ -61,7 +61,7 @@ examples: project_id: 'PROJECT_NAME' test_vars_overrides: 'token_ttl': '"7200s"' - # Need the time_sleep resource + # Need the time_sleep resource # for backward compatible package_name: '"package.name.playintegrity" + randomSuffix' external_providers: ["random", "time"] diff --git a/mmv1/products/firebasedataconnect/Service.yaml b/mmv1/products/firebasedataconnect/Service.yaml index a44ab4265ef0..1354f38ebb97 100644 --- a/mmv1/products/firebasedataconnect/Service.yaml +++ b/mmv1/products/firebasedataconnect/Service.yaml @@ -61,6 +61,8 @@ async: resource_inside_response: true include_project: false autogen_status: U2VydmljZQ== +deletion_policy_default: "DEFAULT" +deletion_policy_custom_docs: true parameters: - name: location type: String @@ -130,12 +132,20 @@ properties: virtual_fields: - name: deletion_policy type: String - default_value: DEFAULT description: |- The deletion policy for the database. Setting the field to FORCE allows the Service to be deleted even if a Schema or Connector is present. By default, the Service deletion will only succeed when no Schema or Connectors are present. - Possible values: DEFAULT, FORCE + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". + + Possible values: DEFAULT, FORCE, PREVENT, ABANDON, DELETE + # excluded from generation due to Universal Deletion Policy + exclude: true custom_code: pre_delete: templates/terraform/pre_delete/firebasedataconnect_service.go.tmpl diff --git a/mmv1/products/firebasehosting/Release.yaml b/mmv1/products/firebasehosting/Release.yaml index e4bcbadd2140..d2f21d2ce4de 100644 --- a/mmv1/products/firebasehosting/Release.yaml +++ b/mmv1/products/firebasehosting/Release.yaml @@ -25,7 +25,7 @@ base_url: 'sites/{{site_id}}/channels/{{channel_id}}/releases' self_link: 'sites/{{site_id}}/channels/{{channel_id}}/releases/{{release_id}}' create_url: 'sites/{{site_id}}/channels/{{channel_id}}/releases?versionName={{version_name}}' exclude_delete: true - # not updatable +# not updatable immutable: true import_format: - 'sites/{{site_id}}/releases/{{release_id}}' diff --git a/mmv1/products/firebasehosting/Version.yaml b/mmv1/products/firebasehosting/Version.yaml index 1e7a5a89c997..d5751af0f057 100644 --- a/mmv1/products/firebasehosting/Version.yaml +++ b/mmv1/products/firebasehosting/Version.yaml @@ -258,17 +258,17 @@ properties: type: String description: The user-supplied glob to match against the request URL path. - # exactly_one_of: - # - 'glob' - # - 'regex' + # exactly_one_of: + # - 'glob' + # - 'regex' - name: 'regex' type: String description: The user-supplied RE2 regular expression to match against the request URL path. - # exactly_one_of: - # - 'glob' - # - 'regex' + # exactly_one_of: + # - 'glob' + # - 'regex' - name: 'headers' type: KeyValuePairs description: | diff --git a/mmv1/products/firebasestorage/Bucket.yaml b/mmv1/products/firebasestorage/Bucket.yaml index 8072b2269af0..93082cadf1bf 100644 --- a/mmv1/products/firebasestorage/Bucket.yaml +++ b/mmv1/products/firebasestorage/Bucket.yaml @@ -27,7 +27,7 @@ self_link: 'projects/{{project}}/buckets/{{bucket_id}}' create_url: 'projects/{{project}}/buckets/{{bucket_id}}:addFirebase' delete_url: 'projects/{{project}}/buckets/{{bucket_id}}:removeFirebase' delete_verb: 'POST' - # Does not support update operation. There is nothing to update. +# Does not support update operation. There is nothing to update. immutable: true import_format: - 'projects/{{project}}/buckets/{{bucket_id}}' diff --git a/mmv1/products/firebasestorage/DefaultBucket.yaml b/mmv1/products/firebasestorage/DefaultBucket.yaml index 3e0b75083aed..19e20437144a 100644 --- a/mmv1/products/firebasestorage/DefaultBucket.yaml +++ b/mmv1/products/firebasestorage/DefaultBucket.yaml @@ -54,6 +54,7 @@ properties: The resource name of the underlying Google Cloud Storage bucket. min_version: "beta" output: true + custom_flatten: 'templates/terraform/custom_flatten/firebasestorage_bucket.go.tmpl' properties: - name: "name" type: String @@ -62,6 +63,12 @@ properties: projects/PROJECT_IDENTIFIER/buckets/BUCKET_ID min_version: "beta" output: true + - name: "bucketId" + type: String + description: | + The last segment of bucket.name. + min_version: "beta" + output: true - name: "location" type: String description: | diff --git a/mmv1/products/firestore/Database.yaml b/mmv1/products/firestore/Database.yaml index 67296bc41675..9c5b07534100 100644 --- a/mmv1/products/firestore/Database.yaml +++ b/mmv1/products/firestore/Database.yaml @@ -49,6 +49,8 @@ async: resource_inside_response: true custom_code: pre_delete: 'templates/terraform/pre_delete/firestore_database.go.tmpl' +# TODO: remove this default in the 8.0.0 major release +deletion_policy_default: "ABANDON" examples: - name: 'firestore_default_database' primary_resource_id: 'database' @@ -177,19 +179,6 @@ examples: - 'project' - 'etag' - 'deletion_policy' -virtual_fields: - - name: 'deletion_policy' - description: | - Deletion behavior for this database. - If the deletion policy is `ABANDON`, the database will be removed from Terraform state but not deleted from Google Cloud upon destruction. - If the deletion policy is `DELETE`, the database will both be removed from Terraform state and deleted from Google Cloud upon destruction. - The default value is `ABANDON`. - See also `delete_protection`. - type: String - default_value: "ABANDON" - # `deletion_policy` is deprecated and will be removed in a future major release. - # Once that release happens, you should use `delete_protection_state` instead. - # For now though, setting this field is necessary if you wish for your Firestore databases to be deleted upon `terraform destroy`. parameters: properties: - name: 'name' diff --git a/mmv1/products/firestore/Index.yaml b/mmv1/products/firestore/Index.yaml index a819873fd84d..94b696f5e8f1 100644 --- a/mmv1/products/firestore/Index.yaml +++ b/mmv1/products/firestore/Index.yaml @@ -52,7 +52,6 @@ custom_code: encoder: 'templates/terraform/encoders/index.go.tmpl' custom_import: 'templates/terraform/custom_import/index_self_link_as_name_set_project.go.tmpl' custom_create: 'templates/terraform/custom_create/firestore_index.go.tmpl' - pre_delete: 'templates/terraform/pre_delete/firestore_index.go.tmpl' error_retry_predicates: - 'transport_tpg.FirestoreIndex409Retry' examples: @@ -144,18 +143,6 @@ virtual_fields: default_value: false description: "Whether to skip waiting for the index to be created." ignore_read: true - - name: 'deletion_policy' - type: Enum - default_value: 'DELETE' - ignore_read: true - enum_values: - - 'DELETE' - - 'PREVENT' - description: | - Deletion behavior for this index. - If the deletion policy is `PREVENT`, the index cannot be deleted and a terraform destroy will fail. - If the deletion policy is `DELETE`, the index will both be removed from Terraform state and deleted from Google Cloud upon destruction. - The default value is `DELETE`. parameters: # Firestore uses a custom create function. Any new fields must be explicitly handled there. properties: diff --git a/mmv1/products/gkebackup/BackupPlan.yaml b/mmv1/products/gkebackup/BackupPlan.yaml index e4b35878fe09..f167451b6c0f 100644 --- a/mmv1/products/gkebackup/BackupPlan.yaml +++ b/mmv1/products/gkebackup/BackupPlan.yaml @@ -58,8 +58,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_autopilot' @@ -72,8 +72,8 @@ examples: subnetwork_name: 'default' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_cmek' @@ -89,8 +89,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_nslabels' @@ -105,8 +105,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_full' @@ -121,8 +121,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_permissive' @@ -137,8 +137,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_rpo_daily_window' @@ -153,8 +153,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_backupplan_rpo_weekly_window' @@ -169,8 +169,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' parameters: @@ -380,7 +380,7 @@ properties: - 'FRIDAY' - 'SATURDAY' - 'SUNDAY' - # Exclusion Window Object - End + # Exclusion Window Object - End - name: 'etag' type: String description: | diff --git a/mmv1/products/gkebackup/RestorePlan.yaml b/mmv1/products/gkebackup/RestorePlan.yaml index db85d61e1ad6..7d6d2920f966 100644 --- a/mmv1/products/gkebackup/RestorePlan.yaml +++ b/mmv1/products/gkebackup/RestorePlan.yaml @@ -57,8 +57,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_rollback_namespace' @@ -72,8 +72,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_protected_application' @@ -87,8 +87,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_all_cluster_resources' @@ -102,8 +102,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_rename_namespace' @@ -117,8 +117,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_second_transformation' @@ -132,8 +132,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_gitops_mode' @@ -147,8 +147,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_restore_order' @@ -162,8 +162,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' - name: 'gkebackup_restoreplan_volume_res' @@ -177,8 +177,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' parameters: @@ -223,7 +223,7 @@ properties: - name: 'cluster' type: String description: | - The source cluster from which Restores will be created via this RestorePlan. + The name of the target cluster to which you want to Restore via this RestorePlan. required: true immutable: true - name: 'restoreConfig' diff --git a/mmv1/products/gkehub/Membership.yaml b/mmv1/products/gkehub/Membership.yaml index d387a7105a31..c59970a15555 100644 --- a/mmv1/products/gkehub/Membership.yaml +++ b/mmv1/products/gkehub/Membership.yaml @@ -66,8 +66,8 @@ examples: project: 'PROJECT_NAME' location: 'REGION' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' # for backward compatible name: '"basic" + randomSuffix' - name: 'gkehub_membership_basic' @@ -80,8 +80,8 @@ examples: subnetwork_name: 'default' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' # for backward compatible name: '"basic" + randomSuffix' oics_vars_overrides: @@ -98,8 +98,8 @@ examples: project: 'PROJECT_NAME' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' # for backward compatible name: '"basic" + randomSuffix' oics_vars_overrides: diff --git a/mmv1/products/gkehub2/MembershipBinding.yaml b/mmv1/products/gkehub2/MembershipBinding.yaml index 885e7e754188..35ec2b40a348 100644 --- a/mmv1/products/gkehub2/MembershipBinding.yaml +++ b/mmv1/products/gkehub2/MembershipBinding.yaml @@ -58,8 +58,8 @@ examples: membership_id: 'fmt.Sprintf("tf-test-membership%s", context["random_suffix"])' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' parameters: diff --git a/mmv1/products/gkehub2/MembershipRBACRoleBinding.yaml b/mmv1/products/gkehub2/MembershipRBACRoleBinding.yaml index 8d0abfc1ab30..76abcd9a6b79 100644 --- a/mmv1/products/gkehub2/MembershipRBACRoleBinding.yaml +++ b/mmv1/products/gkehub2/MembershipRBACRoleBinding.yaml @@ -58,8 +58,8 @@ examples: location: 'global' test_vars_overrides: 'deletion_protection': 'false' - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "gke-cluster")' - 'subnetwork_name': 'acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster"))' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "gke-cluster")' + 'subnetwork_name': 'compute.BootstrapSubnet(t, "gke-cluster", compute.BootstrapSharedTestNetwork(t, "gke-cluster"))' oics_vars_overrides: 'deletion_protection': 'false' parameters: diff --git a/mmv1/products/hypercomputecluster/Cluster.yaml b/mmv1/products/hypercomputecluster/Cluster.yaml index 86efee43153e..5b81b66af7ab 100644 --- a/mmv1/products/hypercomputecluster/Cluster.yaml +++ b/mmv1/products/hypercomputecluster/Cluster.yaml @@ -1,4 +1,4 @@ -# Copyright 2025 Google Inc. +# Copyright 2026 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -597,6 +597,13 @@ properties: type: Boolean required: true description: Enables Auto-class feature. + - name: terminalStorageClass + type: String + description: |- + Terminal storage class of the autoclass bucket + Possible values: + NEARLINE + ARCHIVE - name: bucket type: String required: true @@ -717,6 +724,14 @@ properties: description: |- Name of the Managed Lustre instance to create, in the format `projects/{project}/locations/{location}/instances/{instance}` + - name: perUnitStorageThroughput + type: String + description: |- + Throughput of the instance in MB/s/TiB. Valid values are 125, 250, + 500, 1000. See [Performance tiers and maximum storage + capacities](https://cloud.google.com/managed-lustre/docs/create-instance#performance-tiers) + for more information. + immutable: true - name: filestore type: NestedObject description: A reference to a [Filestore](https://cloud.google.com/filestore) instance. diff --git a/mmv1/products/hypercomputecluster/product.yaml b/mmv1/products/hypercomputecluster/product.yaml index 58abcea924d7..302dfc8e3eb9 100644 --- a/mmv1/products/hypercomputecluster/product.yaml +++ b/mmv1/products/hypercomputecluster/product.yaml @@ -1,4 +1,4 @@ -# Copyright 2025 Google Inc. +# Copyright 2026 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at diff --git a/mmv1/products/iamworkforcepool/WorkforcePoolProvider.yaml b/mmv1/products/iamworkforcepool/WorkforcePoolProvider.yaml index 4ee1f332f72a..98031a38a6dc 100644 --- a/mmv1/products/iamworkforcepool/WorkforcePoolProvider.yaml +++ b/mmv1/products/iamworkforcepool/WorkforcePoolProvider.yaml @@ -116,7 +116,7 @@ examples: workforce_pool_id: example-pool test_env_vars: org_id: ORG_ID - skip_func: acctest.SkipTestUntil(t, "2026-03-05") # waiting for rollout + skip_func: acctest.SkipTestUntil(t, "2026-03-05") # waiting for rollout - name: iam_workforce_pool_provider_extra_attributes_display_name_oauth2_config_client_full primary_resource_id: example ignore_read_extra: @@ -127,7 +127,7 @@ examples: workforce_pool_id: example-pool test_env_vars: org_id: ORG_ID - skip_func: acctest.SkipTestUntil(t, "2026-03-05") # waiting for rollout + skip_func: acctest.SkipTestUntil(t, "2026-03-05") # waiting for rollout - name: iam_workforce_pool_provider_extended_attributes_oauth2_config_client_basic primary_resource_id: example ignore_read_extra: diff --git a/mmv1/products/iap/ForwardingRuleRegionalService.yaml b/mmv1/products/iap/ForwardingRuleRegionalService.yaml index 0602ac8b28a9..0b0c54d89735 100644 --- a/mmv1/products/iap/ForwardingRuleRegionalService.yaml +++ b/mmv1/products/iap/ForwardingRuleRegionalService.yaml @@ -1,3 +1,4 @@ +--- name: 'WebRegionForwardingRuleService' description: | Only used to generate IAM resources diff --git a/mmv1/products/identityplatform/Config.yaml b/mmv1/products/identityplatform/Config.yaml index f61cd197d6d9..447e136619a7 100644 --- a/mmv1/products/identityplatform/Config.yaml +++ b/mmv1/products/identityplatform/Config.yaml @@ -53,7 +53,7 @@ examples: test_env_vars: org_id: 'ORG_ID' billing_acct: 'BILLING_ACCT' - # Resource creation race + # Resource creation race test_vars_overrides: # Set quota start time for the following day. 'quota_start_time': 'time.Now().AddDate(0, 0, 1).Format(time.RFC3339)' diff --git a/mmv1/products/identityplatform/DefaultSupportedIdpConfig.yaml b/mmv1/products/identityplatform/DefaultSupportedIdpConfig.yaml index 43ecacf7967a..1236182436f8 100644 --- a/mmv1/products/identityplatform/DefaultSupportedIdpConfig.yaml +++ b/mmv1/products/identityplatform/DefaultSupportedIdpConfig.yaml @@ -36,8 +36,8 @@ custom_code: examples: - name: 'identity_platform_default_supported_idp_config_basic' primary_resource_id: 'idp_config' - # Skip test due to operating on singleton and the handwritten update test handles this - # If we could spin up a project and enable identity platform we could test this separately + # Skip test due to operating on singleton and the handwritten update test handles this + # If we could spin up a project and enable identity platform we could test this separately exclude_test: true parameters: properties: diff --git a/mmv1/products/integrations/AuthConfig.yaml b/mmv1/products/integrations/AuthConfig.yaml index 7dfa89bc106d..d28eca51cddc 100644 --- a/mmv1/products/integrations/AuthConfig.yaml +++ b/mmv1/products/integrations/AuthConfig.yaml @@ -49,7 +49,7 @@ examples: primary_resource_id: 'basic_example' vars: auth_config_name: 'test-authconfig' - # This is already part of other examples. + # This is already part of other examples. exclude_test: true - name: 'integrations_auth_config_advance' primary_resource_id: 'advance_example' @@ -342,7 +342,7 @@ properties: A list of parameter map entries. item_type: type: NestedObject - # ParameterMapEntry + # ParameterMapEntry properties: - name: 'key' type: NestedObject diff --git a/mmv1/products/integrations/Client.yaml b/mmv1/products/integrations/Client.yaml index a3ddc281162e..0a927efd6d10 100644 --- a/mmv1/products/integrations/Client.yaml +++ b/mmv1/products/integrations/Client.yaml @@ -49,7 +49,7 @@ examples: test_vars_overrides: key_ring_name: '"tftest-shared-keyring-1"' crypto_key_name: '"tftest-shared-key-1"' - kms_key: 'acctest.BootstrapKMSKeyInLocation(t, "us-east1")' + kms_key: 'kms.BootstrapKMSKeyInLocation(t, "us-east1")' bootstrap_iam: - member: "serviceAccount:service-{project_number}@gcp-sa-integrations.iam.gserviceaccount.com" role: "roles/cloudkmskacls.serviceAgent" diff --git a/mmv1/products/kms/KeyRing.yaml b/mmv1/products/kms/KeyRing.yaml index 6cca3351f8a0..5281c579366f 100644 --- a/mmv1/products/kms/KeyRing.yaml +++ b/mmv1/products/kms/KeyRing.yaml @@ -46,12 +46,12 @@ custom_code: examples: - name: 'kms_key_ring_basic' primary_resource_id: 'example-keyring' - # Because we can't really delete the resource, we get an error of - # dangling resources with the auto generated tests. The hand-written - # tests do a better job at testing that the key was removed from state - # and that no keyrings are left behind since they create (and destroy) - # a project just for this test, but they require org level IAM roles - # for the test service account. + # Because we can't really delete the resource, we get an error of + # dangling resources with the auto generated tests. The hand-written + # tests do a better job at testing that the key was removed from state + # and that no keyrings are left behind since they create (and destroy) + # a project just for this test, but they require org level IAM roles + # for the test service account. exclude_test: true parameters: - name: 'location' diff --git a/mmv1/products/logging/FolderSettings.yaml b/mmv1/products/logging/FolderSettings.yaml index f9f16f498a2c..641b513e208d 100644 --- a/mmv1/products/logging/FolderSettings.yaml +++ b/mmv1/products/logging/FolderSettings.yaml @@ -51,7 +51,7 @@ examples: test_env_vars: org_id: 'ORG_ID' test_vars_overrides: - 'key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' parameters: - name: 'folder' type: String diff --git a/mmv1/products/logging/LinkedDataset.yaml b/mmv1/products/logging/LinkedDataset.yaml index 91de68f84427..d646e3abdcea 100644 --- a/mmv1/products/logging/LinkedDataset.yaml +++ b/mmv1/products/logging/LinkedDataset.yaml @@ -91,7 +91,7 @@ parameters: url_param_only: true immutable: true default_from_api: true - # Make this a String for now since we don't have a good way to reference multiple resources. + # Make this a String for now since we don't have a good way to reference multiple resources. - name: 'bucket' type: String description: The bucket to which the linked dataset is attached. diff --git a/mmv1/products/logging/LogView.yaml b/mmv1/products/logging/LogView.yaml index 34d5c90503ce..6ff4b80e05aa 100644 --- a/mmv1/products/logging/LogView.yaml +++ b/mmv1/products/logging/LogView.yaml @@ -78,7 +78,7 @@ parameters: url_param_only: true immutable: true default_from_api: true - # Make this a String for now since we don't have a good way to reference multiple resources. + # Make this a String for now since we don't have a good way to reference multiple resources. - name: 'bucket' type: String description: The bucket of the resource diff --git a/mmv1/products/looker/Instance.yaml b/mmv1/products/looker/Instance.yaml index 8378769b923f..1c3337c9fbff 100644 --- a/mmv1/products/looker/Instance.yaml +++ b/mmv1/products/looker/Instance.yaml @@ -38,9 +38,10 @@ async: base_url: '{{op_id}}' result: resource_inside_response: true +deletion_policy_default: "DEFAULT" +deletion_policy_custom_docs: true exclude_sweeper: true error_abort_predicates: - - 'transport_tpg.Is429QuotaError' examples: - name: 'looker_instance_basic' @@ -83,9 +84,9 @@ examples: client_id: 'my-client-id' client_secret: 'my-client-secret' test_vars_overrides: - 'address_name': 'acctest.BootstrapSharedTestGlobalAddress(t, "looker-vpc-network-3", acctest.AddressWithPrefixLength(8))' - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "looker-vpc-network-3", acctest.ServiceNetworkWithPrefixLength(8))' + 'address_name': 'compute.BootstrapSharedTestGlobalAddress(t, "looker-vpc-network-3", compute.AddressWithPrefixLength(8))' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "looker-vpc-network-3", servicenetworking.ServiceNetworkWithPrefixLength(8))' exclude_docs: true - name: 'looker_instance_custom_domain' primary_resource_id: 'looker-instance' @@ -110,13 +111,21 @@ examples: - 'deletion_policy' virtual_fields: - name: 'deletion_policy' - default_value: "DEFAULT" type: String description: | Policy to determine if the cluster should be deleted forcefully. If setting deletion_policy = "FORCE", the Looker instance will be deleted regardless of its nested resources. If set to "DEFAULT", Looker instances that still have - nested resources will return an error. Possible values: DEFAULT, FORCE + nested resources will return an error. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". + + Possible values: DEFAULT, FORCE, PREVENT, ABANDON, DELETE + exclude: true custom_code: pre_delete: templates/terraform/pre_delete/looker_instance.go.tmpl parameters: diff --git a/mmv1/products/lustre/Instance.yaml b/mmv1/products/lustre/Instance.yaml index a4a1f3af1025..9b51a164463a 100644 --- a/mmv1/products/lustre/Instance.yaml +++ b/mmv1/products/lustre/Instance.yaml @@ -34,8 +34,8 @@ sweeper: url_substitutions: - location: "us-central1-a" - location: "us-central1-c" +custom_code: examples: - - name: lustre_instance_basic primary_resource_id: 'instance' vars: @@ -44,7 +44,7 @@ examples: network_name: 'my-network' subnetwork_name: 'my-subnetwork' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "default-vpc")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "default-vpc")' autogen_async: true async: operation: diff --git a/mmv1/products/managedkafka/Cluster.yaml b/mmv1/products/managedkafka/Cluster.yaml index dfcab50890f1..7208f02d480a 100644 --- a/mmv1/products/managedkafka/Cluster.yaml +++ b/mmv1/products/managedkafka/Cluster.yaml @@ -61,7 +61,7 @@ examples: - member: "serviceAccount:service-{project_number}@gcp-sa-managedkafka.iam.gserviceaccount.com" role: "roles/cloudkms.cryptoKeyEncrypterDecrypter" test_vars_overrides: - key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + key_name: 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' external_providers: ["time"] parameters: - name: 'location' diff --git a/mmv1/products/memcache/Instance.yaml b/mmv1/products/memcache/Instance.yaml index 9eacf1c511b0..0bb8f66174c6 100644 --- a/mmv1/products/memcache/Instance.yaml +++ b/mmv1/products/memcache/Instance.yaml @@ -54,7 +54,7 @@ examples: instance_name: test-instance network_name: test-network test_vars_overrides: - network_name: acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1") + network_name: servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1") # for backward compatible address_name: '"address" + randomSuffix' virtual_fields: diff --git a/mmv1/products/memorystore/Instance.yaml b/mmv1/products/memorystore/Instance.yaml index b29f279c7f3e..3a281cc7ba67 100644 --- a/mmv1/products/memorystore/Instance.yaml +++ b/mmv1/products/memorystore/Instance.yaml @@ -71,7 +71,7 @@ examples: kms_key_name: 'my-key' test_vars_overrides: 'prevent_destroy': 'false' - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' ignore_read_extra: - 'update_time' - name: 'memorystore_instance_persistence_aof' diff --git a/mmv1/products/metastore/Service.yaml b/mmv1/products/metastore/Service.yaml index e657bf2dc4e7..979c7826df77 100644 --- a/mmv1/products/metastore/Service.yaml +++ b/mmv1/products/metastore/Service.yaml @@ -70,7 +70,7 @@ examples: metastore_service_name: 'example-service' kms_key_name: 'example-key' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-metastore-service-key1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-metastore-service-key1").CryptoKey.Name' exclude_docs: true skip_vcr: true - name: 'dataproc_metastore_service_cmek_example' diff --git a/mmv1/products/migrationcenter/AssetsExportJob.yaml b/mmv1/products/migrationcenter/AssetsExportJob.yaml new file mode 100644 index 000000000000..84f1415e9584 --- /dev/null +++ b/mmv1/products/migrationcenter/AssetsExportJob.yaml @@ -0,0 +1,270 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: AssetsExportJob +description: AssetsExportJob represents a batch job that exports Migration Center assets to external destinations such as Cloud Storage. +base_url: projects/{{project}}/locations/{{location}}/assetsExportJobs +immutable: true +self_link: projects/{{project}}/locations/{{location}}/assetsExportJobs/{{assets_export_job_id}} +create_url: projects/{{project}}/locations/{{location}}/assetsExportJobs?assetsExportJobId={{assets_export_job_id}} +import_format: + - projects/{{project}}/locations/{{location}}/assetsExportJobs/{{assets_export_job_id}} +async: + operation: + base_url: '{{op_id}}' + actions: + - create + - delete + result: + resource_inside_response: true +autogen_status: QXNzZXRzRXhwb3J0Sm9i +autogen_async: true +examples: + - name: 'migration_center_assets_export_job_basic' + primary_resource_id: 'default' + vars: + assets_export_job_id: 'assets-export-job-test' +parameters: + - name: location + type: String + required: true + description: Resource ID segment making up resource `name`. It identifies the resource within its parent collection as described in https://google.aip.dev/122. + immutable: true + url_param_only: true + - name: assetsExportJobId + type: String + required: true + description: The ID to use for the asset export job. + immutable: true + url_param_only: true +properties: + - name: condition + type: NestedObject + description: Conditions for selecting assets to export. + properties: + - name: filter + type: String + description: Assets filter, supports the same syntax as asset listing. + - name: createTime + type: String + description: Resource creation time. + output: true + - name: inventory + type: NestedObject + description: Configuration for asset inventory details exports. + output: true + properties: [] + - name: labels + type: KeyValueLabels + description: |- + Labels as key value pairs. + Labels must meet the following constraints: + + * Keys and values can contain only lowercase letters, numeric characters, + underscores, and dashes. + * All characters must use UTF-8 encoding, and international characters are + allowed. + * Keys must start with a lowercase letter or international character. + * Each resource is limited to a maximum of 64 labels. + + Both keys and values are additionally constrained to be <= 128 bytes. + - name: name + type: String + description: Identifier. Resource name. + output: true + - name: networkDependencies + type: NestedObject + description: Configuration for network dependencies exports. + output: true + properties: [] + - name: performanceData + type: NestedObject + description: Configuration for performance data exports. + properties: + - name: maxDays + type: Integer + description: |- + When this value is set to a positive integer, + performance data will be returned for the most recent days + for which data is available. When this value is unset (or set to zero), + all available data is returned. + The maximum value is 420; values above 420 will be coerced to 420. + If unset (0 value) a default value of 40 will be used. + - name: recentExecutions + type: Array + description: Recent non expired executions of the job. + output: true + item_type: + type: NestedObject + properties: + - name: endTime + type: String + description: Completion time of the export. + output: true + - name: executionId + type: String + description: Globally unique identifier of the execution. + output: true + - name: expireTime + type: String + description: Expiration time for the export and artifacts. + output: true + - name: requestedAssetCount + type: Integer + description: |- + Number of assets requested for export after resolving the requested + filters. + output: true + - name: result + type: NestedObject + description: Contains the result of the assets export. + output: true + properties: + - name: error + type: NestedObject + description: |- + The `Status` type defines a logical error model that is suitable for + different programming environments, including REST APIs and RPC APIs. It is + used by [gRPC](https://github.com/grpc). Each `Status` message contains + three pieces of data: error code, error message, and error details. + + You can find out more about this error model and how to work with it in the + [API Design Guide](https://cloud.google.com/apis/design/errors). + output: true + properties: + - name: code + type: Integer + description: The status code, which should be an enum value of google.rpc.Code. + output: true + - name: details + type: Array + description: |- + A list of messages that carry the error details. There is a common set of + message types for APIs to use. + output: true + item_type: + type: NestedObject + properties: [] + - name: message + type: String + description: |- + A developer-facing error message, which should be in English. Any + user-facing error message should be localized and sent in the + google.rpc.Status.details field, or localized by the client. + output: true + - name: outputFiles + type: NestedObject + description: Contains a list of output files. + output: true + properties: + - name: entries + type: Array + description: List of output files. + output: true + item_type: + type: NestedObject + properties: + - name: csvOutputFile + type: NestedObject + description: Contains a single output file of type CSV. + output: true + properties: + - name: columnsCount + type: Integer + description: Number of columns in the file. + output: true + - name: rowCount + type: Integer + description: Number of rows in the file. + output: true + - name: signedUri + type: NestedObject + description: Contains a signed URI. + output: true + properties: + - name: file + type: String + description: Name of the file the Signed URI references. + output: true + - name: uri + type: String + description: Download URI for the file. + output: true + - name: fileSizeBytes + type: String + description: File size in bytes. + output: true + - name: xlsxOutputFile + type: NestedObject + description: Contains a single output file of type XLSX. + output: true + properties: + - name: signedUri + type: NestedObject + description: Contains a signed URI. + output: true + properties: + - name: file + type: String + description: Name of the file the Signed URI references. + output: true + - name: uri + type: String + description: Download URI for the file. + output: true + - name: signedUris + type: NestedObject + description: Contains a list of Signed URIs. + output: true + properties: + - name: signedUris + type: Array + description: List of signed URIs. + output: true + item_type: + type: NestedObject + properties: + - name: file + type: String + description: Name of the file the Signed URI references. + output: true + - name: uri + type: String + description: Download URI for the file. + output: true + - name: startTime + type: String + description: Execution timestamp. + output: true + - name: showHidden + type: Boolean + description: |- + When this value is set to 'true' the response will include all assets, + including those that are hidden. + - name: signedUriDestination + type: NestedObject + description: Signed URI destination configuration. + properties: + - name: fileFormat + type: String + required: true + description: |- + The file format to export. + Possible values: + CSV + XLSX + - name: updateTime + type: String + description: Resource update time. + output: true diff --git a/mmv1/products/migrationcenter/ReportConfig.yaml b/mmv1/products/migrationcenter/ReportConfig.yaml new file mode 100644 index 000000000000..ef61f7c566c1 --- /dev/null +++ b/mmv1/products/migrationcenter/ReportConfig.yaml @@ -0,0 +1,91 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: ReportConfig +description: ReportConfig defines the configuration and criteria used to generate Migration Center reports. +base_url: projects/{{project}}/locations/{{location}}/reportConfigs +immutable: true +self_link: projects/{{project}}/locations/{{location}}/reportConfigs/{{report_config_id}} +create_url: projects/{{project}}/locations/{{location}}/reportConfigs?reportConfigId={{report_config_id}} +import_format: + - projects/{{project}}/locations/{{location}}/reportConfigs/{{report_config_id}} +async: + operation: + base_url: '{{op_id}}' + actions: + - create + - delete + result: + resource_inside_response: true +autogen_status: UmVwb3J0Q29uZmln +autogen_async: true +examples: + - name: 'migration_center_report_config_basic' + primary_resource_id: 'default' + vars: + report_config_id: 'report-config-test' + pref_set_id: 'pref-set-test' + group_id: 'group-test' +parameters: + - name: location + type: String + required: true + description: Resource ID segment making up resource `name`. It identifies the resource within its parent collection as described in https://google.aip.dev/122. + immutable: true + url_param_only: true + - name: reportConfigId + type: String + required: true + description: |- + User specified ID for the report config. It will become the last component + of the report config name. The ID must be unique within the project, must + conform with RFC-1034, is restricted to lower-cased letters, and has a + maximum length of 63 characters. The ID must match the regular expression: + [a-z]([a-z0-9-]{0,61}[a-z0-9])?. + immutable: true + url_param_only: true +properties: + - name: createTime + type: String + description: The timestamp when the resource was created. + output: true + - name: description + type: String + description: Free-text description. + - name: displayName + type: String + description: User-friendly display name. Maximum length is 63 characters. + - name: groupPreferencesetAssignments + type: Array + required: true + description: Collection of combinations of groups and preference sets. + item_type: + type: NestedObject + properties: + - name: group + type: String + required: true + description: Name of the group. + - name: preferenceSet + type: String + required: true + description: Name of the Preference Set. + - name: name + type: String + description: Name of resource. + output: true + - name: updateTime + type: String + description: The timestamp when the resource was last updated. + output: true diff --git a/mmv1/products/migrationcenter/Settings.yaml b/mmv1/products/migrationcenter/Settings.yaml new file mode 100644 index 000000000000..13bc04fb3d81 --- /dev/null +++ b/mmv1/products/migrationcenter/Settings.yaml @@ -0,0 +1,64 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: Settings +description: Settings represents the global or regional settings configuration for a Migration Center project. +base_url: projects/{{project}}/locations/{{location}}/settings +self_link: projects/{{project}}/locations/{{location}}/settings +create_url: projects/{{project}}/locations/{{location}}/settings?updateMask=* +update_mask: true +create_verb: PATCH +update_verb: PATCH +import_format: + - projects/{{project}}/locations/{{location}}/settings +async: + operation: + base_url: '{{op_id}}' + actions: + - update + result: + resource_inside_response: true +custom_code: + custom_delete: 'templates/terraform/custom_delete/clear_migration_center_settings.go.tmpl' + test_check_destroy: 'templates/terraform/custom_check_destroy/skip_delete_during_test.go.tmpl' +autogen_status: U2V0dGluZ3M= +autogen_async: true +examples: + - name: 'migration_center_settings_basic' + primary_resource_id: 'default' + # Exclude basic test as this is a singleton and conflicts with the update test + # The update test covers this scenario + exclude_test: true + vars: + pref_set_id: 'pref-set-test' +parameters: + - name: location + type: String + required: true + description: Resource ID segment making up resource `name`. It identifies the resource within its parent collection as described in https://google.aip.dev/122. + immutable: true + url_param_only: true +properties: + - name: disableCloudLogging + type: Boolean + description: |- + Disable Cloud Logging for the Migration Center API. + Users are billed for the logs. + - name: name + type: String + description: The name of the resource. + output: true + - name: preferenceSet + type: String + description: The preference set used by default for a project. diff --git a/mmv1/products/migrationcenter/Source.yaml b/mmv1/products/migrationcenter/Source.yaml new file mode 100644 index 000000000000..f910aefe5ea8 --- /dev/null +++ b/mmv1/products/migrationcenter/Source.yaml @@ -0,0 +1,112 @@ +# Copyright 2026 Google Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +name: Source +description: Source represents a data source from which asset discovery data is ingested into Migration Center. +base_url: projects/{{project}}/locations/{{location}}/sources +self_link: projects/{{project}}/locations/{{location}}/sources/{{source_id}} +create_url: projects/{{project}}/locations/{{location}}/sources?sourceId={{source_id}} +update_mask: true +update_verb: PATCH +import_format: + - projects/{{project}}/locations/{{location}}/sources/{{source_id}} +async: + operation: + base_url: '{{op_id}}' + actions: + - create + - update + - delete + result: + resource_inside_response: true +autogen_status: U291cmNl +autogen_async: true +examples: + - name: 'migration_center_source_basic' + primary_resource_id: 'default' + vars: + source_id: 'source-test' +parameters: + - name: location + type: String + required: true + description: Resource ID segment making up resource `name`. It identifies the resource within its parent collection as described in https://google.aip.dev/122. + immutable: true + url_param_only: true + - name: sourceId + type: String + required: true + description: |- + User specified ID for the source. It will become the last component of the + source name. The ID must be unique within the project, must conform with + RFC-1034, is restricted to lower-cased letters, and has a maximum + length of 63 characters. The ID must match the + regular expression: `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. + immutable: true + url_param_only: true +properties: + - name: createTime + type: String + description: The timestamp when the source was created. + output: true + - name: description + type: String + description: Free-text description. + - name: displayName + type: String + description: User-friendly display name. + - name: errorFrameCount + type: Integer + description: The number of frames that were reported by the source and contained errors. + output: true + - name: managed + type: Boolean + description: If `true`, the source is managed by other service(s). + - name: name + type: String + description: The full name of the source. + output: true + - name: pendingFrameCount + type: Integer + description: Number of frames that are still being processed. + output: true + - name: priority + type: Integer + description: |- + The information confidence of the source. + The higher the value, the higher the confidence. + - name: state + type: String + description: |- + The state of the source. + Possible values: + ACTIVE + DELETING + INVALID + output: true + - name: type + type: String + description: |- + Data source type. + Possible values: + SOURCE_TYPE_UNKNOWN + SOURCE_TYPE_UPLOAD + SOURCE_TYPE_GUEST_OS_SCAN + SOURCE_TYPE_INVENTORY_SCAN + SOURCE_TYPE_CUSTOM + SOURCE_TYPE_DISCOVERY_CLIENT + - name: updateTime + type: String + description: The timestamp when the source was last updated. + output: true diff --git a/mmv1/products/modelarmor/Template.yaml b/mmv1/products/modelarmor/Template.yaml index 27ba82f9f3bb..01cbdb356df8 100644 --- a/mmv1/products/modelarmor/Template.yaml +++ b/mmv1/products/modelarmor/Template.yaml @@ -111,6 +111,8 @@ examples: filter_config_sdp_settings_advanced_config_deidentify_template: '"projects/llm-firewall-demo/locations/us-central1/deidentifyTemplates/t2"' filter_config_sdp_settings_basic_config_filter_enforcement: '"ENABLED"' template_metadata_multi_language_detection_enable_multi_language_detection: false +custom_code: + pre_update: 'templates/terraform/pre_update/modelarmor_template.go.tmpl' autogen_status: VGVtcGxhdGU= parameters: - name: location @@ -257,6 +259,8 @@ properties: type: NestedObject description: Message describing TemplateMetadata allow_empty_object: true + default_from_api: true + custom_flatten: 'templates/terraform/custom_flatten/modelarmor_template_template_metadata.go.tmpl' properties: - name: logTemplateOperations type: Boolean @@ -267,7 +271,6 @@ properties: - name: multiLanguageDetection type: NestedObject description: Metadata to enable multi language detection via template. - custom_flatten: 'templates/terraform/custom_flatten/modelarmor_template_multilanguage_detection.go.tmpl' properties: - name: enableMultiLanguageDetection type: Boolean diff --git a/mmv1/products/monitoring/AlertPolicy.yaml b/mmv1/products/monitoring/AlertPolicy.yaml index 44c2772e81df..2668843a9692 100644 --- a/mmv1/products/monitoring/AlertPolicy.yaml +++ b/mmv1/products/monitoring/AlertPolicy.yaml @@ -638,14 +638,19 @@ properties: - name: 'comparison' type: Enum description: | - The comparison to apply between the time - series (indicated by filter and aggregation) - and the threshold (indicated by - threshold_value). The comparison is applied - on each time series, with the time series on - the left-hand side and the threshold on the - right-hand side. Only COMPARISON_LT and - COMPARISON_GT are supported currently. + The comparison to apply between the time series + (indicated by filter and aggregation) and the threshold + (indicated by threshold_value). The comparison is + applied on each time series, with the time series on + the left-hand side and the threshold on the right-hand + side. + + The Cloud Monitoring API only supports `COMPARISON_LT` + and `COMPARISON_GT` for metric-threshold conditions; the + other values are kept in the schema for backward + compatibility with imported state but will be rejected + by the API. See + https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies#MetricThreshold. required: true enum_values: - 'COMPARISON_GT' @@ -1058,14 +1063,20 @@ properties: - name: 'comparison' type: Enum description: | - The comparison to apply between the time - series (indicated by filter and aggregation) - and the threshold (indicated by - threshold_value). The comparison is applied - on each time series, with the time series on - the left-hand side and the threshold on the - right-hand side. Only COMPARISON_LT and - COMPARISON_GT are supported currently. + The comparison to apply between the time series + (indicated by filter and aggregation) and the + threshold (indicated by threshold_value). The + comparison is applied on each time series, with + the time series on the left-hand side and the + threshold on the right-hand side. + + The Cloud Monitoring API only supports + `COMPARISON_LT` and `COMPARISON_GT` for SQL + row-count thresholds; the other values are kept + in the schema for backward compatibility with + imported state but will be rejected by the API. + See + https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies#MetricThreshold. enum_values: - 'COMPARISON_GT' - 'COMPARISON_GE' diff --git a/mmv1/products/netapp/Backup.yaml b/mmv1/products/netapp/Backup.yaml index 4eb21d4109af..0b603864186d 100644 --- a/mmv1/products/netapp/Backup.yaml +++ b/mmv1/products/netapp/Backup.yaml @@ -60,6 +60,7 @@ async: # Skipping the sweeper since we need to sweep multiple regions exclude_sweeper: true include_in_tgc_next: true +custom_code: examples: - name: 'netapp_backup' primary_resource_id: 'test_backup' @@ -70,7 +71,7 @@ examples: backup_name: 'test-backup' network_name: 'network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' parameters: - name: 'location' type: String @@ -144,6 +145,32 @@ properties: Format: `projects/{{projectId}}/locations/{{location}}/volumes/{{volumename}}/snapshots/{{snapshotname}}`` required: false diff_suppress_func: 'tpgresource.ProjectNumberDiffSuppress' + - name: 'ontapSource' + type: NestedObject + description: | + Details of the ONTAP source volume and snapshot. + required: false + immutable: true + min_version: beta + properties: + - name: 'storagePool' + type: String + description: | + Name of the storage pool. This must be specified for creating backups for ONTAP mode volumes. + Format: `projects/{{project}}/locations/{{location}}/storagePools/{{storage_pool_id}}` + required: true + immutable: true + - name: 'volumeUuid' + type: String + description: | + The UUID of the ONTAP source volume. + required: true + immutable: true + - name: 'snapshotUuid' + type: String + description: | + The UUID of the ONTAP source snapshot. + immutable: true - name: 'volumeRegion' type: String description: | diff --git a/mmv1/products/netapp/StoragePool.yaml b/mmv1/products/netapp/StoragePool.yaml index 1804f7853548..662100f706bd 100644 --- a/mmv1/products/netapp/StoragePool.yaml +++ b/mmv1/products/netapp/StoragePool.yaml @@ -76,7 +76,7 @@ examples: pool_name: 'test-pool' network_name: 'test-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' exclude_docs: true - name: 'Storage_pool_create_doc' primary_resource_id: 'test_pool' diff --git a/mmv1/products/netapp/Volume.yaml b/mmv1/products/netapp/Volume.yaml index 4ad3b14d5c15..5fea5e9628de 100644 --- a/mmv1/products/netapp/Volume.yaml +++ b/mmv1/products/netapp/Volume.yaml @@ -51,6 +51,8 @@ custom_code: pre_delete: 'templates/terraform/pre_delete/netapp_volume_force_delete.go.tmpl' pre_update: 'templates/terraform/pre_update/netapp_volume_update.go.tmpl' constants: 'templates/terraform/constants/netapp_volume.go.tmpl' +deletion_policy_default: "DEFAULT" +deletion_policy_custom_docs: true examples: - name: 'netapp_volume_basic' primary_resource_id: 'test_volume' @@ -59,7 +61,7 @@ examples: pool_name: 'test-pool' network_name: 'test-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' ignore_read_extra: - 'deletion_policy' virtual_fields: @@ -68,9 +70,16 @@ virtual_fields: Policy to determine if the volume should be deleted forcefully. Volumes may have nested snapshot resources. Deleting such a volume will fail. Setting this parameter to FORCE will delete volumes including nested snapshots. - Possible values: DEFAULT, FORCE. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "DEFAULT". + + Possible values: DEFAULT, FORCE, PREVENT, ABANDON, DELETE. type: String - default_value: "DEFAULT" + exclude: true parameters: - name: 'location' type: String diff --git a/mmv1/products/netapp/VolumeQuotaRule.yaml b/mmv1/products/netapp/VolumeQuotaRule.yaml index bd80d2b0fe0c..d47053021621 100644 --- a/mmv1/products/netapp/VolumeQuotaRule.yaml +++ b/mmv1/products/netapp/VolumeQuotaRule.yaml @@ -52,7 +52,7 @@ examples: network_name: 'test-network' quota_rule_name: 'test-volume-quota-rule' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' parameters: - name: 'location' type: String diff --git a/mmv1/products/netapp/VolumeReplication.yaml b/mmv1/products/netapp/VolumeReplication.yaml index 5e83a7fe45c3..aca8b79c20d5 100644 --- a/mmv1/products/netapp/VolumeReplication.yaml +++ b/mmv1/products/netapp/VolumeReplication.yaml @@ -72,7 +72,7 @@ examples: destination_volume: 'destination-volume' network_name: 'test-network' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' ignore_read_extra: - 'delete_destination_volume' - 'replication_enabled' diff --git a/mmv1/products/netapp/VolumeSnapshot.yaml b/mmv1/products/netapp/VolumeSnapshot.yaml index 46809bf73d1d..f456c98cb507 100644 --- a/mmv1/products/netapp/VolumeSnapshot.yaml +++ b/mmv1/products/netapp/VolumeSnapshot.yaml @@ -57,7 +57,7 @@ examples: network_name: 'test-network' snap_name: 'testvolumesnap' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog"))' # for backward compatible snap_name: '"testvolumesnap" + randomSuffix' parameters: diff --git a/mmv1/products/netapp/kmsconfig.yaml b/mmv1/products/netapp/kmsconfig.yaml index 1f52337586de..b47bb1f54e27 100644 --- a/mmv1/products/netapp/kmsconfig.yaml +++ b/mmv1/products/netapp/kmsconfig.yaml @@ -63,7 +63,7 @@ examples: kms_name: 'kms-test' kms_key_name: 'crypto-name' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-netapp-kmsconfig-key1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-netapp-kmsconfig-key1").CryptoKey.Name' parameters: - name: 'location' type: String diff --git a/mmv1/products/networkconnectivity/Destination.yaml b/mmv1/products/networkconnectivity/Destination.yaml index d93b9d48c3b3..c3f8072fb616 100644 --- a/mmv1/products/networkconnectivity/Destination.yaml +++ b/mmv1/products/networkconnectivity/Destination.yaml @@ -41,6 +41,13 @@ examples: config_name: "basic-config" destination_name: "basic-destination" +sweeper: + parent: + resource_type: "google_network_connectivity_multicloud_data_transfer_config" + child_field: "multicloud_data_transfer_config" + parent_field: "name" + parent_field_extract_name: true + parameters: - name: 'multicloudDataTransferConfig' type: String @@ -56,13 +63,12 @@ parameters: url_param_only: true description: | The location of the destination. - properties: - name: 'name' type: String required: true immutable: true - url_param_only: true + ignore_read: true description: | The name of the destination. - name: 'createTime' diff --git a/mmv1/products/networkconnectivity/Group.yaml b/mmv1/products/networkconnectivity/Group.yaml index f76cfc86ef8b..29b5d4230b62 100644 --- a/mmv1/products/networkconnectivity/Group.yaml +++ b/mmv1/products/networkconnectivity/Group.yaml @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +--- name: Group include_in_tgc_next: true legacy_long_form_project: true diff --git a/mmv1/products/networkconnectivity/MulticloudDataTransferConfig.yaml b/mmv1/products/networkconnectivity/MulticloudDataTransferConfig.yaml index 42dcb7ff37b4..2557080b1ced 100644 --- a/mmv1/products/networkconnectivity/MulticloudDataTransferConfig.yaml +++ b/mmv1/products/networkconnectivity/MulticloudDataTransferConfig.yaml @@ -39,6 +39,13 @@ examples: vars: config_name: "basic_config" +sweeper: + url_substitutions: + - region: "europe-west1" + - region: "europe-west2" + - region: "europe-west3" + - region: "europe-west4" + parameters: - name: 'location' type: String @@ -53,7 +60,7 @@ properties: type: String required: true immutable: true - url_param_only: true + ignore_read: true description: | The name of the MulticloudDataTransferConfig resource. - name: 'createTime' diff --git a/mmv1/products/networkconnectivity/PolicyBasedRoute.yaml b/mmv1/products/networkconnectivity/PolicyBasedRoute.yaml index e8d238f8de80..7bd7358b2ab3 100644 --- a/mmv1/products/networkconnectivity/PolicyBasedRoute.yaml +++ b/mmv1/products/networkconnectivity/PolicyBasedRoute.yaml @@ -89,7 +89,7 @@ properties: enum_values: - 'IPV4' - 'IPV6' - # probably could have been an enum, but it's a string in the API + # probably could have been an enum, but it's a string in the API - name: 'ipProtocol' type: String description: | @@ -181,7 +181,7 @@ properties: item_type: type: NestedObject properties: - # technically enum, but doesn't matter for output fields + # technically enum, but doesn't matter for output fields - name: 'code' type: String description: | diff --git a/mmv1/products/networkconnectivity/Spoke.yaml b/mmv1/products/networkconnectivity/Spoke.yaml index 26c14c06f814..c31fdc2c491d 100644 --- a/mmv1/products/networkconnectivity/Spoke.yaml +++ b/mmv1/products/networkconnectivity/Spoke.yaml @@ -86,7 +86,7 @@ examples: hub_name: 'basic-hub1' vpn_tunnel_1_spoke_name: 'vpn-tunnel-1-spoke' vpn_tunnel_2_spoke_name: 'vpn-tunnel-2-spoke' - # Skip due to multiple fine-grained resources + # Skip due to multiple fine-grained resources test_vars_overrides: # for backward compatible vpn_tunnel_1_name: '"tunnel1" + randomSuffix' diff --git a/mmv1/products/networkconnectivity/Transport.yaml b/mmv1/products/networkconnectivity/Transport.yaml index 0696c9fc7a58..ac599be9c39b 100644 --- a/mmv1/products/networkconnectivity/Transport.yaml +++ b/mmv1/products/networkconnectivity/Transport.yaml @@ -17,8 +17,8 @@ description: | The Transport resource is a top-level resource used by customers to control Partner Cross-Cloud Interconnect (CCI) connections. references: guides: - 'Official Documentation': 'https://docs.cloud.google.com/sdk/gcloud/reference/beta/network-connectivity/transports' - api: 'https://cloud.google.com/network-connectivity/docs/reference/networkconnectivity/rest/v1beta/projects.locations.transport' + 'Official Documentation': 'https://docs.cloud.google.com/sdk/gcloud/reference/network-connectivity/transports' + api: 'https://docs.cloud.google.com/network-connectivity/docs/reference/networkconnectivity/rest/v1/projects.locations.transports' docs: base_url: 'projects/{{project}}/locations/{{region}}/transports' self_link: 'projects/{{project}}/locations/{{region}}/transports/{{name}}' @@ -36,7 +36,6 @@ async: result: resource_inside_response: false collection_url_key: 'items' -min_version: 'beta' examples: - name: 'network_connectivity_transport_basic' primary_resource_id: 'primary' @@ -114,6 +113,7 @@ properties: type: Boolean description: | Administrative state of the underlying connectivity. If set to true (default), connectivity should be available between your environments. If set to false, the connectivity over these links is disabled. Disabling your Transport does not affect billing, and retains the underlying network bandwidth associated with the connectivity. + min_version: 'beta' send_empty_value: true default_value: true - name: 'network' @@ -143,6 +143,7 @@ properties: type: ResourceRef description: | The NCC Hub that the Transport should attach to. The hub must be in the same project as the Transport. + min_version: 'beta' resource: 'Hub' imports: 'selfLink' immutable: true @@ -150,6 +151,7 @@ properties: type: Boolean description: | Controls whether a Routing VPC Spoke should be created and attached to the NCC Hub. + min_version: 'beta' send_empty_value: true default_value: false immutable: true @@ -157,6 +159,7 @@ properties: type: Boolean description: | Controls whether resources proposed by the Transport are automatically accepted on behalf of the user. + min_version: 'beta' send_empty_value: true default_value: false immutable: true diff --git a/mmv1/products/networksecurity/FirewallEndpoint.yaml b/mmv1/products/networksecurity/FirewallEndpoint.yaml index 6d60d4e30088..4db480864c3e 100644 --- a/mmv1/products/networksecurity/FirewallEndpoint.yaml +++ b/mmv1/products/networksecurity/FirewallEndpoint.yaml @@ -59,7 +59,7 @@ examples: test_env_vars: org_id: 'ORG_ID' project: 'PROJECT_NAME' - # update tests will take care of create and update. Firewall endpoint creation is too long. + # update tests will take care of create and update. Firewall endpoint creation is too long. exclude_test: true - name: 'network_security_firewall_endpoint_project' primary_resource_id: 'default' @@ -67,7 +67,7 @@ examples: resource_name: 'my-firewall-endpoint' test_env_vars: project: 'PROJECT_NAME' - # update tests will take care of create and update. Firewall endpoint creation is too long. + # update tests will take care of create and update. Firewall endpoint creation is too long. exclude_test: true parameters: - name: 'name' diff --git a/mmv1/products/networkservices/EdgeCacheOrigin.yaml b/mmv1/products/networkservices/EdgeCacheOrigin.yaml index 1680c2a76e98..18888b71cc11 100644 --- a/mmv1/products/networkservices/EdgeCacheOrigin.yaml +++ b/mmv1/products/networkservices/EdgeCacheOrigin.yaml @@ -92,7 +92,7 @@ properties: When providing an FQDN (hostname), it must be publicly resolvable (e.g. via Google public DNS) and IP addresses must be publicly routable. It must not contain a protocol (e.g., https://) and it must not contain any slashes. If a Cloud Storage bucket is provided, it must be in the canonical "gs://bucketname" format. Other forms, such as "storage.googleapis.com", will be rejected. required: true - # default http2 from api + # default http2 from api - name: 'protocol' type: Enum description: | @@ -104,7 +104,7 @@ properties: - 'HTTP2' - 'HTTPS' - 'HTTP' - # default from api + # default from api - name: 'port' type: Integer description: | @@ -137,7 +137,7 @@ properties: The value of timeout.maxAttemptsTimeout dictates the timeout across all origins. A reference to a Topic resource. diff_suppress_func: 'tpgresource.CompareResourceNames' - # default CONNECT_FAILURE from api + # default CONNECT_FAILURE from api - name: 'retryConditions' type: Array description: | diff --git a/mmv1/products/networkservices/EdgeCacheService.yaml b/mmv1/products/networkservices/EdgeCacheService.yaml index 7b0c5dd0f621..062a8cf52578 100644 --- a/mmv1/products/networkservices/EdgeCacheService.yaml +++ b/mmv1/products/networkservices/EdgeCacheService.yaml @@ -82,13 +82,13 @@ properties: - name: 'labels' type: KeyValueLabels description: 'Set of label tags associated with the EdgeCache resource.' - # default from api + # default from api - name: 'disableQuic' type: Boolean description: | HTTP/3 (IETF QUIC) and Google QUIC are enabled by default. default_from_api: true - # default from api + # default from api - name: 'disableHttp2' type: Boolean description: | @@ -238,7 +238,7 @@ properties: item_type: type: NestedObject properties: - # default from api + # default from api - name: 'ignoreCase' type: Boolean description: | @@ -327,9 +327,9 @@ properties: For satisfying the matchRule condition, the path of the request must exactly match the value specified in fullPathMatch after removing any query parameters and anchor that may be part of the original URL. min_size: 1 max_size: 5 - # TODO: (scottsuarez) conflicts also won't work for array path matchers yet, uncomment here once supported. - # conflicts: - # - Routing.PathMatcher.RouteRule.prefixMatch + # TODO: (scottsuarez) conflicts also won't work for array path matchers yet, uncomment here once supported. + # conflicts: + # - Routing.PathMatcher.RouteRule.prefixMatch - name: 'routeMethods' type: NestedObject description: | @@ -371,7 +371,7 @@ properties: description: | The value of the header to add. required: true - # default from api + # default from api - name: 'replace' type: Boolean description: | @@ -448,7 +448,7 @@ properties: description: | The policy to use for defining caching and signed request behaviour for requests that match this route. properties: - # default from api + # default from api - name: 'cacheMode' type: Enum description: | @@ -494,7 +494,7 @@ properties: A duration in seconds terminated by 's'. Example: "3s". default_from_api: true - # defalt from api + # defalt from api - name: 'maxTtl' type: String description: | @@ -518,7 +518,7 @@ properties: description: | Defines the request parameters that contribute to the cache key. properties: - # default from api + # default from api - name: 'includeProtocol' type: Boolean description: | @@ -624,7 +624,7 @@ properties: - 'DISABLED' - 'REQUIRE_SIGNATURES' - 'REQUIRE_TOKENS' - # resource ref, EdgeCacheKeyset? + # resource ref, EdgeCacheKeyset? - name: 'signedRequestKeyset' type: String description: | @@ -896,7 +896,7 @@ properties: - 'SEE_OTHER' - 'TEMPORARY_REDIRECT' - 'PERMANENT_REDIRECT' - # default from api + # default from api - name: 'httpsRedirect' type: Boolean description: | @@ -904,7 +904,7 @@ properties: This can only be set if there is at least one (1) edgeSslCertificate set on the service. default_from_api: true - # default from api + # default from api - name: 'stripQuery' type: Boolean description: | @@ -919,7 +919,7 @@ properties: description: | Specifies the logging options for the traffic served by this service. If logging is enabled, logs will be exported to Cloud Logging. properties: - # default from api + # default from api - name: 'enable' type: Boolean description: | diff --git a/mmv1/products/notebooks/Instance.yaml b/mmv1/products/notebooks/Instance.yaml index f96e1a6ed27d..4d23175130c8 100644 --- a/mmv1/products/notebooks/Instance.yaml +++ b/mmv1/products/notebooks/Instance.yaml @@ -102,7 +102,7 @@ examples: test_env_vars: service_account: 'SERVICE_ACCT' test_vars_overrides: - 'key_name': 'acctest.BootstrapKMSKeyInLocation(t, "global").CryptoKey.Name' + 'key_name': 'kms.BootstrapKMSKeyInLocation(t, "global").CryptoKey.Name' ignore_read_extra: - 'update_time' virtual_fields: diff --git a/mmv1/products/observability/FolderSettings.yaml b/mmv1/products/observability/FolderSettings.yaml index 09d0dabd67e8..1ecab27aaca0 100644 --- a/mmv1/products/observability/FolderSettings.yaml +++ b/mmv1/products/observability/FolderSettings.yaml @@ -53,7 +53,7 @@ examples: test_env_vars: org_id: 'ORG_ID' test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' # for backward compatible location: '"us" + randomSuffix' - name: "observability_folder_settings_basic_global" diff --git a/mmv1/products/observability/OrganizationSettings.yaml b/mmv1/products/observability/OrganizationSettings.yaml index 7d097f913753..13b5f61f35e0 100644 --- a/mmv1/products/observability/OrganizationSettings.yaml +++ b/mmv1/products/observability/OrganizationSettings.yaml @@ -50,7 +50,7 @@ examples: location: "us" kms_key_name: "example-key" test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' # for backward compatible location: '"us" + randomSuffix' test_env_vars: diff --git a/mmv1/products/observability/ProjectSettings.yaml b/mmv1/products/observability/ProjectSettings.yaml index b92b01a31a48..24f1d84ca6c7 100644 --- a/mmv1/products/observability/ProjectSettings.yaml +++ b/mmv1/products/observability/ProjectSettings.yaml @@ -53,7 +53,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCOUNT' test_vars_overrides: - kms_key_name: 'acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' + kms_key_name: 'kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name' # for backward compatible location: '"us" + randomSuffix' - name: "observability_project_settings_basic_global" diff --git a/mmv1/products/oracledatabase/CloudVmCluster.yaml b/mmv1/products/oracledatabase/CloudVmCluster.yaml index dcf3a3494c9d..f68b7d56e06f 100644 --- a/mmv1/products/oracledatabase/CloudVmCluster.yaml +++ b/mmv1/products/oracledatabase/CloudVmCluster.yaml @@ -349,3 +349,25 @@ properties: Format: projects/{project}/locations/{location}/odbNetworks/{odb_network}/odbSubnets/{odb_subnet} default_from_api: true + - name: 'identityConnector' + type: NestedObject + output: true + description: |- + The identity connector details which will allow OCI to securely access + the resources in the customer project. + properties: + - name: 'serviceAgentEmail' + type: String + output: true + description: 'A google managed service account on which customers can grant roles to access resources in the customer project.' + - name: 'connectionState' + type: String + output: true + description: |- + The connection state of the identity connector. + Possible values: + CONNECTION_STATE_UNSPECIFIED + CONNECTED + PARTIALLY_CONNECTED + DISCONNECTED + UNKNOWN diff --git a/mmv1/products/oracledatabase/DbSystem.yaml b/mmv1/products/oracledatabase/DbSystem.yaml index c1d425cc0a82..0151c526cce2 100644 --- a/mmv1/products/oracledatabase/DbSystem.yaml +++ b/mmv1/products/oracledatabase/DbSystem.yaml @@ -10,6 +10,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +--- name: DbSystem description: A DbSystem Resource base_url: projects/{{project}}/locations/{{location}}/dbSystems diff --git a/mmv1/products/osconfig/GuestPolicies.yaml b/mmv1/products/osconfig/GuestPolicies.yaml index bd37400aa888..455e3290fa95 100644 --- a/mmv1/products/osconfig/GuestPolicies.yaml +++ b/mmv1/products/osconfig/GuestPolicies.yaml @@ -45,21 +45,21 @@ examples: instance_name: 'guest-policy-inst' guest_policy_id: 'guest-policy' ignore_read_extra: - # project number is returned in rest response + # project number is returned in rest response - 'project' - name: 'os_config_guest_policies_packages' primary_resource_id: 'guest_policies' vars: guest_policy_id: 'guest-policy' ignore_read_extra: - # project number is returned in rest response + # project number is returned in rest response - 'project' - name: 'os_config_guest_policies_recipes' primary_resource_id: 'guest_policies' vars: guest_policy_id: 'guest-policy' ignore_read_extra: - # project number is returned in rest response + # project number is returned in rest response - 'project' parameters: - name: 'guestPolicyId' diff --git a/mmv1/products/parametermanager/Parameter.yaml b/mmv1/products/parametermanager/Parameter.yaml index f9deb64da177..24677a2d9184 100644 --- a/mmv1/products/parametermanager/Parameter.yaml +++ b/mmv1/products/parametermanager/Parameter.yaml @@ -30,6 +30,7 @@ timeouts: insert_minutes: 20 update_minutes: 20 delete_minutes: 20 +custom_code: examples: - name: 'parameter_config_basic' primary_resource_id: 'parameter-basic' @@ -58,7 +59,7 @@ examples: parameter_id: 'parameter' kms_key: 'kms-key' test_vars_overrides: - 'kms_key': 'acctest.BootstrapKMSKey(t).CryptoKey.Name' + 'kms_key': 'kms.BootstrapKMSKey(t).CryptoKey.Name' # for backward compatible parameter_id: '"parameter" + randomSuffix' bootstrap_iam: diff --git a/mmv1/products/parametermanager/ParameterVersion.yaml b/mmv1/products/parametermanager/ParameterVersion.yaml index dea76fafdfd7..4981e3d14b87 100644 --- a/mmv1/products/parametermanager/ParameterVersion.yaml +++ b/mmv1/products/parametermanager/ParameterVersion.yaml @@ -54,7 +54,7 @@ examples: parameter_version_id: 'parameter_version' kms_key: 'kms-key' test_vars_overrides: - 'kms_key': 'acctest.BootstrapKMSKey(t).CryptoKey.Name' + 'kms_key': 'kms.BootstrapKMSKey(t).CryptoKey.Name' # for backward compatible parameter_id: '"parameter" + randomSuffix' bootstrap_iam: diff --git a/mmv1/products/parametermanagerregional/RegionalParameter.yaml b/mmv1/products/parametermanagerregional/RegionalParameter.yaml index f0c428c82eee..697699f8520c 100644 --- a/mmv1/products/parametermanagerregional/RegionalParameter.yaml +++ b/mmv1/products/parametermanagerregional/RegionalParameter.yaml @@ -31,6 +31,7 @@ timeouts: insert_minutes: 20 update_minutes: 20 delete_minutes: 20 +custom_code: examples: - name: 'regional_parameter_basic' primary_resource_id: 'regional-parameter-basic' @@ -50,7 +51,7 @@ examples: parameter_id: 'regional_parameter' kms_key: 'kms-key' test_vars_overrides: - 'kms_key': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' bootstrap_iam: - member: "serviceAccount:service-{project_number}@gcp-sa-pm.iam.gserviceaccount.com" role: "roles/cloudkms.cryptoKeyEncrypterDecrypter" diff --git a/mmv1/products/parametermanagerregional/RegionalParameterVersion.yaml b/mmv1/products/parametermanagerregional/RegionalParameterVersion.yaml index 142281151b38..8bd5f7336eaa 100644 --- a/mmv1/products/parametermanagerregional/RegionalParameterVersion.yaml +++ b/mmv1/products/parametermanagerregional/RegionalParameterVersion.yaml @@ -54,7 +54,7 @@ examples: parameter_version_id: 'regional_parameter_version' kms_key: 'kms-key' test_vars_overrides: - 'kms_key': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' bootstrap_iam: - member: "serviceAccount:service-{project_number}@gcp-sa-pm.iam.gserviceaccount.com" role: "roles/cloudkms.cryptoKeyEncrypterDecrypter" diff --git a/mmv1/products/privateca/CaPool.yaml b/mmv1/products/privateca/CaPool.yaml index c94d9fe272bf..6551091a7e01 100644 --- a/mmv1/products/privateca/CaPool.yaml +++ b/mmv1/products/privateca/CaPool.yaml @@ -60,7 +60,7 @@ examples: name: 'my-pool' cloud_kms_key: 'projects/keys-project/locations/us-central1/keyRings/key-ring/cryptoKeys/crypto-key' test_vars_overrides: - 'cloud_kms_key': 'acctest.BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", "us-central1").CryptoKey.Name' + 'cloud_kms_key': 'kms.BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", "us-central1").CryptoKey.Name' # Test requires a beta-only resource min_version: beta - name: 'privateca_quickstart' diff --git a/mmv1/products/privateca/Certificate.yaml b/mmv1/products/privateca/Certificate.yaml index 0b5423280a78..58a65d46eac2 100644 --- a/mmv1/products/privateca/Certificate.yaml +++ b/mmv1/products/privateca/Certificate.yaml @@ -120,7 +120,7 @@ properties: "notAfterTime" fields inside an X.509 certificate. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s". immutable: true - # 10 years + # 10 years default_value: "315360000s" - name: 'revocationDetails' type: NestedObject diff --git a/mmv1/products/privateca/CertificateAuthority.yaml b/mmv1/products/privateca/CertificateAuthority.yaml index 513ec47fe234..e035e752cf5c 100644 --- a/mmv1/products/privateca/CertificateAuthority.yaml +++ b/mmv1/products/privateca/CertificateAuthority.yaml @@ -65,7 +65,7 @@ examples: pool_location: 'us-central1' deletion_protection: 'true' test_vars_overrides: - 'pool_name': 'acctest.BootstrapSharedCaPoolInLocation(t, "us-central1")' + 'pool_name': 'BootstrapSharedCaPoolInLocation(t, "us-central1")' 'pool_location': '"us-central1"' 'deletion_protection': 'false' ignore_read_extra: @@ -78,13 +78,13 @@ examples: pool_location: 'us-central1' deletion_protection: 'true' test_vars_overrides: - 'pool_name': 'acctest.BootstrapSharedCaPoolInLocation(t, "us-central1")' + 'pool_name': 'BootstrapSharedCaPoolInLocation(t, "us-central1")' 'pool_location': '"us-central1"' 'deletion_protection': 'false' ignore_read_extra: - 'deletion_protection' - # This example is meant to confirm that it's possible to make - # a CA without specifying the organization field + # This example is meant to confirm that it's possible to make + # a CA without specifying the organization field - name: 'privateca_certificate_authority_subordinate' primary_resource_id: 'default' vars: @@ -93,7 +93,7 @@ examples: pool_location: 'us-central1' deletion_protection: 'true' test_vars_overrides: - 'pool_name': 'acctest.BootstrapSharedCaPoolInLocation(t, "us-central1")' + 'pool_name': 'BootstrapSharedCaPoolInLocation(t, "us-central1")' 'pool_location': '"us-central1"' 'deletion_protection': 'false' ignore_read_extra: @@ -111,8 +111,8 @@ examples: pool_location: 'us-central1' deletion_protection: 'true' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocation(t, "ASYMMETRIC_SIGN", "us-central1").CryptoKey.Name' - 'pool_name': 'acctest.BootstrapSharedCaPoolInLocation(t, "us-central1")' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocation(t, "ASYMMETRIC_SIGN", "us-central1").CryptoKey.Name' + 'pool_name': 'BootstrapSharedCaPoolInLocation(t, "us-central1")' 'pool_location': '"us-central1"' 'deletion_protection': 'false' ignore_read_extra: @@ -131,8 +131,8 @@ examples: pool_location: 'us-central1' deletion_protection: 'true' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocation(t, "ASYMMETRIC_SIGN", "us-central1").CryptoKey.Name' - 'pool_name': 'acctest.BootstrapSharedCaPoolInLocation(t, "us-central1")' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocation(t, "ASYMMETRIC_SIGN", "us-central1").CryptoKey.Name' + 'pool_name': 'BootstrapSharedCaPoolInLocation(t, "us-central1")' 'pool_location': '"us-central1"' 'deletion_protection': 'false' ignore_read_extra: @@ -149,7 +149,7 @@ examples: pool_location: 'us-central1' deletion_protection: 'true' test_vars_overrides: - 'pool_name': 'acctest.BootstrapSharedCaPoolInLocation(t, "us-central1")' + 'pool_name': 'BootstrapSharedCaPoolInLocation(t, "us-central1")' 'pool_location': '"us-central1"' 'deletion_protection': 'false' ignore_read_extra: diff --git a/mmv1/products/privilegedaccessmanager/Settings.yaml b/mmv1/products/privilegedaccessmanager/Settings.yaml index 12ca82e7ec30..278203a45c43 100644 --- a/mmv1/products/privilegedaccessmanager/Settings.yaml +++ b/mmv1/products/privilegedaccessmanager/Settings.yaml @@ -34,7 +34,7 @@ update_verb: 'PATCH' create_verb: 'PATCH' update_mask: true custom_code: - pre_update: 'templates/terraform/pre_update/privileged_access_manager_settings.go.tmpl' # get etag + pre_update: 'templates/terraform/pre_update/privileged_access_manager_settings.go.tmpl' # get etag custom_create: 'templates/terraform/custom_create/privileged_access_manager_settings.go.tmpl' examples: - name: 'privileged_access_manager_settings_basic' diff --git a/mmv1/products/pubsub/Topic.yaml b/mmv1/products/pubsub/Topic.yaml index d3e4670e0389..968db3194912 100644 --- a/mmv1/products/pubsub/Topic.yaml +++ b/mmv1/products/pubsub/Topic.yaml @@ -301,7 +301,7 @@ properties: - 'avro_format' - 'pubsub_avro_format' properties: - # Meant to be an empty object with no properties. + # Meant to be an empty object with no properties. [] - name: 'pubsubAvroFormat' type: NestedObject @@ -317,7 +317,7 @@ properties: - 'avro_format' - 'pubsub_avro_format' properties: - # Meant to be an empty object with no properties. + # Meant to be an empty object with no properties. [] - name: 'minimumObjectCreateTime' type: String diff --git a/mmv1/products/redis/Cluster.yaml b/mmv1/products/redis/Cluster.yaml index dcbca567bbf1..538a8604085d 100644 --- a/mmv1/products/redis/Cluster.yaml +++ b/mmv1/products/redis/Cluster.yaml @@ -224,7 +224,7 @@ examples: deletion_protection_enabled: 'true' test_vars_overrides: 'deletion_protection_enabled': 'false' - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' oics_vars_overrides: 'deletion_protection_enabled': 'false' - name: 'redis_cluster_flexible_ca' diff --git a/mmv1/products/redis/Instance.yaml b/mmv1/products/redis/Instance.yaml index 3810b9033bcb..fadda5001575 100644 --- a/mmv1/products/redis/Instance.yaml +++ b/mmv1/products/redis/Instance.yaml @@ -69,7 +69,7 @@ examples: network_name: 'redis-test-network' prevent_destroy: 'true' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "redis-full")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "redis-full")' 'prevent_destroy': 'false' oics_vars_overrides: 'prevent_destroy': 'false' @@ -80,7 +80,7 @@ examples: network_name: 'redis-test-network' prevent_destroy: 'true' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "redis-full-persis")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "redis-full-persis")' 'prevent_destroy': 'false' oics_vars_overrides: 'prevent_destroy': 'false' @@ -105,7 +105,7 @@ examples: network_name: 'redis-test-network' prevent_destroy: 'true' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' 'prevent_destroy': 'false' oics_vars_overrides: 'prevent_destroy': 'false' @@ -117,7 +117,7 @@ examples: network_name: 'redis-test-network' prevent_destroy: 'true' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "redis-mrr")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "redis-mrr")' 'prevent_destroy': 'false' oics_vars_overrides: 'prevent_destroy': 'false' @@ -128,7 +128,7 @@ examples: network_name: 'redis-test-network' prevent_destroy: 'true' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "redis-cmek")' + 'network_name': 'compute.BootstrapSharedTestNetwork(t, "redis-cmek")' 'prevent_destroy': 'false' oics_vars_overrides: 'prevent_destroy': 'false' diff --git a/mmv1/products/resourcemanager/Lien.yaml b/mmv1/products/resourcemanager/Lien.yaml index 5336c0c33393..19d831fdc50e 100644 --- a/mmv1/products/resourcemanager/Lien.yaml +++ b/mmv1/products/resourcemanager/Lien.yaml @@ -46,7 +46,6 @@ nested_query: modify_by_patch: false custom_code: constants: 'templates/terraform/constants/resourcemanager_lien.go.tmpl' - test_constants: 'templates/terraform/constants/resourcemanager_lien.go.tpml' decoder: 'templates/terraform/decoders/avoid_meaningless_project_update.tmpl' pre_delete: 'templates/terraform/pre_delete/modify_delete_url.tmpl' post_import: 'templates/terraform/post_import/lien_import.tmpl' diff --git a/mmv1/products/secretmanager/Secret.yaml b/mmv1/products/secretmanager/Secret.yaml index e113134f5477..a4e6dbeb4a17 100644 --- a/mmv1/products/secretmanager/Secret.yaml +++ b/mmv1/products/secretmanager/Secret.yaml @@ -75,7 +75,7 @@ examples: secret_id: 'secret' kms_key_name: 'kms-key' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKey(t).CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKey(t).CryptoKey.Name' # for backward compatible secret_id: '"secret" + randomSuffix' parameters: diff --git a/mmv1/products/secretmanager/SecretVersion.yaml b/mmv1/products/secretmanager/SecretVersion.yaml index 74ae3d4cd6ac..164643375de9 100644 --- a/mmv1/products/secretmanager/SecretVersion.yaml +++ b/mmv1/products/secretmanager/SecretVersion.yaml @@ -54,6 +54,7 @@ custom_code: exclude_sweeper: true # exluding resource_identity due to custom_import exclude_identity_generation: true +deletion_policy_custom_docs: true examples: - name: 'secret_version_basic' primary_resource_id: 'secret-version-basic' @@ -103,12 +104,18 @@ virtual_fields: description: | The deletion policy for the secret version. Setting `ABANDON` allows the resource to be abandoned rather than deleted. Setting `DISABLE` allows the resource to be - disabled rather than deleted. Default is `DELETE`. Possible values are: + disabled rather than deleted. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + + Default is `DELETE`. Possible values are: * DELETE * DISABLE * ABANDON + * PREVENT type: String - default_value: "DELETE" + exclude: true - name: 'is_secret_data_base64' type: Boolean immutable: true diff --git a/mmv1/products/secretmanagerregional/RegionalSecret.yaml b/mmv1/products/secretmanagerregional/RegionalSecret.yaml index a8d6cafb8f95..67d25b7ce402 100644 --- a/mmv1/products/secretmanagerregional/RegionalSecret.yaml +++ b/mmv1/products/secretmanagerregional/RegionalSecret.yaml @@ -58,7 +58,7 @@ examples: secret_id: 'tf-reg-secret' kms_key_name: 'kms-key' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' - name: 'regional_secret_with_rotation' primary_resource_id: 'regional-secret-with-rotation' vars: diff --git a/mmv1/products/secretmanagerregional/RegionalSecretVersion.yaml b/mmv1/products/secretmanagerregional/RegionalSecretVersion.yaml index 86feca1dbcbf..30d5b1289d65 100644 --- a/mmv1/products/secretmanagerregional/RegionalSecretVersion.yaml +++ b/mmv1/products/secretmanagerregional/RegionalSecretVersion.yaml @@ -47,6 +47,7 @@ custom_code: pre_delete: 'templates/terraform/pre_delete/regional_secret_version_deletion_policy.go.tmpl' custom_import: 'templates/terraform/custom_import/regional_secret_version.go.tmpl' constants: 'templates/terraform/constants/regional_secret_version.go.tmpl' +deletion_policy_custom_docs: true # Sweeper skipped as this resource has customized deletion. # exluding resource_identity due to custom_import exclude_identity_generation: true @@ -90,14 +91,20 @@ examples: virtual_fields: - name: 'deletion_policy' description: | - The deletion policy for the regional secret version. Setting `ABANDON` allows the resource + The deletion policy for the secret version. Setting `ABANDON` allows the resource to be abandoned rather than deleted. Setting `DISABLE` allows the resource to be - disabled rather than deleted. Default is `DELETE`. Possible values are: + disabled rather than deleted. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + + Default is `DELETE`. Possible values are: * DELETE * DISABLE * ABANDON + * PREVENT type: String - default_value: "DELETE" + exclude: true - name: 'is_secret_data_base64' type: Boolean immutable: true diff --git a/mmv1/products/securesourcemanager/Instance.yaml b/mmv1/products/securesourcemanager/Instance.yaml index 58eca7139b5f..c69ab8b7a044 100644 --- a/mmv1/products/securesourcemanager/Instance.yaml +++ b/mmv1/products/securesourcemanager/Instance.yaml @@ -53,6 +53,7 @@ iam_policy: - '{{instance_id}}' custom_code: pre_delete: 'templates/terraform/pre_delete/securesourcemanager_deletion_policy.go.tmpl' +deletion_policy_default: "PREVENT" examples: - name: 'secure_source_manager_instance_basic' primary_resource_id: 'default' @@ -74,7 +75,7 @@ examples: deletion_policy: 'PREVENT' test_vars_overrides: 'deletion_policy': '"DELETE"' - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-secure-source-manager-key1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-secure-source-manager-key1").CryptoKey.Name' oics_vars_overrides: 'deletion_policy': '"DELETE"' ignore_read_extra: @@ -188,19 +189,6 @@ parameters: url_param_only: true required: true immutable: true -virtual_fields: - - name: 'deletion_policy' - type: String - description: | - The deletion policy for the instance. Setting `ABANDON` allows the resource - to be abandoned, rather than deleted. Setting `DELETE` deletes the resource - and all its contents. Setting `PREVENT` prevents the resource from accidental - deletion by erroring out during plan. - Default is `PREVENT`. Possible values are: - * DELETE - * PREVENT - * ABANDON - default_value: 'PREVENT' properties: - name: 'name' type: String diff --git a/mmv1/products/securesourcemanager/Repository.yaml b/mmv1/products/securesourcemanager/Repository.yaml index 929cfbd4ef36..5420836e2f24 100644 --- a/mmv1/products/securesourcemanager/Repository.yaml +++ b/mmv1/products/securesourcemanager/Repository.yaml @@ -45,8 +45,7 @@ iam_policy: import_format: - 'projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}' - '{{repository_id}}' -custom_code: - pre_delete: 'templates/terraform/pre_delete/securesourcemanager_deletion_policy.go.tmpl' +deletion_policy_default: "PREVENT" examples: - name: 'secure_source_manager_repository_basic' primary_resource_id: 'default' @@ -87,19 +86,6 @@ parameters: The ID for the Repository. url_param_only: true required: true -virtual_fields: - - name: 'deletion_policy' - type: String - description: | - The deletion policy for the repository. Setting `ABANDON` allows the resource - to be abandoned, rather than deleted. Setting `DELETE` deletes the resource - and all its contents. Setting `PREVENT` prevents the resource from accidental deletion - by erroring out during plan. - Default is `PREVENT`. Possible values are: - * DELETE - * PREVENT - * ABANDON - default_value: 'PREVENT' properties: - name: 'name' type: String diff --git a/mmv1/products/servicenetworking/VPCServiceControls.yaml b/mmv1/products/servicenetworking/VPCServiceControls.yaml index 23a05bf33a50..ff7a0f70b6a5 100644 --- a/mmv1/products/servicenetworking/VPCServiceControls.yaml +++ b/mmv1/products/servicenetworking/VPCServiceControls.yaml @@ -62,7 +62,7 @@ timeouts: delete_minutes: 20 autogen_async: true async: - # we just need the boilerplate async code, we'll call the methods manually + # we just need the boilerplate async code, we'll call the methods manually actions: [''] type: 'OpAsync' operation: @@ -75,7 +75,7 @@ custom_code: custom_create: 'templates/terraform/custom_create/service_networking_vpc_service_controls.go.tmpl' pre_read: 'templates/terraform/pre_read/service_networking_vpc_service_controls.go.tmpl' custom_update: 'templates/terraform/custom_create/service_networking_vpc_service_controls.go.tmpl' - # excluding tgc because of helpers in custom_code.constants +# excluding tgc because of helpers in custom_code.constants exclude_tgc: true examples: - name: 'service_networking_vpc_service_controls_basic' diff --git a/mmv1/products/spanner/Instance.yaml b/mmv1/products/spanner/Instance.yaml index 95053fa49e9f..28d46b540d76 100644 --- a/mmv1/products/spanner/Instance.yaml +++ b/mmv1/products/spanner/Instance.yaml @@ -56,15 +56,15 @@ custom_code: examples: - name: 'spanner_instance_basic' primary_resource_id: 'example' - # Randomness + # Randomness skip_vcr: true - name: 'spanner_instance_processing_units' primary_resource_id: 'example' - # Randomness + # Randomness skip_vcr: true - name: 'spanner_instance_multi_regional' primary_resource_id: 'example' - # Randomness + # Randomness skip_vcr: true virtual_fields: - name: 'force_destroy' @@ -88,9 +88,9 @@ properties: in length. If not provided, a random string starting with `tf-` will be selected. immutable: true - # This resource supports a sort of odd autogenerate-if-not-set - # system, which is done in the encoder. Consequently we have - # to interpret "not set" as "use the name in state". + # This resource supports a sort of odd autogenerate-if-not-set + # system, which is done in the encoder. Consequently we have + # to interpret "not set" as "use the name in state". default_from_api: true custom_flatten: 'templates/terraform/custom_flatten/name_from_self_link.tmpl' validation: diff --git a/mmv1/products/sql/Database.yaml b/mmv1/products/sql/Database.yaml index 7a74376617a1..4f5029b530a4 100644 --- a/mmv1/products/sql/Database.yaml +++ b/mmv1/products/sql/Database.yaml @@ -39,7 +39,6 @@ async: resource_inside_response: false collection_url_key: 'items' custom_code: - pre_delete: 'templates/terraform/pre_delete/sql_database_deletion_policy.tmpl' pre_read: 'templates/terraform/pre_read/sql_database_activation_policy.tmpl' # Sweeper skipped as this resource has customized deletion. exclude_sweeper: true @@ -67,16 +66,6 @@ examples: 'deletion_protection': 'false' ignore_read_extra: - 'deletion_policy' -virtual_fields: - # TODO: make this an enum in a future major version. If using this field as a reference, look at PerInstanceConfig's minimal_action field for enum configuration. - - name: 'deletion_policy' - description: | - The deletion policy for the database. Setting ABANDON allows the resource - to be abandoned rather than deleted. This is useful for Postgres, where databases cannot be - deleted from the API if there are users other than cloudsqlsuperuser with access. Possible - values are: "ABANDON", "DELETE". Defaults to "DELETE". - type: String - default_value: "DELETE" parameters: - name: 'instance' type: String diff --git a/mmv1/products/storage/HmacKey.yaml b/mmv1/products/storage/HmacKey.yaml index 1df033b441f1..39f0ac6c6c69 100644 --- a/mmv1/products/storage/HmacKey.yaml +++ b/mmv1/products/storage/HmacKey.yaml @@ -74,7 +74,7 @@ properties: fingerprint_name: 'etag' default_value: "ACTIVE" enum_values: - # - :DELETED (not directly settable) + # - :DELETED (not directly settable) - 'ACTIVE' - 'INACTIVE' - name: 'secret' diff --git a/mmv1/products/storage/ManagedFolder.yaml b/mmv1/products/storage/ManagedFolder.yaml index f858c646abb1..7df4a7cec9a8 100644 --- a/mmv1/products/storage/ManagedFolder.yaml +++ b/mmv1/products/storage/ManagedFolder.yaml @@ -46,7 +46,7 @@ timeouts: delete_minutes: 20 custom_code: custom_update: 'templates/terraform/custom_update/storage_managed_folder.go.tmpl' - # Skipping sweeper since this is a child resource. +# Skipping sweeper since this is a child resource. exclude_sweeper: true examples: - name: 'storage_managed_folder_basic' diff --git a/mmv1/products/storagebatchoperations/Job.yaml b/mmv1/products/storagebatchoperations/Job.yaml index da00df9839e9..e5f8919fef49 100644 --- a/mmv1/products/storagebatchoperations/Job.yaml +++ b/mmv1/products/storagebatchoperations/Job.yaml @@ -48,6 +48,13 @@ examples: vars: bucket_name: tf-sample-bucket job_id: tf-job + - name: storage_batch_operations_description + primary_resource_id: tf-job + ignore_read_extra: + - delete_protection + vars: + bucket_name: tf-sample-bucket + job_id: tf-job virtual_fields: - name: delete_protection type: Boolean @@ -287,3 +294,6 @@ properties: immutable: true validation: function: validation.StringInSlice([]string{"SET", "UNSET"}, false) + - name: description + type: String + description: A description provided by the user for the job. Its max length is 1024 bytes when Unicode-encoded. diff --git a/mmv1/products/vertexai/FeatureOnlineStore.yaml b/mmv1/products/vertexai/FeatureOnlineStore.yaml index 65053b2fca53..3c16b437ef8a 100644 --- a/mmv1/products/vertexai/FeatureOnlineStore.yaml +++ b/mmv1/products/vertexai/FeatureOnlineStore.yaml @@ -156,7 +156,7 @@ properties: - 'bigtable' - 'optimized' properties: - # Meant to be an empty object with no properties - see here : https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.featureOnlineStores#Optimized + # Meant to be an empty object with no properties - see here : https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.featureOnlineStores#Optimized [] - name: 'dedicatedServingEndpoint' type: NestedObject diff --git a/mmv1/products/vertexai/Featurestore.yaml b/mmv1/products/vertexai/Featurestore.yaml index 48338c27af0c..52bd0eab6a08 100644 --- a/mmv1/products/vertexai/Featurestore.yaml +++ b/mmv1/products/vertexai/Featurestore.yaml @@ -58,7 +58,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible name: '"terraform" + randomSuffix' ignore_read_extra: @@ -74,7 +74,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible name: '"terraform2" + randomSuffix' ignore_read_extra: @@ -89,7 +89,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible name: '"terraform3" + randomSuffix' ignore_read_extra: diff --git a/mmv1/products/vertexai/FeaturestoreEntitytype.yaml b/mmv1/products/vertexai/FeaturestoreEntitytype.yaml index 9c6cdf44aec8..546425ba2265 100644 --- a/mmv1/products/vertexai/FeaturestoreEntitytype.yaml +++ b/mmv1/products/vertexai/FeaturestoreEntitytype.yaml @@ -68,7 +68,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible name: '"terraform" + randomSuffix' - name: 'vertex_ai_featurestore_entitytype_with_beta_fields' @@ -82,7 +82,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible name: '"terraform2" + randomSuffix' parameters: diff --git a/mmv1/products/vertexai/Index.yaml b/mmv1/products/vertexai/Index.yaml index 26268f40f38b..87bf78295be2 100644 --- a/mmv1/products/vertexai/Index.yaml +++ b/mmv1/products/vertexai/Index.yaml @@ -37,6 +37,8 @@ async: resource_inside_response: true custom_code: custom_update: 'templates/terraform/custom_update/vertex_ai_index.go.tmpl' +sweeper: + identifier_field: 'displayName' examples: - name: 'vertex_ai_index' min_version: beta @@ -48,7 +50,7 @@ examples: test_env_vars: project: 'PROJECT_NAME' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' ignore_read_extra: - 'metadata.0.contents_delta_uri' - 'metadata.0.is_complete_overwrite' @@ -61,7 +63,7 @@ examples: test_env_vars: project: 'PROJECT_NAME' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' ignore_read_extra: - 'metadata.0.contents_delta_uri' - 'metadata.0.is_complete_overwrite' diff --git a/mmv1/products/vertexai/IndexEndpoint.yaml b/mmv1/products/vertexai/IndexEndpoint.yaml index 12dd7cbb4e54..c50b7dbfd3e1 100644 --- a/mmv1/products/vertexai/IndexEndpoint.yaml +++ b/mmv1/products/vertexai/IndexEndpoint.yaml @@ -35,7 +35,8 @@ async: base_url: '{{op_id}}' result: resource_inside_response: true -custom_code: +sweeper: + identifier_field: 'displayName' examples: - name: 'vertex_ai_index_endpoint' primary_resource_id: 'index_endpoint' @@ -48,22 +49,27 @@ examples: vars: network_name: 'network-name' kms_key_name: 'kms-name' + index_endpoint_display_name: 'sample-endpoint' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' exclude_docs: true min_version: beta - name: 'vertex_ai_index_endpoint_with_psc' primary_resource_id: 'index_endpoint' + vars: + index_endpoint_display_name: 'sample-endpoint' - name: 'vertex_ai_index_endpoint_with_false_psc' primary_resource_id: 'index_endpoint' # It's not distinguishable if the psc is false or not set, so we need to skip the test. exclude_import_test: true exclude_docs: true + vars: + index_endpoint_display_name: 'sample-endpoint' - name: 'vertex_ai_index_endpoint_with_public_endpoint' primary_resource_id: 'index_endpoint' - test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedTestNetwork(t, "vertex-ai-index-endpoint")' + vars: + index_endpoint_display_name: 'sample-endpoint' parameters: - name: 'region' type: String diff --git a/mmv1/products/vertexai/IndexEndpointDeployedIndex.yaml b/mmv1/products/vertexai/IndexEndpointDeployedIndex.yaml index 7abefd7714d2..4d557a0b5744 100644 --- a/mmv1/products/vertexai/IndexEndpointDeployedIndex.yaml +++ b/mmv1/products/vertexai/IndexEndpointDeployedIndex.yaml @@ -67,8 +67,8 @@ examples: service_account_id: 'vertex-sa' address_name: 'vertex-ai-range' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' - 'address_name': 'acctest.BootstrapSharedTestGlobalAddress(t, "vpc-network-1", acctest.AddressWithPrefixLength(8))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' + 'address_name': 'compute.BootstrapSharedTestGlobalAddress(t, "vpc-network-1", compute.AddressWithPrefixLength(8))' - name: 'vertex_ai_index_endpoint_deployed_index_basic_two' primary_resource_id: 'basic_deployed_index' vars: @@ -81,8 +81,8 @@ examples: service_account_id: 'vertex-sa' address_name: 'vertex-ai-range' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' - 'address_name': 'acctest.BootstrapSharedTestGlobalAddress(t, "vpc-network-1", acctest.AddressWithPrefixLength(8))' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1")' + 'address_name': 'compute.BootstrapSharedTestGlobalAddress(t, "vpc-network-1", compute.AddressWithPrefixLength(8))' - name: 'vertex_ai_index_endpoint_deployed_index_dedicated_resources' primary_resource_id: 'dedicated_resources' vars: diff --git a/mmv1/products/vertexai/ReasoningEngine.yaml b/mmv1/products/vertexai/ReasoningEngine.yaml index 01880fa87283..58f5e538fce2 100644 --- a/mmv1/products/vertexai/ReasoningEngine.yaml +++ b/mmv1/products/vertexai/ReasoningEngine.yaml @@ -25,6 +25,7 @@ self_link: 'projects/{{project}}/locations/{{region}}/reasoningEngines/{{name}}' create_url: 'projects/{{project}}/locations/{{region}}/reasoningEngines' update_verb: 'PATCH' update_mask: true +deletion_policy_custom_docs: true timeouts: insert_minutes: 20 update_minutes: 20 @@ -114,7 +115,7 @@ examples: - member: "serviceAccount:service-{project_number}@gcp-sa-aiplatform.iam.gserviceaccount.com" role: "roles/cloudkms.cryptoKeyEncrypterDecrypter" test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-re-key1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-re-key1").CryptoKey.Name' # for backward compatible secret_name: '"secret" + randomSuffix' # for backward compatible @@ -142,10 +143,16 @@ custom_code: virtual_fields: - name: 'deletion_policy' description: | - Optional. The deletion policy for the reasoning engine. Setting this to FORCE allows the reasoning engine to be deleted regardless of child undeleted resources. - type: Enum - enum_values: - - 'FORCE' + Optional. The deletion policy for the reasoning engine. + Setting this to FORCE allows the reasoning engine to be deleted regardless of child undeleted resources. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is permitted. + type: String + exclude: true iam_policy: method_name_separator: ':' fetch_iam_policy_verb: 'POST' diff --git a/mmv1/products/vertexai/Tensorboard.yaml b/mmv1/products/vertexai/Tensorboard.yaml index 7291a4c8128a..45d73f401151 100644 --- a/mmv1/products/vertexai/Tensorboard.yaml +++ b/mmv1/products/vertexai/Tensorboard.yaml @@ -53,7 +53,7 @@ examples: display_name: 'terraform' kms_key_name: 'kms-name' test_vars_overrides: - 'kms_key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'kms_key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' # for backward compatible display_name: '"terraform" + randomSuffix' ignore_read_extra: diff --git a/mmv1/products/vmwareengine/ExternalAccessRule.yaml b/mmv1/products/vmwareengine/ExternalAccessRule.yaml index 0e7ca5990d8e..9d7520d1a271 100644 --- a/mmv1/products/vmwareengine/ExternalAccessRule.yaml +++ b/mmv1/products/vmwareengine/ExternalAccessRule.yaml @@ -52,7 +52,7 @@ examples: network_policy_id: 'sample-np' test_env_vars: region: 'REGION' - # update tests will take care of create and update. The test id dependent on PC creation, which is expensive and requires node reservation. + # update tests will take care of create and update. The test id dependent on PC creation, which is expensive and requires node reservation. exclude_test: true - name: 'vmware_engine_external_access_rule_full' primary_resource_id: 'vmw-engine-external-access-rule' @@ -65,7 +65,7 @@ examples: external_address_id: 'sample-ea' test_env_vars: region: 'REGION' - # update tests will take care of create and update. The test id dependent on PC creation, which is expensive and requires node reservation. + # update tests will take care of create and update. The test id dependent on PC creation, which is expensive and requires node reservation. exclude_test: true parameters: - name: 'parent' diff --git a/mmv1/products/vmwareengine/ExternalAddress.yaml b/mmv1/products/vmwareengine/ExternalAddress.yaml index 5e51a5143d24..f9031c0657f5 100644 --- a/mmv1/products/vmwareengine/ExternalAddress.yaml +++ b/mmv1/products/vmwareengine/ExternalAddress.yaml @@ -64,7 +64,7 @@ examples: network_policy_id: 'sample-np' test_env_vars: region: 'REGION' - # update tests will take care of all CRUD tests. Parent PC creation is expensive and node reservation is required. + # update tests will take care of all CRUD tests. Parent PC creation is expensive and node reservation is required. exclude_test: true parameters: - name: 'parent' diff --git a/mmv1/products/vmwareengine/Network.yaml b/mmv1/products/vmwareengine/Network.yaml index be81c65cbde2..25d3771c1a11 100644 --- a/mmv1/products/vmwareengine/Network.yaml +++ b/mmv1/products/vmwareengine/Network.yaml @@ -64,7 +64,7 @@ examples: org_id: 'ORG_ID' billing_account: 'BILLING_ACCT' external_providers: ["random", "time"] - # update tests will take care of create and update. Legacy network needs to be created on an isolated project. + # update tests will take care of create and update. Legacy network needs to be created on an isolated project. exclude_test: true parameters: - name: 'location' diff --git a/mmv1/products/vmwareengine/Subnet.yaml b/mmv1/products/vmwareengine/Subnet.yaml index 5603709a4436..8a17aa16dfe3 100644 --- a/mmv1/products/vmwareengine/Subnet.yaml +++ b/mmv1/products/vmwareengine/Subnet.yaml @@ -55,7 +55,7 @@ examples: subnet_id: 'service-1' test_env_vars: region: 'REGION' - # update tests will take care of read and update. Parent PC creation is expensive and node reservation is required. + # update tests will take care of read and update. Parent PC creation is expensive and node reservation is required. exclude_test: true parameters: - name: 'parent' diff --git a/mmv1/products/vpcaccess/Connector.yaml b/mmv1/products/vpcaccess/Connector.yaml index 45a737196666..4c937b28fcf9 100644 --- a/mmv1/products/vpcaccess/Connector.yaml +++ b/mmv1/products/vpcaccess/Connector.yaml @@ -56,14 +56,14 @@ examples: name: 'vpc-con' network_name: 'default' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-access-connector")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-access-connector")' - name: 'vpc_access_connector_shared_vpc' primary_resource_id: 'connector' vars: name: 'vpc-con' network_name: 'default' test_vars_overrides: - 'network_name': 'acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-access-connector")' + 'network_name': 'servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-access-connector")' tgc_tests: - name: TestAccVPCAccessConnector_vpcAccessConnectorThroughput_usingThroughputOrInstancesLimits skip: 'For instances vs throughput, prefer instances during cai2hcl conversion as throughput is discouraged.' diff --git a/mmv1/products/workbench/Instance.yaml b/mmv1/products/workbench/Instance.yaml index e9cf61c0816d..bc59df795c44 100644 --- a/mmv1/products/workbench/Instance.yaml +++ b/mmv1/products/workbench/Instance.yaml @@ -105,7 +105,7 @@ examples: project_id: 'PROJECT_NAME' service_account: 'SERVICE_ACCT' test_vars_overrides: - 'key_name': 'acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' + 'key_name': 'kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name' ignore_read_extra: - 'gce_setup.0.vm_image' - 'gce_setup.0.boot_disk.0.disk_type' diff --git a/mmv1/products/workstations/WorkstationCluster.yaml b/mmv1/products/workstations/WorkstationCluster.yaml index e7eb8669697a..3e027a403c17 100644 --- a/mmv1/products/workstations/WorkstationCluster.yaml +++ b/mmv1/products/workstations/WorkstationCluster.yaml @@ -65,6 +65,15 @@ examples: test_vars_overrides: 'key_short_name': '"tf-test-key-" + acctest.RandString(t, 10)' 'value_short_name': '"tf-test-value-" + acctest.RandString(t, 10)' +samples: + - name: "workstation_cluster_urls" + primary_resource_id: "default" + steps: + - name: "workstation_cluster_custom_urls" + vars: + cluster_id: "custom-urls-cluster" + resource_id_vars: + cluster_network_name: "workstations-network" parameters: - name: 'workstationClusterId' type: String @@ -120,6 +129,17 @@ properties: type: String description: | Human-readable name for this resource. + - name: 'workstationAuthorizationUrl' + type: String + default_from_api: true + description: | + Specifies the redirect URL for unauthorized requests received by workstation VMs in this cluster. + Redirects to this endpoint will send a base64 encoded `state` query param containing the target workstation name and original request hostname. The endpoint is responsible for retrieving a token using `GenerateAccessToken` and redirecting back to the original hostname with the token. + - name: 'workstationLaunchUrl' + type: String + description: | + Specifies the launch URL for workstations in this cluster. Requests sent to unstarted workstations will be redirected to this URL. + Requests redirected to the launch endpoint will be sent with a `workstation` query parameter containing the full workstation resource. The launch endpoint is responsible for starting the workstation, polling it until it reaches `STATE_RUNNING`, and then issuing a redirect to the workstation's host URL. - name: 'degraded' type: Boolean description: | diff --git a/mmv1/provider/BUILD.bazel b/mmv1/provider/BUILD.bazel index 8a964f3e28e1..3cf9a830b253 100644 --- a/mmv1/provider/BUILD.bazel +++ b/mmv1/provider/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_go//go:def.bzl", "go_library") +load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "provider", @@ -25,3 +25,10 @@ go_library( "@org_golang_x_exp//slices", ], ) + +go_test( + name = "provider_test", + srcs = ["terraform_tgc_next_test.go"], + embed = [":provider"], + deps = ["//mmv1/api"], +) diff --git a/mmv1/provider/template_data.go b/mmv1/provider/template_data.go index 55183ca1d1fe..61d7476d7e91 100644 --- a/mmv1/provider/template_data.go +++ b/mmv1/provider/template_data.go @@ -122,6 +122,24 @@ func (td *TemplateData) GenerateDocumentationFile(filePath string, resource api. td.GenerateFile(filePath, templatePath, resource, false, templates...) } +func (td *TemplateData) GenerateListResourceDocumentationFile(filePath string, resource api.Resource) { + templatePath := "templates/terraform/list_resource.html.markdown.tmpl" + templates := []string{ + templatePath, + } + td.GenerateFile(filePath, templatePath, resource, false, templates...) +} + +func (td *TemplateData) GenerateDataSourceDocumentationFile(filePath string, resource api.Resource) { + templatePath := "templates/terraform/datasource.html.markdown.tmpl" + templates := []string{ + templatePath, + "templates/terraform/property_documentation.html.markdown.tmpl", + "templates/terraform/nested_property_documentation.html.markdown.tmpl", + } + td.GenerateFile(filePath, templatePath, resource, false, templates...) +} + func (td *TemplateData) GenerateTestFileLegacy(filePath string, resource api.Resource) { templatePath := "templates/terraform/examples/base_configs/test_file.go.tmpl" templates := []string{ @@ -282,6 +300,16 @@ func (td *TemplateData) GenerateIamPolicyTestFile(filePath string, resource api. td.GenerateFile(filePath, templatePath, resource, true, templates...) } +// GenerateQueryTestFile emits a Terraform query-mode acceptance test for list resources (generate_list_resource). +func (td *TemplateData) GenerateQueryTestFile(filePath string, resource api.Resource) { + templatePath := "templates/terraform/samples/base_configs/query_test_file.go.tmpl" + templates := []string{ + templatePath, + "templates/terraform/env_var_context.go.tmpl", + } + td.GenerateFile(filePath, templatePath, resource, true, templates...) +} + func (td *TemplateData) GenerateSweeperFile(filePath string, resource api.Resource) { templatePath := "templates/terraform/sweeper_file.go.tmpl" templates := []string{ diff --git a/mmv1/provider/terraform.go b/mmv1/provider/terraform.go index 7731668970f1..f30b1386db9e 100644 --- a/mmv1/provider/terraform.go +++ b/mmv1/provider/terraform.go @@ -104,12 +104,12 @@ func (t *Terraform) GenerateObject(object api.Resource, outputFolder, productPat if !object.IsExcluded() { log.Printf("Generating %s resource", object.Name) t.GenerateResource(object, *templateData, outputFolder, generateCode, generateDocs) + t.GenerateSingularDataSource(object, *templateData, outputFolder, generateCode, generateDocs) if generateCode { // log.Printf("Generating %s tests", object.Name) t.GenerateResourceTests(object, *templateData, outputFolder) t.GenerateResourceSweeper(object, *templateData, outputFolder) - t.GenerateSingularDataSource(object, *templateData, outputFolder) t.GenerateSingularDataSourceTests(object, *templateData, outputFolder) // log.Printf("Generating %s metadata", object.Name) t.GenerateResourceMetadata(object, *templateData, outputFolder) @@ -155,12 +155,38 @@ func (t *Terraform) GenerateResource(object api.Resource, templateData TemplateD targetFilePath := path.Join(targetFolder, fmt.Sprintf("resource_%s.go", t.ResourceGoFilename(object))) templateData.GenerateResourceFile(targetFilePath, object) } + + t.GenerateListResource(object, templateData, targetFolder) } if generateDocs { targetFolder := t.makeFolder(outputFolder, "website", "docs", "r") targetFilePath := path.Join(targetFolder, fmt.Sprintf("%s.html.markdown", t.FullResourceName(object))) templateData.GenerateDocumentationFile(targetFilePath, object) + + if object.GenerateListResource { + listDocFolder := t.makeFolder(outputFolder, "website", "docs", "list-resources") + listDocFilePath := path.Join(listDocFolder, fmt.Sprintf("%s.html.markdown", object.TerraformName())) + templateData.GenerateListResourceDocumentationFile(listDocFilePath, object) + } + } +} + +func (t *Terraform) GenerateListResource(object api.Resource, templateData TemplateData, targetFolder string) { + if object.GenerateListResource { + if object.ExcludeIdentityGeneration { + log.Fatalf("generate_list_resource requires identity support; remove exclude_identity_generation from resource %q or disable generate_list_resource", object.Name) + } + if object.ExcludeRead { + log.Fatalf("generate_list_resource requires read support; remove exclude_read from resource %q or disable generate_list_resource", object.Name) + } + targetFilePath := path.Join(targetFolder, fmt.Sprintf("list_%s.go", t.ResourceGoFilename(object))) + templateData.GenerateFile(targetFilePath, "templates/terraform/list_resource.go.tmpl", object, true, + "templates/terraform/list_resource.go.tmpl", + "templates/terraform/list_resource_method.go.tmpl", + ) + + t.GenerateListResourceQueryTest(object, templateData, targetFolder) } } @@ -249,6 +275,17 @@ func (t *Terraform) GenerateResourceTests(object api.Resource, templateData Temp templateData.GenerateTestFile(targetFilePath, object) } +func (t *Terraform) GenerateListResourceQueryTest(object api.Resource, templateData TemplateData, targetFolder string) { + if object.Samples != nil && object.Examples != nil { + log.Fatalf("Both Samples and Examples block exist in %v", object.Name) + } + if object.Samples == nil || !t.hasEligibleSample(object) { + return + } + targetFilePath := path.Join(targetFolder, fmt.Sprintf("list_%s_generated_test.go", t.ResourceGoFilename(object))) + templateData.GenerateQueryTestFile(targetFilePath, object) +} + func (t *Terraform) GenerateResourceSweeper(object api.Resource, templateData TemplateData, outputFolder string) { if !object.ShouldGenerateSweepers() { return @@ -273,14 +310,22 @@ func (t *Terraform) GenerateResourceSweeperFile(object api.Resource, targetFileP templateData.GenerateSweeperFile(targetFilePath, object) } -func (t *Terraform) GenerateSingularDataSource(object api.Resource, templateData TemplateData, outputFolder string) { +func (t *Terraform) GenerateSingularDataSource(object api.Resource, templateData TemplateData, outputFolder string, generateCode, generateDocs bool) { if !object.ShouldGenerateSingularDataSource() { return } - targetFolder := t.makeFolder(outputFolder, t.FolderName(), "services", t.Product.ApiName) - targetFilePath := path.Join(targetFolder, fmt.Sprintf("data_source_%s.go", t.ResourceGoFilename(object))) - templateData.GenerateDataSourceFile(targetFilePath, object) + if generateCode { + targetFolder := t.makeFolder(outputFolder, t.FolderName(), "services", t.Product.ApiName) + targetFilePath := path.Join(targetFolder, fmt.Sprintf("data_source_%s.go", t.ResourceGoFilename(object))) + templateData.GenerateDataSourceFile(targetFilePath, object) + } + + if generateDocs { + targetFolder := t.makeFolder(outputFolder, "website", "docs", "d") + targetFilePath := path.Join(targetFolder, fmt.Sprintf("%s.html.markdown", t.FullResourceName(object))) + templateData.GenerateDataSourceDocumentationFile(targetFilePath, object) + } } func (t *Terraform) GenerateSingularDataSourceTestsLegacy(object api.Resource, templateData TemplateData, outputFolder string) { @@ -505,7 +550,28 @@ func (t Terraform) getCommonCopyFiles(versionName string, generateCode, generate // save the folder name to foldersCopiedToGoogleDir var foldersCopiedToGoogleDir []string if generateCode { - foldersCopiedToGoogleDir = []string{"third_party/terraform/services", "third_party/terraform/acctest", "third_party/terraform/sweeper", "third_party/terraform/provider", "third_party/terraform/registry", "third_party/terraform/tpgdclresource", "third_party/terraform/tpgiamresource", "third_party/terraform/tpgresource", "third_party/terraform/transport", "third_party/terraform/fwmodels", "third_party/terraform/fwprovider", "third_party/terraform/fwtransport", "third_party/terraform/fwresource", "third_party/terraform/fwutils", "third_party/terraform/fwvalidators", "third_party/terraform/verify", "third_party/terraform/envvar", "third_party/terraform/functions", "third_party/terraform/test-fixtures"} + foldersCopiedToGoogleDir = []string{ + "third_party/terraform/acctest", + "third_party/terraform/allservices", + "third_party/terraform/envvar", + "third_party/terraform/functions", + "third_party/terraform/fwmodels", + "third_party/terraform/fwprovider", + "third_party/terraform/fwresource", + "third_party/terraform/fwtransport", + "third_party/terraform/fwutils", + "third_party/terraform/fwvalidators", + "third_party/terraform/provider", + "third_party/terraform/registry", + "third_party/terraform/services", + "third_party/terraform/sweeper", + "third_party/terraform/test-fixtures", + "third_party/terraform/tpgdclresource", + "third_party/terraform/tpgiamresource", + "third_party/terraform/tpgresource", + "third_party/terraform/transport", + "third_party/terraform/verify", + } } googleDir := "google" if versionName != "ga" { @@ -622,7 +688,25 @@ func (t Terraform) getCommonCompileFiles(versionName string) map[string]string { // Case 2: When compile all of files except .tmpl in a folder to the google directory of downstream repository, // save the folder name to foldersCopiedToGoogleDir - foldersCompiledToGoogleDir := []string{"third_party/terraform/services", "third_party/terraform/acctest", "third_party/terraform/sweeper", "third_party/terraform/provider", "third_party/terraform/tpgdclresource", "third_party/terraform/tpgiamresource", "third_party/terraform/tpgresource", "third_party/terraform/transport", "third_party/terraform/fwmodels", "third_party/terraform/fwprovider", "third_party/terraform/fwtransport", "third_party/terraform/fwresource", "third_party/terraform/verify", "third_party/terraform/envvar", "third_party/terraform/functions", "third_party/terraform/test-fixtures"} + foldersCompiledToGoogleDir := []string{ + "third_party/terraform/acctest", + "third_party/terraform/allservices", + "third_party/terraform/envvar", + "third_party/terraform/functions", + "third_party/terraform/fwmodels", + "third_party/terraform/fwprovider", + "third_party/terraform/fwresource", + "third_party/terraform/fwtransport", + "third_party/terraform/provider", + "third_party/terraform/services", + "third_party/terraform/sweeper", + "third_party/terraform/test-fixtures", + "third_party/terraform/tpgdclresource", + "third_party/terraform/tpgiamresource", + "third_party/terraform/tpgresource", + "third_party/terraform/transport", + "third_party/terraform/verify", + } googleDir := "google" if versionName != "ga" { googleDir = fmt.Sprintf("google-%s", versionName) diff --git a/mmv1/provider/terraform/common~compile.yaml b/mmv1/provider/terraform/common~compile.yaml deleted file mode 100644 index 266818c89957..000000000000 --- a/mmv1/provider/terraform/common~compile.yaml +++ /dev/null @@ -1,122 +0,0 @@ -# Copyright 2018 Google Inc. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# These files contains code that needs to be compiled before being delivered to -# the final module tree structure: -<% - dir = @target_version_name == 'ga' ? 'google' : "google-#{@target_version_name}" --%> - -# Compile all of the terraform resources that are still hand written into the specific service folder -<% Dir["third_party/terraform/services/**"].each do |product_path| - product_name = product_path.split('/')[-1] - Dir[product_path + "/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/services/<%= product_name -%>/<%= fname.delete_suffix(".erb") -%>': '<%= product_path -%>/<%= fname -%>' -<% end -%> -<% end -%> - -<% - Dir["third_party/terraform/acctest/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/acctest/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/acctest/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/provider/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/provider/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/provider/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/tpgiamresource/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/tpgiamresource/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/tpgiamresource/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/tpgresource/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/tpgresource/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/tpgresource/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwmodels/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwmodels/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/fwmodels/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwprovider/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwprovider/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/fwprovider/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwtransport/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwtransport/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/fwtransport/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/sweeper/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/sweeper/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/sweeper/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/transport/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/transport/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/transport/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/verify/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/verify/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/verify/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/framework_models/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/framework_models/<%= fname -%>' -<% end -%> -<% - Dir["third_party/terraform/functions/*.go.erb"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/functions/<%= fname.delete_suffix(".erb") -%>': 'third_party/terraform/functions/<%= fname -%>' -<% end -%> -<% - Dir["third_party/terraform/scripts/**/*.erb"].each do |file_path| - fname = file_path.delete_prefix("third_party/terraform/") --%> -'<%= fname.delete_suffix(".erb") -%>': '<%= file_path -%>' -<% end -%> -'main.go': 'third_party/terraform/main.go.erb' -'go.mod': 'third_party/terraform/go.mod.erb' -'.goreleaser.yml': 'third_party/terraform/.goreleaser.yml.erb' -'terraform-registry-manifest.json': 'third_party/terraform/terraform-registry-manifest.json.erb' -'.release/release-metadata.hcl': 'third_party/terraform/release-metadata.hcl.erb' -'.copywrite.hcl': 'third_party/terraform/.copywrite.hcl.erb' \ No newline at end of file diff --git a/mmv1/provider/terraform/common~copy.yaml b/mmv1/provider/terraform/common~copy.yaml deleted file mode 100644 index 1784bffb4170..000000000000 --- a/mmv1/provider/terraform/common~copy.yaml +++ /dev/null @@ -1,208 +0,0 @@ -# Copyright 2018 Google Inc. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# These files contains code that needs to be compiled before being delivered to -# the final module tree structure: -<% - dir = version_name == 'ga' ? 'google' : "google-#{version_name}" --%> - -<% if generate_code -%> - -# Copy all of the terraform resources that are still hand written into the specific service folder -<% Dir["third_party/terraform/services/**"].each do |product_path| - product_name = product_path.split('/')[-1] - Dir[product_path + "/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/services/<%= product_name -%>/<%= fname -%>': '<%= product_path -%>/<%= fname -%>' -<% end -%> -<% if Dir.exist?("#{product_path}/test-fixtures") -%> -'<%= dir -%>/services/<%= product_name -%>/test-fixtures': '<%= product_path -%>/test-fixtures' -<% end -%> -<% end -%> - -<% - Dir["third_party/terraform/acctest/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/acctest/<%= fname -%>': 'third_party/terraform/acctest/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/sweeper/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/sweeper/<%= fname -%>': 'third_party/terraform/sweeper/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/provider/*.go"].each do |file_path| - fname = file_path.delete_prefix("third_party/terraform/provider") --%> -'<%= dir -%>/provider/<%= fname -%>': 'third_party/terraform/provider/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/provider/universe/*.go"].each do |file_path| - fname = file_path.delete_prefix("third_party/terraform/provider") --%> -'<%= dir -%>/provider/<%= fname -%>': 'third_party/terraform/provider/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/tpgdclresource/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/tpgdclresource/<%= fname -%>': 'third_party/terraform/tpgdclresource/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/tpgiamresource/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/tpgiamresource/<%= fname -%>': 'third_party/terraform/tpgiamresource/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/tpgresource/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/tpgresource/<%= fname -%>': 'third_party/terraform/tpgresource/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/transport/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/transport/<%= fname -%>': 'third_party/terraform/transport/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwmodels/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwmodels/<%= fname -%>': 'third_party/terraform/fwmodels/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwprovider/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwprovider/<%= fname -%>': 'third_party/terraform/fwprovider/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwutils/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwutils/<%= fname -%>': 'third_party/terraform/fwutils/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwvalidators/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwvalidators/<%= fname -%>': 'third_party/terraform/fwvalidators/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwtransport/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwtransport/<%= fname -%>': 'third_party/terraform/fwtransport/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/fwresource/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/fwresource/<%= fname -%>': 'third_party/terraform/fwresource/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/verify/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/verify/<%= fname -%>': 'third_party/terraform/verify/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/envvar/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/envvar/<%= fname -%>': 'third_party/terraform/envvar/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/functions/*.go"].each do |file_path| - fname = file_path.split('/')[-1] --%> -'<%= dir -%>/functions/<%= fname -%>': 'third_party/terraform/functions/<%= fname -%>' -<% end -%> - -<% - Dir["third_party/terraform/scripts/*.*"].each do |file_path| - next if file_path.end_with?('.erb') - fname = file_path.delete_prefix('third_party/terraform/') --%> -'<%= fname -%>': '<%= file_path -%>' -<% end -%> - -<% - Dir["third_party/terraform/scripts/affectedtests/*.*"].each do |file_path| - next if file_path.end_with?('.erb') - fname = file_path.delete_prefix('third_party/terraform/') --%> -'<%= fname -%>': '<%= file_path -%>' -<% end -%> - -'<%= dir -%>/test-fixtures/': 'third_party/terraform/test-fixtures' -<% end -%> -<% if generate_docs -%> -<% Dir["third_party/terraform/website/**/*.*"].each do |file_path| - fname = file_path.split('/', 4)[3] --%> -'website/<%= fname -%>': 'third_party/terraform/website/<%= fname -%>' -<% end -%> -<% end -%> - -<% if version_name == "ga" -%> -# Copy TeamCity-related Kotlin & Markdown files to TPG only, not TPGB -<% - Dir["third_party/terraform/.teamcity/**/*.kt"].each do |file_path| - fname = file_path.delete_prefix("third_party/terraform/") --%> -'<%= fname -%>': '<%= file_path -%>' -<% end -%> -<% - Dir["third_party/terraform/.teamcity/**/*.md"].each do |file_path| - fname = file_path.delete_prefix("third_party/terraform/") --%> -'<%= fname -%>': '<%= file_path -%>' -<% end -%> -'.teamcity/settings.kts': 'third_party/terraform/.teamcity/settings.kts' -'.teamcity/pom.xml': 'third_party/terraform/.teamcity/pom.xml' -'.teamcity/.gitignore': 'third_party/terraform/.teamcity/.gitignore' -'.teamcity/Makefile': 'third_party/terraform/.teamcity/Makefile' -<% end -%> # end if version_name == "ga" - -# Copy all files in the META.d folder -<% - Dir["third_party/terraform/META.d/*.yaml"].each do |file_path| - fname = file_path.delete_prefix("third_party/terraform/") --%> -'<%= fname -%>': '<%= file_path -%>' -<% end -%> -'version/version.go': 'third_party/terraform/version/version.go' -'go.sum': 'third_party/terraform/go.sum' -'.go-version': 'third_party/terraform/.go-version' diff --git a/mmv1/provider/terraform/product~compile.yaml b/mmv1/provider/terraform/product~compile.yaml deleted file mode 100644 index ac4b7f0a5d21..000000000000 --- a/mmv1/provider/terraform/product~compile.yaml +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2018 Google Inc. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# These files contains code that needs to be compiled before being delivered to -# the final module tree structure: -<% - dir = version_name == 'ga' ? 'google' : "google-#{version_name}" --%> -# No entries right now, but an entry would look like this: -# '<%= dir -%>/provider_<%= api.name.underscore -%>_gen.go': 'templates/terraform/provider_gen.erb' diff --git a/mmv1/provider/terraform_tgc_next.go b/mmv1/provider/terraform_tgc_next.go index bb966ec5a56c..3482545c3984 100644 --- a/mmv1/provider/terraform_tgc_next.go +++ b/mmv1/provider/terraform_tgc_next.go @@ -258,7 +258,6 @@ func (tgc TerraformGoogleConversionNext) CopyCommonFiles(outputFolder string, ge "pkg/transport/batcher.go": "third_party/terraform/transport/batcher.go", "pkg/transport/error_retry_predicates.go": "third_party/terraform/transport/error_retry_predicates.go", "pkg/transport/header_transport.go": "third_party/terraform/transport/header_transport.go", - "pkg/transport/mtls_util.go": "third_party/terraform/transport/mtls_util.go", "pkg/transport/retry_transport.go": "third_party/terraform/transport/retry_transport.go", "pkg/transport/retry_utils.go": "third_party/terraform/transport/retry_utils.go", "pkg/transport/transport.go": "third_party/terraform/transport/transport.go", diff --git a/mmv1/templates/terraform/constants/compute_forwarding_rule.go.tmpl b/mmv1/templates/terraform/constants/compute_forwarding_rule.go.tmpl index d8e1d47eb059..f3273680b96f 100644 --- a/mmv1/templates/terraform/constants/compute_forwarding_rule.go.tmpl +++ b/mmv1/templates/terraform/constants/compute_forwarding_rule.go.tmpl @@ -15,6 +15,21 @@ func forwardingRuleCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v } } + // Force recreation if PSC target is updated to a new PSC service attachment and + // the existing target was also a PSC service attachment. + if diff.Id() != "" && diff.HasChange("target") { + oldTarget, newTarget := diff.GetChange("target") + oldTargetStr, oldOk := oldTarget.(string) + newTargetStr, newOk := newTarget.(string) + + // Check if there is an actual semantic change, ignoring v1 vs beta differences + if oldOk && newOk && !tpgresource.CompareSelfLinkRelativePathsIgnoreProjectId("target", oldTargetStr, newTargetStr, nil) { + if strings.Contains(newTargetStr, "/serviceAttachments/") && strings.Contains(oldTargetStr, "/serviceAttachments/") { + diff.ForceNew("target") + } + } + } + // Force recreation if allow_global_access changes for INTERNAL_MANAGED load balancing scheme if diff.Id() != "" && diff.HasChange("allow_global_access") { if loadBalancingScheme, ok := diff.Get("load_balancing_scheme").(string); ok && loadBalancingScheme == "INTERNAL_MANAGED" { diff --git a/mmv1/templates/terraform/constants/source_repo_repository.go.tmpl b/mmv1/templates/terraform/constants/source_repo_repository.go.tmpl index 4684dec4c47e..b5f98578ed63 100644 --- a/mmv1/templates/terraform/constants/source_repo_repository.go.tmpl +++ b/mmv1/templates/terraform/constants/source_repo_repository.go.tmpl @@ -35,7 +35,7 @@ func resourceSourceRepoRepositoryPollRead(d *schema.ResourceData, meta interface return nil, err } - url, err := tpgresource.ReplaceVars(d, config, "{{"{{SourceRepoBasePath}}projects/{{project}}/repos"}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"projects/{{project}}/repos"}}") if err != nil { return nil, err } diff --git a/mmv1/templates/terraform/constants/subnetwork.tmpl b/mmv1/templates/terraform/constants/subnetwork.tmpl index ac8208da7995..0f76dde9212e 100644 --- a/mmv1/templates/terraform/constants/subnetwork.tmpl +++ b/mmv1/templates/terraform/constants/subnetwork.tmpl @@ -67,7 +67,7 @@ func IpDiffSuppress(_, old, new string, d *schema.ResourceData) bool { addr_netmask_old := strings.Split(old, "/") addr_netmask_new := strings.Split(new, "/") - if (!((len(addr_netmask_old)) == 2 && (len(addr_netmask_new) == 2))) { + if !((len(addr_netmask_old)) == 2 && (len(addr_netmask_new) == 2)) { return false } @@ -85,3 +85,138 @@ func IpDiffSuppress(_, old, new string, d *schema.ResourceData) bool { return addr_equality && netmask_equality } + +// CustomDiff function for secondary_ip_range. +// Normalizes old state and new config sets before Set comparison to prevent false TypeSet diffs. +// Specifically handles two Beta-only scenarios where state diverges from HCL config: +// 1. Automatically inherits allocated ULA CIDRs from state when omitted in HCL config. +// 2. Normalizes ip_collection self-links to relative paths to match user config short names. +func resourceComputeSubnetworkSecondaryIpRangeCustomDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error { + return resourceComputeSubnetworkSecondaryIpRangeCustomDiffFunc(diff) +} + +func resourceComputeSubnetworkSecondaryIpRangeCustomDiffFunc(diff tpgresource.TerraformResourceDiff) error { +{{ if and (ne $.TargetVersionName `ga`) (and (ne $.ProductMetadata.Compiler `terraformgoogleconversion-codegen`) (ne $.ProductMetadata.Compiler `terraformgoogleconversionnext-codegen`)) -}} + if len(diff.GetChangedKeysPrefix("secondary_ip_range")) == 0 { + return nil + } + + oldCount, newCount := diff.GetChange("secondary_ip_range.#") + count := oldCount.(int) + if newCount.(int) > count { + count = newCount.(int) + } + if count < 1 { + return nil + } + + // Extract pristine user CIDR config directly from HCL + configCidrByName := make(map[string]string) + rawConfig := diff.GetRawConfig().GetAttr("secondary_ip_range") + if rawConfig.IsKnown() && !rawConfig.IsNull() { + for _, item := range rawConfig.AsValueSlice() { + if item.IsKnown() && !item.IsNull() && item.GetAttr("range_name").IsKnown() && !item.GetAttr("range_name").IsNull() { + nameVal := item.GetAttr("range_name").AsString() + if nameVal != "" { + if cidrVal := item.GetAttr("ip_cidr_range"); cidrVal.IsKnown() && !cidrVal.IsNull() { + configCidrByName[nameVal] = cidrVal.AsString() + } else { + configCidrByName[nameVal] = "" + } + } + } + } + } + + // Extract old state and new proposed maps + oldByName := make(map[string]map[string]interface{}) + var oldList, newList []interface{} + for i := 0; i < count; i++ { + o, n := diff.GetChange(fmt.Sprintf("secondary_ip_range.%d", i)) + if o != nil { + oldList = append(oldList, o) + if m, ok := o.(map[string]interface{}); ok && m["range_name"] != nil { + oldByName[m["range_name"].(string)] = m + } + } + if n != nil { + newList = append(newList, n) + } + } + + // Helper: normalizes CIDR strings and ip_collection self-links + normalizeItem := func(m map[string]interface{}, overrideCidr string) map[string]interface{} { + clean := make(map[string]interface{}) + for k, v := range m { + if k == "ip_cidr_range" { + cidrStr, _ := v.(string) + if overrideCidr != "" { + cidrStr = overrideCidr + } + if cidrStr == "" { + continue + } + if ip, ipNet, err := net.ParseCIDR(cidrStr); err == nil { + maskSize, _ := ipNet.Mask.Size() + cidrStr = fmt.Sprintf("%s/%d", ip.String(), maskSize) + } + clean[k] = cidrStr + continue + } + if v == nil || v == "" { + continue + } + if k == "ip_collection" { + if rel, err := tpgresource.GetRelativePath(v.(string)); err == nil { + clean[k] = rel + } else { + clean[k] = v + } + } else { + clean[k] = v + } + } + return clean + } + + // Build clean normalized sets + var normalizedOld, normalizedNew []interface{} + for _, o := range oldList { + normalizedOld = append(normalizedOld, normalizeItem(o.(map[string]interface{}), "")) + } + for _, n := range newList { + m := n.(map[string]interface{}) + rangeName, _ := m["range_name"].(string) + userCidr := configCidrByName[rangeName] + if userCidr == "" { + // Inherit allocated state CIDR for ULA ranges + if oldItem, ok := oldByName[rangeName]; ok && oldItem["ip_cidr_range"] != nil { + userCidr, _ = oldItem["ip_cidr_range"].(string) + } + } + normalizedNew = append(normalizedNew, normalizeItem(m, userCidr)) + } + + // Compare Sets and Clear Diff + var hashFunc schema.SchemaSetFunc + if ResourceComputeSubnetwork().Schema != nil && ResourceComputeSubnetwork().Schema["secondary_ip_range"] != nil { + hashFunc = schema.HashResource(ResourceComputeSubnetwork().Schema["secondary_ip_range"].Elem.(*schema.Resource)) + } else { + hashFunc = func(v interface{}) int { + buf := &bytes.Buffer{} + json.NewEncoder(buf).Encode(v) + return schema.HashString(buf.String()) + } + } + + if schema.NewSet(hashFunc, normalizedOld).Equal(schema.NewSet(hashFunc, normalizedNew)) { + if err := diff.Clear("secondary_ip_range"); err != nil { + return err + } + } + + return nil +{{ else -}} + return nil +{{ end -}} +} \ No newline at end of file diff --git a/mmv1/templates/terraform/custom_check_destroy/billing_project_info.go.tmpl b/mmv1/templates/terraform/custom_check_destroy/billing_project_info.go.tmpl index ebd8a74ea63d..a3f412f819ab 100644 --- a/mmv1/templates/terraform/custom_check_destroy/billing_project_info.go.tmpl +++ b/mmv1/templates/terraform/custom_check_destroy/billing_project_info.go.tmpl @@ -5,7 +5,7 @@ config := acctest.GoogleProviderConfig(t) -url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{"{{"}}CoreBillingBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/billingInfo") +url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(cloudbilling.Product, config)+"projects/{{"{{"}}project{{"}}"}}/billingInfo") if err != nil { return err } diff --git a/mmv1/templates/terraform/custom_check_destroy/cloudrun_domain_mapping.go.tmpl b/mmv1/templates/terraform/custom_check_destroy/cloudrun_domain_mapping.go.tmpl index 5fe742a49b85..c6ae7f2c0586 100644 --- a/mmv1/templates/terraform/custom_check_destroy/cloudrun_domain_mapping.go.tmpl +++ b/mmv1/templates/terraform/custom_check_destroy/cloudrun_domain_mapping.go.tmpl @@ -1,5 +1,5 @@ // Delete is eventually-consistent; wait for a moment. -time.Sleep(10*time.Second) +time.Sleep(60*time.Second) config := acctest.GoogleProviderConfig(t) url, err := tpgresource.ReplaceVarsForTest(config, rs, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(cloudrun.Product, config), "apis/domains.cloudrun.com/v1/namespaces/{{"{{"}}project}}/domainmappings/{{"{{"}}name{{"}}"}}")) diff --git a/mmv1/templates/terraform/custom_create/chronicle_rule_deployment.go.tmpl b/mmv1/templates/terraform/custom_create/chronicle_rule_deployment.go.tmpl index 8624414b8faa..d172886064a3 100644 --- a/mmv1/templates/terraform/custom_create/chronicle_rule_deployment.go.tmpl +++ b/mmv1/templates/terraform/custom_create/chronicle_rule_deployment.go.tmpl @@ -3,7 +3,7 @@ if err != nil { return err } -url, err := tpgresource.ReplaceVars(d, config, "{{"{{ChronicleBasePath}}projects/{{project}}/locations/{{location}}/instances/{{instance}}/rules/{{rule}}/deployment"}}") +url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"projects/{{project}}/locations/{{location}}/instances/{{instance}}/rules/{{rule}}/deployment"}}") if err != nil { return err } diff --git a/mmv1/templates/terraform/custom_create/source_repo_repository.go.tmpl b/mmv1/templates/terraform/custom_create/source_repo_repository.go.tmpl index 5332b58c17b9..96a6307a4c07 100644 --- a/mmv1/templates/terraform/custom_create/source_repo_repository.go.tmpl +++ b/mmv1/templates/terraform/custom_create/source_repo_repository.go.tmpl @@ -17,7 +17,7 @@ if err != nil { obj["pubsubConfigs"] = pubsubConfigsProp } -url, err := tpgresource.ReplaceVars(d, config, "{{"{{SourceRepoBasePath}}projects/{{project}}/repos"}}") +url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"projects/{{project}}/repos"}}") if err != nil { return err } diff --git a/mmv1/templates/terraform/custom_create/storage_anywhere_cache.go.tmpl b/mmv1/templates/terraform/custom_create/storage_anywhere_cache.go.tmpl index 1580570a5aa5..b5e1ee773850 100644 --- a/mmv1/templates/terraform/custom_create/storage_anywhere_cache.go.tmpl +++ b/mmv1/templates/terraform/custom_create/storage_anywhere_cache.go.tmpl @@ -32,7 +32,7 @@ if v, ok := d.GetOkExists("ingest_on_write"); ok { } -url, err := tpgresource.ReplaceVars(d, config, "{{"{{StorageBasePath}}b/{{bucket}}/anywhereCaches/"}}") +url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"b/{{bucket}}/anywhereCaches/"}}") if err != nil { return err } diff --git a/mmv1/templates/terraform/custom_delete/clear_migration_center_settings.go.tmpl b/mmv1/templates/terraform/custom_delete/clear_migration_center_settings.go.tmpl new file mode 100644 index 000000000000..633ebe3157b1 --- /dev/null +++ b/mmv1/templates/terraform/custom_delete/clear_migration_center_settings.go.tmpl @@ -0,0 +1,48 @@ +billingProject := "" + +project, err := tpgresource.GetProject(d, config) +if err != nil { + return fmt.Errorf("Error fetching project for Settings: %s", err) +} +billingProject = project + +if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp +} + +obj := make(map[string]interface{}) +obj["preferenceSet"] = "" + +url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "projects/{{"{{"}}project{{"}}"}}/locations/{{"{{"}}location{{"}}"}}/settings")) +if err != nil { + return err +} + +log.Printf("[DEBUG] Emptying MigrationCenter Settings %q: %#v", d.Id(), obj) +updateMask := []string{"preferenceSet"} + +url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) +if err != nil { + return err +} + +headers := make(http.Header) +res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutUpdate), + Headers: headers, +}) + +if err != nil { + return fmt.Errorf("Error emptying MigrationCenter Settings %q: %s", d.Id(), err) +} else { + log.Printf("[DEBUG] Finished emptying MigrationCenter Settings %q: %#v", d.Id(), res) +} + +d.SetId("") +return nil diff --git a/mmv1/templates/terraform/custom_expand/config_input_value.go.tmpl b/mmv1/templates/terraform/custom_expand/config_input_value.go.tmpl new file mode 100644 index 000000000000..f484ff28091f --- /dev/null +++ b/mmv1/templates/terraform/custom_expand/config_input_value.go.tmpl @@ -0,0 +1,20 @@ +func expand{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + if v == nil { + return nil, nil + } + + s, ok := v.(string) + if !ok { + return nil, fmt.Errorf("expected {{$.TitlelizeProperty}} to be a string") + } + if s == "" { + return nil, nil + } + + var out interface{} + if err := json.Unmarshal([]byte(s), &out); err != nil { + return nil, fmt.Errorf("{{$.TitlelizeProperty}} must be valid JSON: %w", err) + } + + return out, nil +} diff --git a/mmv1/templates/terraform/custom_flatten/bigquery_connection_configuration_authentication_flatten.go.tmpl b/mmv1/templates/terraform/custom_flatten/bigquery_connection_configuration_authentication_flatten.go.tmpl index 09f47bf56fb4..8c32dbf5621e 100644 --- a/mmv1/templates/terraform/custom_flatten/bigquery_connection_configuration_authentication_flatten.go.tmpl +++ b/mmv1/templates/terraform/custom_flatten/bigquery_connection_configuration_authentication_flatten.go.tmpl @@ -11,14 +11,29 @@ limitations under the License. */ -}} func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + + password := map[string]interface{}{ + // The API redacts the plaintext on read, so we keep the value from + // state to avoid a permadiff. + "plaintext": d.Get("configuration.0.authentication.0.username_password.0.password.0.plaintext"), + } + if originalPassword, ok := original["password"].(map[string]interface{}); ok { + if secretType, ok := originalPassword["secretType"]; ok { + password["secret_type"] = secretType + } + } + return []interface{}{ map[string]interface{}{ - "username": d.Get("configuration.0.authentication.0.username_password.0.username"), - "password": []interface{}{ - map[string]interface{}{ - "plaintext": d.Get("configuration.0.authentication.0.username_password.0.password.0.plaintext"), - }, - }, + "username": original["username"], + "password": []interface{}{password}, }, } } diff --git a/mmv1/templates/terraform/custom_flatten/config_input_value.go.tmpl b/mmv1/templates/terraform/custom_flatten/config_input_value.go.tmpl new file mode 100644 index 000000000000..837a5929fd31 --- /dev/null +++ b/mmv1/templates/terraform/custom_flatten/config_input_value.go.tmpl @@ -0,0 +1,13 @@ +func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return "" + } + + b, err := json.Marshal(v) + if err != nil { + log.Printf("[ERROR] Failed to marshal {{$.TitlelizeProperty}} to JSON: %s", err) + return "" + } + + return string(b) +} diff --git a/mmv1/templates/terraform/custom_flatten/firebasestorage_bucket.go.tmpl b/mmv1/templates/terraform/custom_flatten/firebasestorage_bucket.go.tmpl new file mode 100644 index 000000000000..2d77bfaaa8e0 --- /dev/null +++ b/mmv1/templates/terraform/custom_flatten/firebasestorage_bucket.go.tmpl @@ -0,0 +1,28 @@ +{{/* + The license inside this block applies to this file + Copyright 2026 Google Inc. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ -}} +func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["name"] = original["name"] + if name, ok := original["name"].(string); ok { + parts := strings.Split(name, "/") + transformed["bucket_id"] = parts[len(parts)-1] + } + return []interface{}{transformed} +} diff --git a/mmv1/templates/terraform/custom_flatten/modelarmor_template_multilanguage_detection.go.tmpl b/mmv1/templates/terraform/custom_flatten/modelarmor_template_multilanguage_detection.go.tmpl deleted file mode 100644 index 85abb1979e7a..000000000000 --- a/mmv1/templates/terraform/custom_flatten/modelarmor_template_multilanguage_detection.go.tmpl +++ /dev/null @@ -1,19 +0,0 @@ -func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - if v == nil { - return nil // The whole multi_language_detection block is absent - } - original, ok := v.(map[string]interface{}) - if !ok { - return nil // Should not happen if API is consistent - } - // Populating the field even if the returned block is empty. - transformed := make(map[string]interface{}) - - if val, ok := original["enableMultiLanguageDetection"]; ok { - transformed["enable_multi_language_detection"] = val - } else { - // Since the field is REQUIRED in the schema and the block exists, default to false if the key is missing from the API response. - transformed["enable_multi_language_detection"] = false - } - return []interface{}{transformed} -} \ No newline at end of file diff --git a/mmv1/templates/terraform/custom_flatten/modelarmor_template_template_metadata.go.tmpl b/mmv1/templates/terraform/custom_flatten/modelarmor_template_template_metadata.go.tmpl new file mode 100644 index 000000000000..cb5489082142 --- /dev/null +++ b/mmv1/templates/terraform/custom_flatten/modelarmor_template_template_metadata.go.tmpl @@ -0,0 +1,35 @@ +func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + transformed := make(map[string]interface{}) + transformed["log_template_operations"] = original["logTemplateOperations"] + transformed["log_sanitize_operations"] = original["logSanitizeOperations"] + transformed["multi_language_detection"] = + flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}MultiLanguageDetection(original["multiLanguageDetection"], d, config) + transformed["ignore_partial_invocation_failures"] = original["ignorePartialInvocationFailures"] + transformed["custom_prompt_safety_error_code"] = original["customPromptSafetyErrorCode"] + transformed["custom_prompt_safety_error_message"] = original["customPromptSafetyErrorMessage"] + transformed["custom_llm_response_safety_error_code"] = original["customLlmResponseSafetyErrorCode"] + transformed["custom_llm_response_safety_error_message"] = original["customLlmResponseSafetyErrorMessage"] + transformed["enforcement_type"] = original["enforcementType"] + return []interface{}{transformed} +} + +func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}MultiLanguageDetection(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original, ok := v.(map[string]interface{}) + if !ok { + return nil + } + transformed := make(map[string]interface{}) + if val, ok := original["enableMultiLanguageDetection"]; ok { + transformed["enable_multi_language_detection"] = val + } else { + transformed["enable_multi_language_detection"] = false + } + return []interface{}{transformed} +} diff --git a/mmv1/templates/terraform/custom_import/apigee_data_collector.go.tmpl b/mmv1/templates/terraform/custom_import/apigee_data_collector.go.tmpl new file mode 100644 index 000000000000..0c5a5d7803bf --- /dev/null +++ b/mmv1/templates/terraform/custom_import/apigee_data_collector.go.tmpl @@ -0,0 +1,42 @@ +config := meta.(*transport_tpg.Config) + +// current import_formats cannot import fields with forward slashes in their value +if err := tpgresource.ParseImportId([]string{"(?P.+)"}, d, config); err != nil { + return nil, err +} + +nameParts := strings.Split(d.Get("data_collector_id").(string), "/") +if len(nameParts) == 4 { + // `organizations/{{"{{"}}org_name{{"}}"}}/datacollectors/{{"{{"}}data_collector_id{{"}}"}}` + orgId := fmt.Sprintf("organizations/%s", nameParts[1]) + if err := d.Set("org_id", orgId); err != nil { + return nil, fmt.Errorf("Error setting org_id: %s", err) + } + if err := d.Set("data_collector_id", nameParts[3]); err != nil { + return nil, fmt.Errorf("Error setting data_collector_id: %s", err) + } +} else if len(nameParts) == 3 { + // `organizations/{{"{{"}}org_name{{"}}"}}/{{"{{"}}data_collector_id{{"}}"}}` + orgId := fmt.Sprintf("organizations/%s", nameParts[1]) + if err := d.Set("org_id", orgId); err != nil { + return nil, fmt.Errorf("Error setting org_id: %s", err) + } + if err := d.Set("data_collector_id", nameParts[2]); err != nil { + return nil, fmt.Errorf("Error setting data_collector_id: %s", err) + } +} else { + return nil, fmt.Errorf( + "Saw %s when the name is expected to have shape %s or %s", + d.Get("data_collector_id"), + "organizations/{{"{{"}}org_name{{"}}"}}/datacollectors/{{"{{"}}data_collector_id{{"}}"}}", + "organizations/{{"{{"}}org_name{{"}}"}}/{{"{{"}}data_collector_id{{"}}"}}") +} + +// Replace import id for the resource id +id, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}org_id{{"}}"}}/datacollectors/{{"{{"}}data_collector_id{{"}}"}}") +if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) +} +d.SetId(id) + +return []*schema.ResourceData{d}, nil diff --git a/mmv1/templates/terraform/custom_update/storage_anywhere_cache.go.tmpl b/mmv1/templates/terraform/custom_update/storage_anywhere_cache.go.tmpl index 426c25447a34..eaa9bc1b4872 100644 --- a/mmv1/templates/terraform/custom_update/storage_anywhere_cache.go.tmpl +++ b/mmv1/templates/terraform/custom_update/storage_anywhere_cache.go.tmpl @@ -27,7 +27,7 @@ if d.HasChange("ingest_on_write") { // use haschange obj["ingestOnWrite"] = ingestOnWriteProp } -url, err := tpgresource.ReplaceVars(d, config, "{{"{{StorageBasePath}}b/{{bucket}}/anywhereCaches/{{anywhere_cache_id}}"}}") +url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"b/{{bucket}}/anywhereCaches/{{anywhere_cache_id}}"}}") if err != nil { return err } diff --git a/mmv1/templates/terraform/datasource.html.markdown.tmpl b/mmv1/templates/terraform/datasource.html.markdown.tmpl new file mode 100644 index 000000000000..f15e39da25bf --- /dev/null +++ b/mmv1/templates/terraform/datasource.html.markdown.tmpl @@ -0,0 +1,78 @@ +{{- /* Copyright 2026 Google LLC. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. */ -}} +--- +{{$.MarkdownHeader TemplatePath}} +subcategory: "{{$.ProductMetadata.DisplayName}}" +description: |- + Get information about a {{$.ProductMetadata.DisplayName}} {{$.Name}}. +--- + +# {{$.TerraformName}} + +Get information about a {{$.ProductMetadata.DisplayName}} {{$.Name}}. +{{ if eq $.MinVersion "beta"}} +~> **Warning:** This datasource is in beta, and should be used with the terraform-provider-google-beta provider. +See [Provider Versions](../guides/provider_versions.html.markdown) for more details on beta resources. +{{- end }} +{{ if and $.References.Api (index $.References.Guides "Official Documentation") }} +For more information see the [official documentation]({{index $.References.Guides "Official Documentation"}}) and +the [API]({{$.References.Api}}). +{{- end }} + +## Example Usage + +```hcl +{{- if $.Samples }} +{{- $sample := index $.Samples 0 }} +data "{{$.TerraformName}}" "default" { +{{- if eq $.MinVersionObj.Name "beta" }} + provider = google-beta +{{- end }} +{{- range $fieldName := $.DatasourceRequiredFields }} + {{ $fieldName }} = {{ $sample.ResourceType $.TerraformName }}.{{ $sample.PrimaryResourceId }}.{{ $fieldName }} +{{- end }} +} +{{- end }} +``` + +## Argument Reference + +The following arguments are supported: + +{{ "" }} +{{ "" }} +{{- range $p := $.AllUserProperties }} + {{- range $field := $.DatasourceRequiredFields }} + {{- if eq (underscore $p.Name) (underscore $field) }} + {{- trimTemplate "property_documentation.html.markdown.tmpl" $p -}} + {{- end }} + {{- end }} +{{- end }} +{{ "" }} +{{- range $p := $.AllUserProperties }} + {{- range $field := $.DatasourceOptionalFields }} + {{- if eq (underscore $p.Name) (underscore $field) }} + {{- trimTemplate "property_documentation.html.markdown.tmpl" $p -}} + {{- end }} + {{- end }} +{{- end }} +{{- if or (contains $.BaseUrl "{{project}}") (contains $.CreateUrl "{{project}}")}} +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. +{{ "" }} +{{- end }} + +## Attributes Reference + +See [{{$.TerraformName}}](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/{{replaceAll $.TerraformName "google_" ""}}#argument-reference) resource for details of the available attributes. diff --git a/mmv1/templates/terraform/examples/apigee_data_collector_basic.tf.tmpl b/mmv1/templates/terraform/examples/apigee_data_collector_basic.tf.tmpl new file mode 100644 index 000000000000..cd2a97b0b253 --- /dev/null +++ b/mmv1/templates/terraform/examples/apigee_data_collector_basic.tf.tmpl @@ -0,0 +1,33 @@ +data "google_client_config" "current" {} + +resource "google_compute_network" "apigee_network" { + name = "{{index $.Vars "network_name"}}" +} + +resource "google_compute_global_address" "apigee_range" { + name = "{{index $.Vars "range_name"}}" + purpose = "VPC_PEERING" + address_type = "INTERNAL" + prefix_length = 16 + network = google_compute_network.apigee_network.id +} + +resource "google_service_networking_connection" "apigee_vpc_connection" { + network = google_compute_network.apigee_network.id + service = "servicenetworking.googleapis.com" + reserved_peering_ranges = [google_compute_global_address.apigee_range.name] +} + +resource "google_apigee_organization" "apigee_org" { + analytics_region = "us-central1" + project_id = data.google_client_config.current.project + authorized_network = google_compute_network.apigee_network.id + depends_on = [google_service_networking_connection.apigee_vpc_connection] +} + +resource "google_apigee_data_collector" "apigee_data_collector" { + org_id = google_apigee_organization.apigee_org.id + data_collector_id = "{{index $.Vars "data_collector_id"}}" + description = "A data collector for custom analytics" + type = "INTEGER" +} diff --git a/mmv1/templates/terraform/examples/apigee_data_collector_basic_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_data_collector_basic_test.tf.tmpl new file mode 100644 index 000000000000..25d138fc2a95 --- /dev/null +++ b/mmv1/templates/terraform/examples/apigee_data_collector_basic_test.tf.tmpl @@ -0,0 +1,74 @@ +resource "google_project" "project" { + project_id = "tf-test%{random_suffix}" + name = "tf-test%{random_suffix}" + org_id = "{{index $.TestEnvVars "org_id"}}" + billing_account = "{{index $.TestEnvVars "billing_account"}}" + deletion_policy = "DELETE" +} + +resource "time_sleep" "wait_60_seconds" { + create_duration = "60s" + depends_on = [google_project.project] +} + +resource "google_project_service" "apigee" { + project = google_project.project.project_id + service = "apigee.googleapis.com" + depends_on = [time_sleep.wait_60_seconds] +} + +resource "google_project_service" "compute" { + project = google_project.project.project_id + service = "compute.googleapis.com" + depends_on = [google_project_service.apigee] +} + +resource "google_project_service" "servicenetworking" { + project = google_project.project.project_id + service = "servicenetworking.googleapis.com" + depends_on = [google_project_service.compute] +} + +resource "time_sleep" "wait_300_seconds" { + create_duration = "300s" + depends_on = [google_project_service.servicenetworking] +} + +resource "google_compute_network" "apigee_network" { + name = "apigee-network" + project = google_project.project.project_id + depends_on = [time_sleep.wait_300_seconds] +} + +resource "google_compute_global_address" "apigee_range" { + name = "apigee-range" + purpose = "VPC_PEERING" + address_type = "INTERNAL" + prefix_length = 16 + network = google_compute_network.apigee_network.id + project = google_project.project.project_id +} + +resource "google_service_networking_connection" "apigee_vpc_connection" { + network = google_compute_network.apigee_network.id + service = "servicenetworking.googleapis.com" + reserved_peering_ranges = [google_compute_global_address.apigee_range.name] + depends_on = [google_project_service.servicenetworking] +} + +resource "google_apigee_organization" "apigee_org" { + analytics_region = "us-central1" + project_id = google_project.project.project_id + authorized_network = google_compute_network.apigee_network.id + depends_on = [ + google_service_networking_connection.apigee_vpc_connection, + google_project_service.apigee, + ] +} + +resource "google_apigee_data_collector" "{{$.PrimaryResourceId}}" { + org_id = google_apigee_organization.apigee_org.id + data_collector_id = "dc_tf_test%{random_suffix}" + description = "A test data collector" + type = "INTEGER" +} diff --git a/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_data_residency_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_data_residency_test.tf.tmpl index 58c58a920acb..40e005eb7199 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_data_residency_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_data_residency_test.tf.tmpl @@ -22,6 +22,10 @@ resource "time_sleep" "wait_300_seconds" { depends_on = [google_project_service.apigee] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} + resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { description = "Terraform-provisioned basic Apigee Org under European Union hosting jurisdiction." project_id = google_project.project.project_id @@ -30,10 +34,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { disable_vpc_peering = true depends_on = [ time_sleep.wait_300_seconds, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_disable_vpc_peering_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_disable_vpc_peering_test.tf.tmpl index 91361a2179f5..03f4430d7a83 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_disable_vpc_peering_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_disable_vpc_peering_test.tf.tmpl @@ -16,6 +16,9 @@ resource "time_sleep" "wait_300_seconds" { depends_on = [google_project_service.apigee] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { description = "Terraform-provisioned basic Apigee Org without VPC Peering." @@ -24,10 +27,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { disable_vpc_peering = true depends_on = [ time_sleep.wait_300_seconds, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_test.tf.tmpl index 77f6cca1a927..b28b417e8d04 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_cloud_basic_test.tf.tmpl @@ -56,6 +56,10 @@ resource "google_service_networking_connection" "apigee_vpc_connection" { depends_on = [google_project_service.servicenetworking] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} + resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { analytics_region = "us-central1" project_id = google_project.project.project_id @@ -63,10 +67,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { depends_on = [ google_service_networking_connection.apigee_vpc_connection, google_project_service.apigee, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/apigee_organization_cloud_full_disable_vpc_peering_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_cloud_full_disable_vpc_peering_test.tf.tmpl index 5879b931221e..ad2987d5b012 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_cloud_full_disable_vpc_peering_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_cloud_full_disable_vpc_peering_test.tf.tmpl @@ -79,6 +79,10 @@ resource "time_sleep" "wait_for_iam" { depends_on = [google_kms_crypto_key_iam_member.apigee_sa_keyuser] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} + resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { provider = google-beta @@ -102,10 +106,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { depends_on = [ time_sleep.wait_for_iam, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/apigee_organization_cloud_full_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_cloud_full_test.tf.tmpl index 389da9606f53..f8a218d16101 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_cloud_full_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_cloud_full_test.tf.tmpl @@ -115,6 +115,10 @@ resource "time_sleep" "wait_for_iam" { depends_on = [google_kms_crypto_key_iam_member.apigee_sa_keyuser] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} + resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { provider = google-beta @@ -139,10 +143,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { depends_on = [ google_service_networking_connection.apigee_vpc_connection, time_sleep.wait_for_iam, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/apigee_organization_drz_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_drz_test.tf.tmpl index 97abe4e30ad5..cae78b444747 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_drz_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_drz_test.tf.tmpl @@ -119,6 +119,10 @@ resource "time_sleep" "wait_for_iam" { depends_on = [google_kms_crypto_key_iam_member.apigee_sa_keyuser] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} + resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { provider = google-beta @@ -134,10 +138,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { google_service_networking_connection.apigee_vpc_connection, google_project_service.apigee, time_sleep.wait_for_iam, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/apigee_organization_retention_test.tf.tmpl b/mmv1/templates/terraform/examples/apigee_organization_retention_test.tf.tmpl index 697c7610a001..616152639f60 100644 --- a/mmv1/templates/terraform/examples/apigee_organization_retention_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/apigee_organization_retention_test.tf.tmpl @@ -115,6 +115,10 @@ resource "time_sleep" "wait_for_iam" { depends_on = [google_kms_crypto_key_iam_member.apigee_sa_keyuser] } +resource "time_sleep" "wait_after_destroy" { + destroy_duration = "150s" +} + resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { provider = google-beta @@ -129,10 +133,6 @@ resource "google_apigee_organization" "{{$.PrimaryResourceId}}" { google_service_networking_connection.apigee_vpc_connection, google_project_service.apigee, time_sleep.wait_for_iam, + time_sleep.wait_after_destroy, ] } - -resource "time_sleep" "wait_after_destroy" { - destroy_duration = "150s" - depends_on = [google_apigee_organization.{{$.PrimaryResourceId}}] -} diff --git a/mmv1/templates/terraform/examples/autoscaler_basic.tf.tmpl b/mmv1/templates/terraform/examples/autoscaler_basic.tf.tmpl index d9854df5960b..93ac3eef20e6 100644 --- a/mmv1/templates/terraform/examples/autoscaler_basic.tf.tmpl +++ b/mmv1/templates/terraform/examples/autoscaler_basic.tf.tmpl @@ -7,6 +7,7 @@ resource "google_compute_autoscaler" "foobar" { max_replicas = 5 min_replicas = 1 cooldown_period = 60 + stabilization_period = 300 cpu_utilization { target = 0.5 diff --git a/mmv1/templates/terraform/examples/autoscaler_single_instance.tf.tmpl b/mmv1/templates/terraform/examples/autoscaler_single_instance.tf.tmpl index 728f2e2416d2..61dbca4e0d16 100644 --- a/mmv1/templates/terraform/examples/autoscaler_single_instance.tf.tmpl +++ b/mmv1/templates/terraform/examples/autoscaler_single_instance.tf.tmpl @@ -9,6 +9,7 @@ resource "google_compute_autoscaler" "{{$.PrimaryResourceId}}" { max_replicas = 5 min_replicas = 1 cooldown_period = 60 + stabilization_period = 300 metric { name = "pubsub.googleapis.com/subscription/num_undelivered_messages" @@ -76,4 +77,4 @@ provider "google-beta" { region = "us-central1" zone = "us-central1-a" {{index $.Vars "provider_alias"}} -} \ No newline at end of file +} diff --git a/mmv1/templates/terraform/examples/base_configs/iam_test_file.go.tmpl b/mmv1/templates/terraform/examples/base_configs/iam_test_file.go.tmpl index c11f91bc837a..04acb378ddd8 100644 --- a/mmv1/templates/terraform/examples/base_configs/iam_test_file.go.tmpl +++ b/mmv1/templates/terraform/examples/base_configs/iam_test_file.go.tmpl @@ -12,12 +12,22 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" +{{- if not $.IamPolicy.ExcludeImportTest }} + "github.com/hashicorp/terraform-plugin-testing/tfversion" +{{- end }} "{{ $.ImportPath }}/acctest" "{{ $.ImportPath }}/envvar" "{{ $.ImportPath }}/tpgresource" +{{- if $.FirstTestExample.BootstrapIam }} + "{{ $.ImportPath }}/services/resourcemanager" +{{- end }} ) +{{if $.CustomCode.TestConstants -}} + {{- customTemplate $ $.CustomCode.TestConstants true -}} +{{- end}} + var ( _ = fmt.Sprintf _ = strings.Trim @@ -77,6 +87,11 @@ func TestAcc{{ $.ResourceName }}IamMemberGenerated(t *testing.T) { {{ template "IamTestSetup" $ }} acctest.VcrTest(t, resource.TestCase{ +{{- if not $.IamPolicy.ExcludeImportTest }} + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.RequireAbove(tfversion.Version1_12_0), // resource identity min version + }, +{{- end }} PreCheck: func() { acctest.AccTestPreCheck(t) }, {{- if eq $.MinVersionObj.Name "beta" }} ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), @@ -102,11 +117,15 @@ func TestAcc{{ $.ResourceName }}IamMemberGenerated(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + ResourceName: "{{ $.IamTerraformName }}_member.foo", + ImportState: true, + ImportStateKind: resource.ImportBlockWithResourceIdentity, + }, {{- end }} }, }) } - func TestAcc{{ $.ResourceName }}IamPolicyGenerated(t *testing.T) { t.Parallel() {{ if $.IamPolicy.AdminIamRole }} diff --git a/mmv1/templates/terraform/examples/base_configs/test_file.go.tmpl b/mmv1/templates/terraform/examples/base_configs/test_file.go.tmpl index 2bee4b84ba98..bf06d63c4b26 100644 --- a/mmv1/templates/terraform/examples/base_configs/test_file.go.tmpl +++ b/mmv1/templates/terraform/examples/base_configs/test_file.go.tmpl @@ -31,6 +31,12 @@ import ( "{{ $.ImportPath }}/acctest" "{{ $.ImportPath }}/envvar" "{{ $.ImportPath }}/services/{{ lower $.Res.ProductMetadata.Name }}" +{{ range $s := $.Res.TestExamples }} + {{- if $s.BootstrapIam }} + "{{ $.ImportPath }}/services/resourcemanager" + {{ break }} + {{- end }} +{{- end }} "{{ $.ImportPath }}/tpgresource" transport_tpg "{{ $.ImportPath }}/transport" @@ -73,7 +79,7 @@ func TestAcc{{ $e.TestSlug $.Res.ProductMetadata.Name $.Res.Name }}(t *testing.T t.Parallel() {{- if $e.BootstrapIam }} - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ {{- range $iam := $e.BootstrapIam }} { Member: "{{$iam.Member}}", @@ -159,7 +165,7 @@ func testAccCheck{{ $.Res.ResourceName }}DestroyProducer(t *testing.T) func(s *t {{- else }} config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, fmt.Sprintf("%s%s", transport_tpg.BaseUrl({{ lower $.Res.ProductMetadata.Name }}.Product, config), "{{$.Res.SelfLinkUri}}")) + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl({{ lower $.Res.ProductMetadata.Name }}.Product, config)+"{{$.Res.SelfLinkUri}}") if err != nil { return err } diff --git a/mmv1/templates/terraform/examples/ces_deployment_full.tf.tmpl b/mmv1/templates/terraform/examples/ces_deployment_full.tf.tmpl new file mode 100644 index 000000000000..20cc637db738 --- /dev/null +++ b/mmv1/templates/terraform/examples/ces_deployment_full.tf.tmpl @@ -0,0 +1,34 @@ +resource "google_ces_app" "my-app" { + location = "us" + display_name = "{{index $.Vars "app_display_name"}}" + app_id = "{{index $.Vars "app_id"}}" + time_zone_settings { + time_zone = "America/Los_Angeles" + } +} +resource "google_ces_deployment" "{{$.PrimaryResourceId}}" { + location = "us" + display_name = "{{index $.Vars "deployment_display_name"}}" + app = google_ces_app.my-app.name + app_version = "projects/example-project/locations/us/apps/example-app/versions/example-version" + channel_profile { + channel_type = "API" + disable_barge_in_control = true + disable_dtmf = true + persona_property { + persona = "CHATTY" + } + profile_id = "temp_profile_id" + web_widget_config { + modality = "CHAT_AND_VOICE" + theme = "DARK" + web_widget_title = "temp_webwidget_title" + security_settings { + enable_public_access = true + enable_origin_check = true + allowed_origins = ["https://example.com", "https://test.com"] + enable_recaptcha = true + } + } + } +} diff --git a/mmv1/templates/terraform/examples/ces_guardrail_llm_prompt_security_fail_open.tf.tmpl b/mmv1/templates/terraform/examples/ces_guardrail_llm_prompt_security_fail_open.tf.tmpl new file mode 100644 index 000000000000..b1d6d30b4cbe --- /dev/null +++ b/mmv1/templates/terraform/examples/ces_guardrail_llm_prompt_security_fail_open.tf.tmpl @@ -0,0 +1,33 @@ +resource "google_ces_app" "ces_app_for_guardrail" { + app_id = "{{index $.Vars "app_id"}}" + location = "us" + description = "App used as parent for CES Toolset example" + display_name = "{{index $.Vars "app_display_name"}}" + + language_settings { + default_language_code = "en-US" + supported_language_codes = ["es-ES", "fr-FR"] + enable_multilingual_support = true + fallback_action = "escalate" + } + time_zone_settings { + time_zone = "America/Los_Angeles" + } +} + +resource "google_ces_guardrail" "ces_guardrail_llm_prompt_security_fail_open" { + guardrail_id = "{{index $.Vars "guardrail_id"}}" + location = google_ces_app.ces_app_for_guardrail.location + app = google_ces_app.ces_app_for_guardrail.app_id + display_name = "{{index $.Vars "guardrail_display_name"}}" + description = "Guardrail description" + action { + generative_answer { + prompt = "example_prompt" + } + } + enabled = true + llm_prompt_security { + fail_open = true + } +} diff --git a/mmv1/templates/terraform/examples/chronicle_nativedashboard_basic.tf.tmpl b/mmv1/templates/terraform/examples/chronicle_nativedashboard_basic.tf.tmpl index bf21073c7e26..1e5b9a95f9f3 100644 --- a/mmv1/templates/terraform/examples/chronicle_nativedashboard_basic.tf.tmpl +++ b/mmv1/templates/terraform/examples/chronicle_nativedashboard_basic.tf.tmpl @@ -1,5 +1,4 @@ resource "google_chronicle_native_dashboard" "my_basic_dashboard" { - provider = google-beta location = "us" instance = "{{index $.TestEnvVars "chronicle_id"}}" display_name = "{{index $.Vars "dashboard_name"}}" diff --git a/mmv1/templates/terraform/examples/config_deployment_basic.tf.tmpl b/mmv1/templates/terraform/examples/config_deployment_basic.tf.tmpl new file mode 100644 index 000000000000..f1f395559ed5 --- /dev/null +++ b/mmv1/templates/terraform/examples/config_deployment_basic.tf.tmpl @@ -0,0 +1,22 @@ +resource "google_config_deployment" "{{$.PrimaryResourceId}}" { + name = "{{index $.Vars "deployment_name"}}" + location = "us-central1" + service_account = "projects/{{$.Vars.project}}/serviceAccounts/{{index $.Vars "service_account_email"}}" + + terraform_blueprint { + git_source { + repo = "https://github.com/terraform-google-modules/terraform-google-network" + directory = "modules/vpc" + ref = "main" + } + + input_values { + variable_name = "project_id" + input_value = "{{$.Vars.project}}" + } + input_values { + variable_name = "network_name" + input_value = "my-network" + } + } +} diff --git a/mmv1/templates/terraform/examples/contact_center_insights_encryption_spec_basic.tf.tmpl b/mmv1/templates/terraform/examples/contact_center_insights_encryption_spec_basic.tf.tmpl new file mode 100644 index 000000000000..f4b1c1f70849 --- /dev/null +++ b/mmv1/templates/terraform/examples/contact_center_insights_encryption_spec_basic.tf.tmpl @@ -0,0 +1,72 @@ +resource "google_project" "project" { + provider = google-beta + project_id = "{{index $.Vars "project_id"}}" + name = "{{index $.Vars "project_id"}}" + org_id = "{{index $.TestEnvVars "org_id"}}" + billing_account = "{{index $.TestEnvVars "billing_acct"}}" + deletion_policy = "DELETE" +} + +resource "google_project_service" "cloudkms" { + provider = google-beta + project = google_project.project.project_id + service = "cloudkms.googleapis.com" +} + +resource "google_project_service" "contactcenterinsights" { + provider = google-beta + project = google_project.project.project_id + service = "contactcenterinsights.googleapis.com" + depends_on = [google_project_service.cloudkms] +} + +resource "time_sleep" "wait_enable_service_api" { + depends_on = [ + google_project_service.cloudkms, + google_project_service.contactcenterinsights + ] + create_duration = "30s" +} + +resource "google_project_service_identity" "gcp_sa" { + provider = google-beta + service = "contactcenterinsights.googleapis.com" + project = google_project.project.project_id + depends_on = [time_sleep.wait_enable_service_api] +} + +resource "time_sleep" "wait_create_sa" { + depends_on = [google_project_service_identity.gcp_sa] + create_duration = "30s" +} + +resource "google_kms_key_ring" "keyring" { + provider = google-beta + name = "{{index $.Vars "kms_keyring"}}" + location = "us-east1" + project = google_project.project.project_id + depends_on = [time_sleep.wait_enable_service_api] +} + +resource "google_kms_crypto_key" "key" { + provider = google-beta + name = "{{index $.Vars "kms_key"}}" + key_ring = google_kms_key_ring.keyring.id + purpose = "ENCRYPT_DECRYPT" +} + +resource "google_kms_crypto_key_iam_member" "crypto_key" { + provider = google-beta + crypto_key_id = google_kms_crypto_key.key.id + member = "${replace(google_project_service_identity.gcp_sa.member, "@gcp-sa-contactcenterinsights.iam", "@gcp-sa-ccai-cmek.iam")}" + role = "roles/cloudkms.cryptoKeyEncrypterDecrypter" + depends_on = [time_sleep.wait_create_sa] +} + +resource "google_contact_center_insights_encryption_spec" "{{$.PrimaryResourceId}}" { + provider = google-beta + project = google_project.project.project_id + location = "us-east1" + kms_key = google_kms_crypto_key.key.id + depends_on = [google_kms_crypto_key_iam_member.crypto_key] +} diff --git a/mmv1/templates/terraform/examples/data_lineage_config_project.tf.tmpl b/mmv1/templates/terraform/examples/data_lineage_config_project.tf.tmpl index b031ccd584b1..13c17867457a 100644 --- a/mmv1/templates/terraform/examples/data_lineage_config_project.tf.tmpl +++ b/mmv1/templates/terraform/examples/data_lineage_config_project.tf.tmpl @@ -1,5 +1,23 @@ +resource "google_project" "project" { + project_id = "tf-test%{random_suffix}" + name = "tf-test%{random_suffix}" + org_id = "{{index $.TestEnvVars "org_id"}}" + deletion_policy = "DELETE" +} + +resource "time_sleep" "wait_for_project" { + create_duration = "60s" + depends_on = [google_project.project] +} + +resource "google_project_service" "datalineage_api" { + project = google_project.project.project_id + service = "datalineage.googleapis.com" + depends_on = [time_sleep.wait_for_project] +} + resource "google_data_lineage_config" "{{$.PrimaryResourceId}}" { - parent = "projects/{{index $.TestEnvVars "project"}}" + parent = "projects/${google_project.project.project_id}" location = "global" ingestion { @@ -12,4 +30,5 @@ resource "google_data_lineage_config" "{{$.PrimaryResourceId}}" { } } } + depends_on = [google_project_service.datalineage_api] } diff --git a/mmv1/templates/terraform/examples/database_migration_service_private_connection.tf.tmpl b/mmv1/templates/terraform/examples/database_migration_service_private_connection.tf.tmpl index fde2453a84c9..d44ac27e8a90 100644 --- a/mmv1/templates/terraform/examples/database_migration_service_private_connection.tf.tmpl +++ b/mmv1/templates/terraform/examples/database_migration_service_private_connection.tf.tmpl @@ -1,6 +1,6 @@ resource "google_database_migration_service_private_connection" "{{$.PrimaryResourceId}}" { display_name = "dbms_pc" - location = "us-central1" + location = "us-west1" private_connection_id = "{{index $.Vars "private_connection_id"}}" labels = { diff --git a/mmv1/templates/terraform/examples/database_migration_service_private_connection_psc.tf.tmpl b/mmv1/templates/terraform/examples/database_migration_service_private_connection_psc.tf.tmpl new file mode 100644 index 000000000000..cd9cff25d913 --- /dev/null +++ b/mmv1/templates/terraform/examples/database_migration_service_private_connection_psc.tf.tmpl @@ -0,0 +1,34 @@ +resource "google_database_migration_service_private_connection" "{{$.PrimaryResourceId}}" { + display_name = "dbms_pc" + location = "us-west1" + private_connection_id = "{{index $.Vars "private_connection_id"}}" + + labels = { + key = "value" + } + + psc_interface_config { + network_attachment = resource.google_compute_network_attachment.default.id + } + + create_without_validation = false +} + +resource "google_compute_network_attachment" "default" { + name = "{{index $.Vars "attachment_name"}}" + region = "us-west1" + connection_preference = "ACCEPT_AUTOMATIC" + subnetworks = [resource.google_compute_subnetwork.default.id] +} + +resource "google_compute_network" "default" { + name = "{{index $.Vars "network_name"}}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "default" { + name = "{{index $.Vars "subnetwork_name"}}" + ip_cidr_range = "10.0.0.0/16" + region = "us-west1" + network = google_compute_network.default.id +} diff --git a/mmv1/templates/terraform/examples/datastream_private_connection_psc_interface.tf.tmpl b/mmv1/templates/terraform/examples/datastream_private_connection_psc_interface.tf.tmpl index c4ee92cc100b..9e032d18adfe 100644 --- a/mmv1/templates/terraform/examples/datastream_private_connection_psc_interface.tf.tmpl +++ b/mmv1/templates/terraform/examples/datastream_private_connection_psc_interface.tf.tmpl @@ -1,6 +1,6 @@ resource "google_datastream_private_connection" "{{$.PrimaryResourceId}}" { display_name = "Connection profile" - location = "us-central1" + location = "us-west1" private_connection_id = "{{index $.Vars "private_connection_id"}}" labels = { @@ -14,7 +14,7 @@ resource "google_datastream_private_connection" "{{$.PrimaryResourceId}}" { resource "google_compute_network_attachment" "default" { name = "{{index $.Vars "network_attachment_name"}}" - region = "us-central1" + region = "us-west1" description = "basic network attachment description" connection_preference = "ACCEPT_AUTOMATIC" @@ -30,7 +30,7 @@ resource "google_compute_network" "default" { resource "google_compute_subnetwork" "default" { name = "{{index $.Vars "subnetwork_name"}}" - region = "us-central1" + region = "us-west1" network = google_compute_network.default.id ip_cidr_range = "10.0.0.0/16" diff --git a/mmv1/templates/terraform/examples/dialogflow_conversation_profile_beta_bidi.tf.tmpl b/mmv1/templates/terraform/examples/dialogflow_conversation_profile_beta_bidi.tf.tmpl index f93b96b35f4b..9abc69df8b7d 100644 --- a/mmv1/templates/terraform/examples/dialogflow_conversation_profile_beta_bidi.tf.tmpl +++ b/mmv1/templates/terraform/examples/dialogflow_conversation_profile_beta_bidi.tf.tmpl @@ -1,12 +1,16 @@ resource "google_dialogflow_conversation_profile" "bidi_profile" { provider = google-beta display_name = "{{index $.Vars "profile_name"}}" - location = "global" + location = "europe-west1" language_code = "en-US" use_bidi_streaming = true automated_agent_config { agent = google_ces_app.ces_app_for_agent.id } + sip_config { + allow_virtual_agent_interaction = true + create_conversation_on_the_fly = true + } } resource "google_ces_app" "ces_app_for_agent" { diff --git a/mmv1/templates/terraform/examples/dialogflow_sip_trunk_basic.tf.tmpl b/mmv1/templates/terraform/examples/dialogflow_sip_trunk_basic.tf.tmpl new file mode 100644 index 000000000000..fadda7eacfb2 --- /dev/null +++ b/mmv1/templates/terraform/examples/dialogflow_sip_trunk_basic.tf.tmpl @@ -0,0 +1,7 @@ +resource "google_dialogflow_sip_trunk" "basic_trunk" { + display_name = "{{index $.Vars "trunk_name"}}" + location = "europe-west3" + expected_hostname = [ + "{{index $.Vars "trunk_name"}}.example.com" + ] +} diff --git a/mmv1/templates/terraform/examples/migration_center_assets_export_job_basic.tf.tmpl b/mmv1/templates/terraform/examples/migration_center_assets_export_job_basic.tf.tmpl new file mode 100644 index 000000000000..7ba07db84870 --- /dev/null +++ b/mmv1/templates/terraform/examples/migration_center_assets_export_job_basic.tf.tmpl @@ -0,0 +1,14 @@ +resource "google_migration_center_assets_export_job" "default" { + location = "us-central1" + assets_export_job_id = "{{index $.Vars "assets_export_job_id"}}" + performance_data { + max_days = 30 + } + show_hidden = true + signed_uri_destination { + file_format = "CSV" + } + labels = { + key = "value" + } +} diff --git a/mmv1/templates/terraform/examples/migration_center_report_config_basic.tf.tmpl b/mmv1/templates/terraform/examples/migration_center_report_config_basic.tf.tmpl new file mode 100644 index 000000000000..592513e24667 --- /dev/null +++ b/mmv1/templates/terraform/examples/migration_center_report_config_basic.tf.tmpl @@ -0,0 +1,20 @@ +resource "google_migration_center_group" "default" { + location = "us-central1" + group_id = "{{index $.Vars "group_id"}}" +} + +resource "google_migration_center_preference_set" "default" { + location = "us-central1" + preference_set_id = "{{index $.Vars "pref_set_id"}}" +} + +resource "google_migration_center_report_config" "default" { + location = "us-central1" + report_config_id = "{{index $.Vars "report_config_id"}}" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + group_preferenceset_assignments { + group = google_migration_center_group.default.id + preference_set = google_migration_center_preference_set.default.id + } +} diff --git a/mmv1/templates/terraform/examples/migration_center_settings_basic.tf.tmpl b/mmv1/templates/terraform/examples/migration_center_settings_basic.tf.tmpl new file mode 100644 index 000000000000..bbe7d4f2b040 --- /dev/null +++ b/mmv1/templates/terraform/examples/migration_center_settings_basic.tf.tmpl @@ -0,0 +1,19 @@ +resource "google_migration_center_settings" "default" { + location = "us-central1" + disable_cloud_logging = true + preference_set = google_migration_center_preference_set.default.id +} + +resource "google_migration_center_preference_set" "default" { + location = "us-central1" + preference_set_id = "{{index $.Vars "pref_set_id"}}" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + virtual_machine_preferences { + vmware_engine_preferences { + cpu_overcommit_ratio = 1.5 + } + sizing_optimization_strategy = "SIZING_OPTIMIZATION_STRATEGY_SAME_AS_SOURCE" + target_product = "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE" + } +} diff --git a/mmv1/templates/terraform/examples/migration_center_source_basic.tf.tmpl b/mmv1/templates/terraform/examples/migration_center_source_basic.tf.tmpl new file mode 100644 index 000000000000..694cb4a42350 --- /dev/null +++ b/mmv1/templates/terraform/examples/migration_center_source_basic.tf.tmpl @@ -0,0 +1,9 @@ +resource "google_migration_center_source" "default" { + location = "us-central1" + source_id = "{{index $.Vars "source_id"}}" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + priority = 10 + type = "SOURCE_TYPE_CUSTOM" + managed = false +} diff --git a/mmv1/templates/terraform/examples/modelarmor_template_basic.tf.tmpl b/mmv1/templates/terraform/examples/modelarmor_template_basic.tf.tmpl index 431cbd61de40..3b7b6dc8231f 100644 --- a/mmv1/templates/terraform/examples/modelarmor_template_basic.tf.tmpl +++ b/mmv1/templates/terraform/examples/modelarmor_template_basic.tf.tmpl @@ -9,4 +9,4 @@ resource "google_model_armor_template" "template-basic" { template_metadata { } -} \ No newline at end of file +} diff --git a/mmv1/templates/terraform/examples/network_connectivity_transport_basic.tf.tmpl b/mmv1/templates/terraform/examples/network_connectivity_transport_basic.tf.tmpl index 4eea141960fd..b162d90c3554 100644 --- a/mmv1/templates/terraform/examples/network_connectivity_transport_basic.tf.tmpl +++ b/mmv1/templates/terraform/examples/network_connectivity_transport_basic.tf.tmpl @@ -1,19 +1,15 @@ -data "google_project" "project" { - provider = google-beta -} +data "google_project" "project" {} resource "google_compute_network" "primary-network" { - provider = google-beta name = "tf-test-my-vpc-network%{random_suffix}" auto_create_subnetworks = false } resource "google_network_connectivity_transport" "primary" { - provider = google-beta name = "tf-test-basic-transport%{random_suffix}" region = "us-east4" description = "A sample transport" - remote_profile = "https://networkconnectivity.googleapis.com/v1beta/${data.google_project.project.id}/locations/us-east4/remoteTransportProfiles/aws-us-east-1" + remote_profile = "https://networkconnectivity.googleapis.com/v1/${data.google_project.project.id}/locations/us-east4/remoteTransportProfiles/aws-us-east-1" network = google_compute_network.primary-network.name bandwidth = "BPS_1G" remote_account_id = "123" diff --git a/mmv1/templates/terraform/examples/organization_security_policy_association_excluded.tf.tmpl b/mmv1/templates/terraform/examples/organization_security_policy_association_excluded.tf.tmpl new file mode 100644 index 000000000000..765288e23494 --- /dev/null +++ b/mmv1/templates/terraform/examples/organization_security_policy_association_excluded.tf.tmpl @@ -0,0 +1,26 @@ +resource "google_folder" "security_policy_target" { + display_name = "tf-test-secpol-%{random_suffix}" + parent = "organizations/{{index $.TestEnvVars "org_id"}}" + deletion_protection = false +} + +resource "google_compute_organization_security_policy" "policy" { + short_name = "tf-test%{random_suffix}" + parent = google_folder.security_policy_target.name + type = "CLOUD_ARMOR" +} + +resource "google_compute_organization_security_policy_association" "{{$.PrimaryResourceId}}" { + name = "tf-test%{random_suffix}" + attachment_id = "organizations/{{index $.TestEnvVars "org_id"}}" + policy_id = google_compute_organization_security_policy.policy.id + + excluded_projects = [ + "projects/2000000002", + "projects/3000000003" + ] + excluded_folders = [ + "folders/4000000004", + "folders/5000000005" + ] +} diff --git a/mmv1/templates/terraform/examples/region_autoscaler_basic.tf.tmpl b/mmv1/templates/terraform/examples/region_autoscaler_basic.tf.tmpl index 0623a608d612..74e97de935cc 100644 --- a/mmv1/templates/terraform/examples/region_autoscaler_basic.tf.tmpl +++ b/mmv1/templates/terraform/examples/region_autoscaler_basic.tf.tmpl @@ -7,6 +7,7 @@ resource "google_compute_region_autoscaler" "{{$.PrimaryResourceId}}" { max_replicas = 5 min_replicas = 1 cooldown_period = 60 + stabilization_period = 300 cpu_utilization { target = 0.5 diff --git a/mmv1/templates/terraform/examples/region_backend_service_cache.tf.tmpl b/mmv1/templates/terraform/examples/region_backend_service_cache.tf.tmpl deleted file mode 100644 index fdc97814861e..000000000000 --- a/mmv1/templates/terraform/examples/region_backend_service_cache.tf.tmpl +++ /dev/null @@ -1,31 +0,0 @@ -resource "google_compute_region_backend_service" "{{$.PrimaryResourceId}}" { - provider = google-beta - - name = "{{index $.Vars "region_backend_service_name"}}" - region = "us-central1" - health_checks = [google_compute_region_health_check.default.id] - enable_cdn = true - cdn_policy { - cache_mode = "CACHE_ALL_STATIC" - default_ttl = 3600 - client_ttl = 7200 - max_ttl = 10800 - negative_caching = true - signed_url_cache_max_age_sec = 7200 - } - - load_balancing_scheme = "EXTERNAL" - protocol = "HTTP" - -} - -resource "google_compute_region_health_check" "default" { - provider = google-beta - - name = "{{index $.Vars "health_check_name"}}" - region = "us-central1" - - http_health_check { - port = 80 - } -} diff --git a/mmv1/templates/terraform/examples/region_ssl_policy_basic.tf.tmpl b/mmv1/templates/terraform/examples/region_ssl_policy_basic.tf.tmpl new file mode 100644 index 000000000000..97489b0c3c54 --- /dev/null +++ b/mmv1/templates/terraform/examples/region_ssl_policy_basic.tf.tmpl @@ -0,0 +1,5 @@ +resource "google_compute_region_ssl_policy" "region-ssl-policy" { + name = "{{index $.Vars "region_ssl_policy_name"}}" + region = "us-central1" + profile = "MODERN" +} diff --git a/mmv1/templates/terraform/examples/region_ssl_policy_post_quantum.tf.tmpl b/mmv1/templates/terraform/examples/region_ssl_policy_post_quantum.tf.tmpl new file mode 100644 index 000000000000..259f099db469 --- /dev/null +++ b/mmv1/templates/terraform/examples/region_ssl_policy_post_quantum.tf.tmpl @@ -0,0 +1,7 @@ +resource "google_compute_region_ssl_policy" "post-quantum-region-ssl-policy" { + name = "{{index $.Vars "post_quantum_region_ssl_policy_name"}}" + region = "us-central1" + profile = "MODERN" + min_tls_version = "TLS_1_2" + post_quantum_key_exchange = "ENABLED" +} diff --git a/mmv1/templates/terraform/examples/security_policy_rule_with_body_exclude.tf.tmpl b/mmv1/templates/terraform/examples/security_policy_rule_with_body_exclude.tf.tmpl index 77ad765f868a..862767b622f9 100644 --- a/mmv1/templates/terraform/examples/security_policy_rule_with_body_exclude.tf.tmpl +++ b/mmv1/templates/terraform/examples/security_policy_rule_with_body_exclude.tf.tmpl @@ -1,7 +1,7 @@ resource "google_compute_network" "default" { provider = google-beta - name = "test-network" + name = "{{index $.Vars "network_name"}}" auto_create_subnetworks = false } diff --git a/mmv1/templates/terraform/examples/ssl_policy_post_quantum.tf.tmpl b/mmv1/templates/terraform/examples/ssl_policy_post_quantum.tf.tmpl new file mode 100644 index 000000000000..1064a363d2cd --- /dev/null +++ b/mmv1/templates/terraform/examples/ssl_policy_post_quantum.tf.tmpl @@ -0,0 +1,6 @@ +resource "google_compute_ssl_policy" "post-quantum-ssl-policy" { + name = "{{index $.Vars "post_quantum_ssl_policy_name"}}" + profile = "MODERN" + min_tls_version = "TLS_1_2" + post_quantum_key_exchange = "ENABLED" +} diff --git a/mmv1/templates/terraform/examples/storage_batch_operations_description.tf.tmpl b/mmv1/templates/terraform/examples/storage_batch_operations_description.tf.tmpl new file mode 100644 index 000000000000..894a0c60c49e --- /dev/null +++ b/mmv1/templates/terraform/examples/storage_batch_operations_description.tf.tmpl @@ -0,0 +1,26 @@ +resource "google_storage_bucket" "bucket" { + name = "{{index $.Vars "bucket_name"}}" + location = "us-central1" + force_destroy = true +} + +resource "google_storage_batch_operations_job" "{{$.PrimaryResourceId}}" { + job_id = "{{index $.Vars "job_id"}}" + description = "A sample job description" + bucket_list { + buckets { + bucket = google_storage_bucket.bucket.name + prefix_list { + included_object_prefixes = [ + "bkt" + ] + } + } + } + put_metadata { + custom_metadata = { + "key" = "value" + } + } + delete_protection = false +} \ No newline at end of file diff --git a/mmv1/templates/terraform/examples/subnetwork_with_secondary_ipv6_range.tf.tmpl b/mmv1/templates/terraform/examples/subnetwork_with_secondary_ipv6_range.tf.tmpl new file mode 100644 index 000000000000..b744fa44bac8 --- /dev/null +++ b/mmv1/templates/terraform/examples/subnetwork_with_secondary_ipv6_range.tf.tmpl @@ -0,0 +1,61 @@ +resource "google_compute_subnetwork" "{{$.PrimaryResourceId}}" { + provider = google-beta + name = "{{index $.Vars "subnetwork_name"}}" + region = "us-central1" + network = google_compute_network.custom-test.id + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } + + secondary_ip_range { + range_name = "v6-byogua-auto" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + } + + secondary_ip_range { + range_name = "v6-byogua-manual" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + ip_cidr_range = "2001:db8:0:2::/64" + } +} + +resource "google_compute_network" "custom-test" { + provider = google-beta + name = "{{index $.Vars "network_name"}}" + auto_create_subnetworks = false + enable_ula_internal_ipv6 = true +} + +resource "google_compute_public_advertised_prefix" "ipv6_pap" { + provider = google-beta + name = "{{index $.Vars "pap_name"}}" + ip_cidr_range = "2001:db8::/40" + pdp_scope = "REGIONAL" + ipv6_access_type = "INTERNAL" + description = "GOOGLE_INTERNAL_TEST_PREFIX" +} + +resource "google_compute_public_delegated_prefix" "ipv6_pdp" { + provider = google-beta + name = "{{index $.Vars "pdp_name"}}" + region = "us-central1" + description = "PDP in internal subnet mode" + ip_cidr_range = "2001:db8::/48" + parent_prefix = google_compute_public_advertised_prefix.ipv6_pap.id + mode = "DELEGATION" +} + +resource "google_compute_public_delegated_prefix" "ipv6_sub_pdp" { + provider = google-beta + name = "{{index $.Vars "sub_pdp_name"}}" + region = "us-central1" + ip_cidr_range = "2001:db8::/56" + parent_prefix = google_compute_public_delegated_prefix.ipv6_pdp.id + mode = "INTERNAL_IPV6_SUBNETWORK_CREATION" +} \ No newline at end of file diff --git a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_test.tf.tmpl b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_test.tf.tmpl index a44626ef8b25..2d4f33970025 100644 --- a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_test.tf.tmpl +++ b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_test.tf.tmpl @@ -12,7 +12,7 @@ resource "google_kms_crypto_key_iam_member" "vertexai_encrypterdecrypter" { resource "google_vertex_ai_index_endpoint" "{{$.PrimaryResourceId}}" { provider = google-beta - display_name = "sample-endpoint" + display_name = "{{index $.Vars "index_endpoint_display_name"}}" description = "A sample vertex endpoint" region = "us-central1" labels = { diff --git a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_false_psc.tf.tmpl b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_false_psc.tf.tmpl index 6174a390c2cd..7f8cddb5b4c0 100644 --- a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_false_psc.tf.tmpl +++ b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_false_psc.tf.tmpl @@ -1,5 +1,5 @@ resource "google_vertex_ai_index_endpoint" "{{$.PrimaryResourceId}}" { - display_name = "sample-endpoint" + display_name = "{{index $.Vars "index_endpoint_display_name"}}" description = "A sample vertex endpoint" region = "us-central1" labels = { diff --git a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_psc.tf.tmpl b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_psc.tf.tmpl index 37e8995870bf..8e31cbfcfca8 100644 --- a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_psc.tf.tmpl +++ b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_psc.tf.tmpl @@ -1,5 +1,5 @@ resource "google_vertex_ai_index_endpoint" "{{$.PrimaryResourceId}}" { - display_name = "sample-endpoint" + display_name = "{{index $.Vars "index_endpoint_display_name"}}" description = "A sample vertex endpoint" region = "us-central1" labels = { diff --git a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_public_endpoint.tf.tmpl b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_public_endpoint.tf.tmpl index 76b33617fb93..b04d5e9d7988 100644 --- a/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_public_endpoint.tf.tmpl +++ b/mmv1/templates/terraform/examples/vertex_ai_index_endpoint_with_public_endpoint.tf.tmpl @@ -1,5 +1,5 @@ resource "google_vertex_ai_index_endpoint" "{{$.PrimaryResourceId}}" { - display_name = "sample-endpoint" + display_name = "{{index $.Vars "index_endpoint_display_name"}}" description = "A sample vertex endpoint with an public endpoint" region = "us-central1" labels = { diff --git a/mmv1/templates/terraform/flatten_property_method.go.tmpl b/mmv1/templates/terraform/flatten_property_method.go.tmpl index 3ec456313eef..d5d764eccd8e 100644 --- a/mmv1/templates/terraform/flatten_property_method.go.tmpl +++ b/mmv1/templates/terraform/flatten_property_method.go.tmpl @@ -18,47 +18,9 @@ {{- customTemplate $ $.CustomFlatten false -}} {{- else -}} func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - {{- if and (or $.IgnoreRead $.ClientSide) (not $.ResourceMetadata.ProductMetadata.IsTgcCompiler) }} + {{- if or $.IgnoreRead $.ClientSide }} return d.Get("{{ join $.Lineage ".0." }}") {{- else if $.IsA "NestedObject" }} - {{- if $.ResourceMetadata.ProductMetadata.IsTgcCompiler }} - {{- if and $.HasRequiredProperty $.FlattenObject }} - {{- if $.UserProperties }} - original := make(map[string]interface{}, 0) - if v != nil { - original = v.(map[string]interface{}) - } - {{- end }} - {{- else }} - if v == nil { - return nil - } - {{- if $.UserProperties }} - original := v.(map[string]interface{}) - {{- end }} - {{- end }} - transformed := make(map[string]interface{}) - {{- range $prop := $.UserProperties }} - {{- if or $prop.WriteOnlyLegacy $prop.WriteOnly }} - {{- else if $prop.FlattenObject }} - if {{ $prop.ApiName }} := flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config); {{ $prop.ApiName }} != nil { - obj := {{ $prop.ApiName }}.([]interface{})[0] - for k, v := range obj.(map[string]interface{}) { - transformed[k] = v - } - } - {{- else }} - transformed["{{ underscore $prop.Name }}"] = - flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config) - {{- end }} - {{- end }}{{/* range $prop := $.UserProperties */}} - {{- if not $.AllowEmptyObject }} - if tgcresource.AllValuesAreNil(transformed) { - return nil - } - {{- end }} - return []interface{}{transformed}{{/* if $.IsA "NestedObject" */}} - {{- else }}{{/* $.ResourceMetadata.ProductMetadata.IsTgcCompiler */}} if v == nil { return nil } @@ -85,8 +47,7 @@ func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.Reso flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config) {{- end }} {{- end }}{{/* range $prop := $.UserProperties */}} - return []interface{}{transformed}{{/* if $.IsA "NestedObject" */}} - {{- end }}{{/* not $.ResourceMetadata.ProductMetadata.IsTgcCompiler */}} + return []interface{}{transformed} {{- else if and ($.IsA "Array") ($.ItemType.IsA "NestedObject") }} if v == nil { return v @@ -164,12 +125,6 @@ func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.Reso return intVal } - {{- if and $.ResourceMetadata.ProductMetadata.IsTgcCompiler $.Required }} - if v == nil { - return 0 - } - {{- end }} - return v // let terraform core handle it otherwise {{- else if and ($.IsA "Array") ($.ItemType.IsA "ResourceRef")}} if v == nil { @@ -177,14 +132,10 @@ func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.Reso } return tpgresource.ConvertAndMapStringArr(v.([]interface{}), tpgresource.ConvertSelfLinkToV1) {{- else if $.IsA "ResourceRef" }} - {{- if $.ResourceMetadata.ProductMetadata.IsTgcCompiler }} - {{- template "fullToRelativePath" $ -}} - {{- else }} if v == nil { return v } return tpgresource.ConvertSelfLinkToV1(v.(string)) - {{- end }} {{- else if $.IsSet }} if v == nil { return v @@ -194,39 +145,13 @@ func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.Reso {{- else if or ($.ItemType.IsA "String") ($.ItemType.IsA "Enum") }} return schema.NewSet(schema.HashString, v.([]interface{})) {{- end }} - {{- else if and ($.ResourceMetadata.ProductMetadata.IsTgcCompiler) ($.IsA "Boolean") ($.Required) }} - if v == nil { - return false - } - return v - {{- else if and ($.ResourceMetadata.ProductMetadata.IsTgcCompiler) ($.IsA "String") ($.Required) }} - if v == nil { - return "unknown" - } - transformed := v.(string) - if transformed == "" { - return "unknown" - } - return v - {{- else if and ($.ResourceMetadata.ProductMetadata.IsTgcCompiler) ($.IsA "String") (not $.Required) (not $.DefaultFromApi) (eq $.DefaultValue nil) (not $.SendEmptyValue) }} - if v == nil { - return nil - } - if strVal, ok := v.(string); ok && strVal == "" { - return nil - } - return v {{- else }} return v {{- end }} } {{- if $.NestedProperties }} {{- range $prop := $.NestedProperties }} - {{- if $.ResourceMetadata.ProductMetadata.IsTgcCompiler }} - {{ template "flattenTgcPropertyMethod" $prop -}} - {{- else }} {{ template "flattenPropertyMethod" $prop -}} - {{- end }} {{- end }} {{- end }} {{- end }} diff --git a/mmv1/templates/terraform/iam/iam_test_setup.go.tmpl b/mmv1/templates/terraform/iam/iam_test_setup.go.tmpl index 350843e759c9..0664c33f45a3 100644 --- a/mmv1/templates/terraform/iam/iam_test_setup.go.tmpl +++ b/mmv1/templates/terraform/iam/iam_test_setup.go.tmpl @@ -3,7 +3,7 @@ {{- $sample := $config.Sample }} {{- $step := $config.Step }} {{- if $sample.BootstrapIam }} - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ {{- range $iam := $sample.BootstrapIam }} { Member: "{{$iam.Member}}", diff --git a/mmv1/templates/terraform/iam/iam_test_setup_legacy.go.tmpl b/mmv1/templates/terraform/iam/iam_test_setup_legacy.go.tmpl index fd54b2b1167e..f1ec32060b57 100644 --- a/mmv1/templates/terraform/iam/iam_test_setup_legacy.go.tmpl +++ b/mmv1/templates/terraform/iam/iam_test_setup_legacy.go.tmpl @@ -1,6 +1,6 @@ {{- define "IamTestSetup" }} {{- if $.FirstTestExample.BootstrapIam }} - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ {{- range $iam := $.FirstTestExample.BootstrapIam }} { Member: "{{$iam.Member}}", diff --git a/mmv1/templates/terraform/iam_policy.go.tmpl b/mmv1/templates/terraform/iam_policy.go.tmpl index efbe279d26b9..d42844b5512a 100644 --- a/mmv1/templates/terraform/iam_policy.go.tmpl +++ b/mmv1/templates/terraform/iam_policy.go.tmpl @@ -56,7 +56,7 @@ func init() { Name: "{{ $.TerraformName }}_iam_member", ProductName: "{{ $.ProductMetadata.Name }}", Type: registry.SchemaTypeIAMResource, - Schema: tpgiamresource.ResourceIamMember({{ $.ResourceName }}IamSchema, {{ $.ResourceName }}IamUpdaterProducer, {{ $.ResourceName }}IdParseFunc{{ if $.IamPolicy.DeprecationMessage }}, tpgiamresource.IamWithDeprecationMessage("{{ $.IamPolicy.DeprecationMessage }}"){{- end }}), + Schema: tpgiamresource.ResourceIamMember({{ $.ResourceName }}IamSchema, {{ $.ResourceName }}IamUpdaterProducer, {{ $.ResourceName }}IdParseFunc, tpgiamresource.IamWithParentResourceIdentity({{ $.ResourceName }}IamParentParentResourceIdentityParser){{ if $.IamPolicy.DeprecationMessage }}, tpgiamresource.IamWithDeprecationMessage("{{ $.IamPolicy.DeprecationMessage }}"){{- end }}), }.Register() registry.Schema{ Name: "{{ $.TerraformName }}_iam_policy", @@ -349,6 +349,17 @@ func (u *{{ $.ResourceName }}IamUpdater) GetResourceId() string { return fmt.Sprintf("{{ $.IamResourceUriFormat }}", {{ $.IamResourceUriStringQualifiers }}) } +func {{ $.ResourceName }}IamParentParentResourceIdentityParser(d *schema.ResourceData, identity *schema.IdentityData, transportConfig *transport_tpg.Config) (string, error) { + return tpgiamresource.ParseIamResourceIdentity(d, identity, transportConfig, tpgiamresource.IamResourceIdentityConfig{ + Params: []tpgiamresource.IamIdentityParam{ +{{- range $param := $.IamResourceParams }} + {Key: "{{ camelize $param "lower" }}", IdentityKey: "{{ underscore $param }}"}, +{{- end }} + }, + UriFormat: "{{ $.IamResourceUriFormat }}", + }) +} + func (u *{{ $.ResourceName }}IamUpdater) GetMutexKey() string { return fmt.Sprintf("iam-{{ lower $.ProductMetadata.Name }}-{{ lower $.Name }}-%s", u.GetResourceId()) } diff --git a/mmv1/templates/terraform/list_resource.go.tmpl b/mmv1/templates/terraform/list_resource.go.tmpl new file mode 100644 index 000000000000..3e2cfc4a794a --- /dev/null +++ b/mmv1/templates/terraform/list_resource.go.tmpl @@ -0,0 +1,124 @@ +{{/* The license inside this block applies to this file + Copyright 2026 Google LLC. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. */ -}} +// Copyright IBM Corp. 2014, 2026 +// SPDX-License-Identifier: MPL-2.0 + +{{$.CodeHeader TemplatePath}} + +package {{ lower $.ProductMetadata.Name }} + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/list" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "{{ $.ImportPath }}/registry" + "{{ $.ImportPath }}/tpgresource" + transport_tpg "{{ $.ImportPath }}/transport" +) + +func init() { + registry.FrameworkListResource{ + Name: "{{ $.TerraformName }}", + ProductName: "{{ $.ProductMetadata.Name }}", + Func: New{{ $.ResourceName -}}ListResource, + }.Register() +} + +var _ list.ListResource = &{{ $.ResourceName -}}ListResource{} + +type {{ $.ResourceName -}}ListResource struct { + tpgresource.ListResourceMetadata +} + +func New{{ $.ResourceName -}}ListResource() list.ListResource { + listR := &{{ $.ResourceName -}}ListResource{} + listR.TypeName = "{{ $.TerraformName }}" + listR.SDKv2Resource = Resource{{ $.ResourceName -}}() + listR.ListConfigFields = []tpgresource.ListConfigField{ +{{- range $scope := $.ListScopeProperties }} + {Name: "{{ underscore $scope.Name }}", Kind: tpgresource.ListConfigKindString, Optional: {{ if $scope.Required }}false{{ else }}true{{ end }}}, +{{- end }} + } + return listR +} + +// {{ $.ResourceName }}ListModel matches ListResourceMetadata.ListConfigFields (tfsdk names and types). +type {{ $.ResourceName -}}ListModel struct { +{{- range $scope := $.ListScopeProperties }} + {{ $scope.TitlelizeProperty }} types.String `tfsdk:"{{ underscore $scope.Name }}"` +{{- end }} +} + +func (listR *{{ $.ResourceName -}}ListResource) List(ctx context.Context, listReq list.ListRequest, stream *list.ListResultsStream) { + var data {{ $.ResourceName -}}ListModel + diags := listReq.Config.Get(ctx, &data) + if diags.HasError() { + stream.Results = list.ListResultsStreamDiagnostics(diags) + return + } + if listR.Client == nil { + diags = append(diags, diag.NewErrorDiagnostic( + "Provider not configured", + "The Google provider client is not available; ensure the provider is configured (e.g. credentials and default project).", + )) + stream.Results = list.ListResultsStreamDiagnostics(diags) + return + } + +{{- range $scope := $.ListScopeProperties }} +{{- if or (eq $scope.Name "project") (eq $scope.Name "region") (eq $scope.Name "zone") (eq $scope.Name "location") }} + {{ $scope.CamelizeProperty }} := listR.Get{{ $scope.TitlelizeProperty }}(data.{{ $scope.TitlelizeProperty }}) +{{- else }} + {{ $scope.CamelizeProperty }} := data.{{ $scope.TitlelizeProperty }}.ValueString() +{{- end }} +{{- end }} + + stream.Results = func(push func(list.ListResult) bool) { + err := List{{ $.ResourceName }}s( + listR.Client, +{{- range $scope := $.ListScopeProperties }} + {{ $scope.CamelizeProperty }}, +{{- end }} + func(rd *schema.ResourceData) error { + result := listReq.NewListResult(ctx) + + if err := listR.SetResult(ctx, listReq.IncludeResource, &result, rd{{- range $k := $.ListResultDisplayNameKeyStrings }}, "{{ $k }}"{{- end }}); err != nil { + return err + } + + if !push(result) { + return errors.New("stream closed") + } + return nil + }, + ) + if err != nil { + diags.AddError("API Error", err.Error()) + result := listReq.NewListResult(ctx) + result.Diagnostics = diags + push(result) + } + } +} + +{{ template "listResourceMethod" $ }} diff --git a/mmv1/templates/terraform/list_resource.html.markdown.tmpl b/mmv1/templates/terraform/list_resource.html.markdown.tmpl new file mode 100644 index 000000000000..e99ce4564186 --- /dev/null +++ b/mmv1/templates/terraform/list_resource.html.markdown.tmpl @@ -0,0 +1,54 @@ +{{- /* Copyright 2024 Google LLC. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. */ -}} +--- +{{$.MarkdownHeader TemplatePath}} +subcategory: "{{$.ProductMetadata.DisplayName}}" +description: |- + List {{$.ProductMetadata.DisplayName}} {{lower $.Name}} resources in a project for use with terraform query + and .tfquery.hcl files. +--- + +# {{$.TerraformName}} (list) + +Lists [`{{$.TerraformName}}`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/{{$.TerraformName}}) resources for use with [`terraform query`](https://developer.hashicorp.com/terraform/cli/commands/query) and **`.tfquery.hcl`** files. + +For how list resources work in this provider, file layout, Terraform version requirements, and shared `list` block arguments, refer to the guide [Use list resources with terraform query (Google Cloud provider)](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/using_list_resources_with_terraform_query). + +## Example + +```hcl +list "{{$.TerraformName}}" "all" { + provider = {{ if eq $.MinVersion "beta" }}google-beta{{ else }}google{{ end }} + + config { +{{- range $scope := $.ListScopeProperties }} + {{ underscore $scope.Name }} = {{ if $scope.Required }}"..."{{ else }}"..." # Optional{{ end }} +{{- end }} + } +} +``` + +Run `terraform query` from the directory that contains the `.tfquery.hcl` file. + +## Configuration (`config` block) + +{{- range $scope := $.ListScopeProperties }} +* `{{ underscore $scope.Name }}` - ({{ if $scope.Required }}Required{{ else }}Optional{{ end }}){{ if $scope.Description }} {{ $scope.Description }}{{ end }} +{{- end }} + +## Results + +By default each result includes **resource identity** for [`{{$.TerraformName}}`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/{{$.TerraformName}}) (see [Resource identity](https://developer.hashicorp.com/terraform/language/resources/identities)). + +With `include_resource = true` on the `list` block, results also include the full resource-style attributes documented for the managed [`{{$.TerraformName}}` resource](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/{{$.TerraformName}}#attributes-reference). diff --git a/mmv1/templates/terraform/list_resource_method.go.tmpl b/mmv1/templates/terraform/list_resource_method.go.tmpl new file mode 100644 index 000000000000..65f6d9661562 --- /dev/null +++ b/mmv1/templates/terraform/list_resource_method.go.tmpl @@ -0,0 +1,114 @@ +{{/* The license inside this block applies to this file + Copyright 2024 Google LLC. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. */ -}} +{{ define "listResourceMethod" }} +func List{{ $.ResourceName }}s(config *transport_tpg.Config, +{{- range $scope := $.ListScopeProperties }} + {{ $scope.CamelizeProperty }} string, +{{- end }} + callback func(*schema.ResourceData) error, +) error { + resourceData := Resource{{ $.ResourceName }}().Data(&terraform.InstanceState{}) +{{- range $scope := $.ListScopeProperties }} + if {{ $scope.CamelizeProperty }} != "" { + if err := resourceData.Set("{{ underscore $scope.Name }}", {{ $scope.CamelizeProperty }}); err != nil { + return fmt.Errorf("error setting {{ underscore $scope.Name }} on temporary resource data: %w", err) + } + } +{{- end }} + + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(resourceData, config, "{{"{{"}}{{$.ProductMetadata.Name}}BasePath{{"}}"}}{{$.BaseUrl}}") + if err != nil { + return err + } + +{{- if $.HasProject }} + billingProject := project +{{- else }} + billingProject := "" +{{- end }} + if bp, err := tpgresource.GetBillingProject(resourceData, config); err == nil { + billingProject = bp + } + + userAgent, err := tpgresource.GenerateUserAgentString(resourceData, config.UserAgent) + if err != nil { + return err + } + + return transport_tpg.ListPages(transport_tpg.ListPagesOptions{ + Config: config, + TempData: resourceData, + Resource: Resource{{ $.ResourceName -}}(), + ListURL: url, + BillingProject: billingProject, + UserAgent: userAgent, + ItemName: "{{ $.CollectionUrlKey }}", + Flattener: func(res map[string]interface{}, d *schema.ResourceData, config *transport_tpg.Config) error { + headers := make(http.Header) + var err error +{{- if $.CustomCode.PostRead }} + {{ customTemplate $ $.CustomCode.PostRead false -}} +{{- end }} +{{- if $.NestedQuery }} + res, err = flattenNested{{ $.ResourceName -}}(d, config, res) + if err != nil { + return err + } + if res == nil { + return fmt.Errorf("error matching nested {{ $.ResourceName }} from list response") + } +{{- end }} +{{- if $.CustomCode.Decoder }} + res, err = resource{{ $.ResourceName -}}Decoder(d, config, res) + if err != nil { + return err + } + if res == nil { + return fmt.Errorf("error decoding {{ $.ResourceName }} from list response") + } +{{- end }} + if err = Resource{{ $.ResourceName }}Flatten(d, config, res, config, {{ if $.HasProject }}project, {{ end }}userAgent, billingProject, url, headers); err != nil { + return err + } +{{- /* url_param_only identity fields (e.g. name) are not GettableProperties, so the flattener does not Set them. Copy from res → d here so SetId/ListResultDisplayName can find them. Integer ids sometimes arrive as strings and need coercion. */ -}} +{{- range $id := $.IdentityProperties }} +{{- if $id.ApiName }} + if v, ok := res["{{ $id.ApiName }}"]; ok && v != nil { + {{- if eq $id.Type "Integer" }} + if s, ok := v.(string); ok { + i, err := strconv.Atoi(s) + if err != nil { + return fmt.Errorf("error coercing {{ underscore $id.Name }}: %w", err) + } + v = i + } + {{- end }} + if err := d.Set("{{ underscore $id.Name }}", v); err != nil { + return fmt.Errorf("error setting {{ underscore $id.Name }}: %w", err) + } + } +{{- end }} +{{- end }} + id, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, "{{ $.IdFormat -}}") + if err != nil { + return fmt.Errorf("error constructing id: %w", err) + } + d.SetId(id) + return nil + }, + Callback: callback, + }) +} +{{ end }} diff --git a/mmv1/templates/terraform/operation.go.tmpl b/mmv1/templates/terraform/operation.go.tmpl index 8bddac026be7..b68ae3481311 100644 --- a/mmv1/templates/terraform/operation.go.tmpl +++ b/mmv1/templates/terraform/operation.go.tmpl @@ -64,11 +64,8 @@ func (w *{{ $.ProductMetadata.Name }}OperationWaiter) QueryOp() (interface{}, er return nil, fmt.Errorf("Cannot query operation, it's unset or nil.") } // Returns the proper get. - url := fmt.Sprintf( - "%s%s", - transport_tpg.BaseUrl(Product, w.Config), - fmt.Sprintf("{{ replaceAll $.GetAsync.Operation.BaseUrl "{{op_id}}" "%s" }}", w.CommonOperationWaiter.Op.Name), - ) + url := transport_tpg.BaseUrl(Product, w.Config) + url += fmt.Sprintf("{{ replaceAll $.GetAsync.Operation.BaseUrl "{{op_id}}" "%s" }}", w.CommonOperationWaiter.Op.Name) {{- if $.ProductMetadata.Version.RepEnabled }} if strings.Contains(url, "{{"{{"}}location{{"}}"}}") && w.Location == "" { return nil, fmt.Errorf("failed to find location for a resource with a regionalized endpoint %s", url) diff --git a/mmv1/templates/terraform/post_update/compute_subnetwork.go.tmpl b/mmv1/templates/terraform/post_update/compute_subnetwork.go.tmpl index 804890056730..86d9707a7eb4 100644 --- a/mmv1/templates/terraform/post_update/compute_subnetwork.go.tmpl +++ b/mmv1/templates/terraform/post_update/compute_subnetwork.go.tmpl @@ -1,9 +1,10 @@ // Handle the "Send Empty" override logic if v, ok := d.GetOk("send_secondary_ip_range_if_empty"); ok && v.(bool) { - if sv, ok := d.GetOk("secondary_ip_range"); ok { + oldRanges, _ := d.GetChange("secondary_ip_range") + if oldRanges != nil { configValue := d.GetRawConfig().GetAttr("secondary_ip_range") - stateValue := sv.([]interface{}) - if configValue.LengthInt() == 0 && len(stateValue) != 0 { + stateValue := oldRanges.([]interface{}) + if (configValue.IsNull() || configValue.LengthInt() == 0) && len(stateValue) != 0 { log.Printf("[DEBUG] Sending empty secondary_ip_range in update") obj := make(map[string]interface{}) obj["secondaryIpRanges"] = make([]interface{}, 0) diff --git a/mmv1/templates/terraform/pre_create/bigquery_analyticshub_subscription.tmpl b/mmv1/templates/terraform/pre_create/bigquery_analyticshub_subscription.tmpl index de25e06d902c..b2c102cb53f9 100644 --- a/mmv1/templates/terraform/pre_create/bigquery_analyticshub_subscription.tmpl +++ b/mmv1/templates/terraform/pre_create/bigquery_analyticshub_subscription.tmpl @@ -1,6 +1,6 @@ // check if this is a listing subscription instead of a data exchange subscription if _, ok := d.GetOk("listing_id"); ok { - url, err = tpgresource.ReplaceVars(d, config, "{{BigqueryAnalyticsHubBasePath}}projects/{{project}}/locations/{{location}}/dataExchanges/{{data_exchange_id}}/listings/{{listing_id}}:subscribe") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/dataExchanges/{{data_exchange_id}}/listings/{{listing_id}}:subscribe") if err != nil { return err } diff --git a/mmv1/templates/terraform/pre_create/bigquery_reservation_assignment.go.tmpl b/mmv1/templates/terraform/pre_create/bigquery_reservation_assignment.go.tmpl index c4a0cdfda0f2..d4ba7aaaf63f 100644 --- a/mmv1/templates/terraform/pre_create/bigquery_reservation_assignment.go.tmpl +++ b/mmv1/templates/terraform/pre_create/bigquery_reservation_assignment.go.tmpl @@ -1,20 +1,22 @@ - if _, ok := d.GetOkExists("location"); !ok { - // Extract location from parent reservation. - reservation := d.Get("reservation").(string) + if _, ok := d.GetOkExists("location"); !ok { + reservation := d.Get("reservation").(string) + tableRef := regexp.MustCompile("projects/(.+)/locations/(.+)/reservations/(.+)") + if parts := tableRef.FindStringSubmatch(reservation); parts != nil { + if err := d.Set("location", parts[2]); err != nil { + return err + } + } else { + return fmt.Errorf( + "`location` is required on google_bigquery_reservation_assignment "+ + "when `reservation` is given as a bare name (got %q). Either set "+ + "`location` explicitly on the assignment, or pass `reservation` "+ + "as the full path `projects/{project}/locations/{location}/"+ + "reservations/{name}` (typically `google_bigquery_reservation..id`).", + reservation, + ) + } - tableRef := regexp.MustCompile("projects/(.+)/locations/(.+)/reservations/(.+)") - if parts := tableRef.FindStringSubmatch(reservation); parts != nil { - err := d.Set("location", parts[2]) - if err != nil { - return err - } - } - - if strings.Contains(url, "locations//") { - // re-compute url now that location must be set - url = strings.ReplaceAll(url, "/locations//", "/locations/"+d.Get("location").(string)+"/") - if err != nil { - return err - } - } - } + if strings.Contains(url, "locations//") { + url = strings.ReplaceAll(url, "/locations//", "/locations/"+d.Get("location").(string)+"/") + } + } diff --git a/mmv1/templates/terraform/pre_create/compute_snapshot_precreate_url.go.tmpl b/mmv1/templates/terraform/pre_create/compute_snapshot_precreate_url.go.tmpl index e55b972fb1b8..3018a96a0779 100644 --- a/mmv1/templates/terraform/pre_create/compute_snapshot_precreate_url.go.tmpl +++ b/mmv1/templates/terraform/pre_create/compute_snapshot_precreate_url.go.tmpl @@ -2,7 +2,7 @@ if sourceDiskProp != "" { url = regexp.MustCompile("PRE_CREATE_REPLACE_ME").ReplaceAllLiteralString(url, sourceDiskProp.(string)) } else if sourceInstantSnapshotProp != "" { - url, err = tpgresource.ReplaceVars(d, config, {{ printf "%q" "{{ComputeBasePath}}projects/{{project}}/global/snapshots" }}) + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"projects/{{project}}/global/snapshots"}}") if err != nil { return err } diff --git a/mmv1/templates/terraform/pre_create/contactcenterinsights_encryption_spec_pre_create.go.tmpl b/mmv1/templates/terraform/pre_create/contactcenterinsights_encryption_spec_pre_create.go.tmpl new file mode 100644 index 000000000000..967e5d806bbc --- /dev/null +++ b/mmv1/templates/terraform/pre_create/contactcenterinsights_encryption_spec_pre_create.go.tmpl @@ -0,0 +1,20 @@ +location := d.Get("location").(string) +universeDomain := config.UniverseDomain + +if universeDomain != "" && universeDomain != "googleapis.com" { + url = strings.Replace(url, "googleapis.com", universeDomain, 1) +} + +if strings.HasPrefix(url, "https://contactcenterinsights") { + if location != "" && location != "us-central1" { + url = strings.Replace(url, "https://contactcenterinsights", fmt.Sprintf("https://%s-contactcenterinsights", location), 1) + } +} + +// Wrap kmsKey in encryption_spec for creation +if kmsKey, ok := obj["kmsKey"]; ok { + obj["encryption_spec"] = map[string]interface{}{ + "kms_key": kmsKey, + } + delete(obj, "kmsKey") +} diff --git a/mmv1/templates/terraform/pre_create/contactcenterinsights_set_endpoint.go.tmpl b/mmv1/templates/terraform/pre_create/contactcenterinsights_set_endpoint.go.tmpl new file mode 100644 index 000000000000..78a2457b469b --- /dev/null +++ b/mmv1/templates/terraform/pre_create/contactcenterinsights_set_endpoint.go.tmpl @@ -0,0 +1,12 @@ +location := d.Get("location").(string) +universeDomain := config.UniverseDomain + +if universeDomain != "" && universeDomain != "googleapis.com" { + url = strings.Replace(url, "googleapis.com", universeDomain, 1) +} + +if strings.HasPrefix(url, "https://contactcenterinsights") { + if location != "" && location != "us-central1" { + url = strings.Replace(url, "https://contactcenterinsights", fmt.Sprintf("https://%s-contactcenterinsights", location), 1) + } +} diff --git a/mmv1/templates/terraform/pre_delete/firestore_database.go.tmpl b/mmv1/templates/terraform/pre_delete/firestore_database.go.tmpl index 2f396d07df3d..93cf63940568 100644 --- a/mmv1/templates/terraform/pre_delete/firestore_database.go.tmpl +++ b/mmv1/templates/terraform/pre_delete/firestore_database.go.tmpl @@ -1,7 +1,3 @@ -if deletionPolicy := d.Get("deletion_policy"); deletionPolicy != "DELETE" { - log.Printf("[WARN] Firestore database %q deletion_policy is not set to 'DELETE', skipping deletion", d.Get("name").(string)) - return nil -} if deleteProtection := d.Get("delete_protection_state"); deleteProtection == "DELETE_PROTECTION_ENABLED" { return fmt.Errorf("Cannot delete Firestore database %s: Delete Protection is enabled. Set delete_protection_state to DELETE_PROTECTION_DISABLED for this resource and run \"terraform apply\" before attempting to delete it.", d.Get("name").(string)) } diff --git a/mmv1/templates/terraform/pre_delete/regional_secret_version_deletion_policy.go.tmpl b/mmv1/templates/terraform/pre_delete/regional_secret_version_deletion_policy.go.tmpl index 63b88d34db56..57bfac2273f1 100644 --- a/mmv1/templates/terraform/pre_delete/regional_secret_version_deletion_policy.go.tmpl +++ b/mmv1/templates/terraform/pre_delete/regional_secret_version_deletion_policy.go.tmpl @@ -12,9 +12,7 @@ */ -}} deletionPolicy := d.Get("deletion_policy"); -if deletionPolicy == "ABANDON" { - return nil -} else if deletionPolicy == "DISABLE" { +if deletionPolicy == "DISABLE" { url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}SecretManagerRegionalBasePath{{"}}"}}{{"{{"}}name{{"}}"}}:disable") if err != nil { return err diff --git a/mmv1/templates/terraform/pre_delete/secret_version_deletion_policy.go.tmpl b/mmv1/templates/terraform/pre_delete/secret_version_deletion_policy.go.tmpl index cba329bad5ed..333bb71a04e9 100644 --- a/mmv1/templates/terraform/pre_delete/secret_version_deletion_policy.go.tmpl +++ b/mmv1/templates/terraform/pre_delete/secret_version_deletion_policy.go.tmpl @@ -11,10 +11,7 @@ limitations under the License. */ -}} deletionPolicy := d.Get("deletion_policy"); - -if deletionPolicy == "ABANDON" { - return nil -} else if deletionPolicy == "DISABLE" { +if deletionPolicy == "DISABLE" { url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}SecretManagerBasePath{{"}}"}}{{"{{"}}name{{"}}"}}:disable") if err != nil { return err diff --git a/mmv1/templates/terraform/pre_update/chronicle_dashboard_chart_dashboard_query.go.tmpl b/mmv1/templates/terraform/pre_update/chronicle_dashboard_chart_dashboard_query.go.tmpl index 3341f369acc3..9834baa5fccb 100644 --- a/mmv1/templates/terraform/pre_update/chronicle_dashboard_chart_dashboard_query.go.tmpl +++ b/mmv1/templates/terraform/pre_update/chronicle_dashboard_chart_dashboard_query.go.tmpl @@ -15,7 +15,7 @@ if queryName == "" { } // 2. URL Formatting -baseUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{ChronicleBasePath}}"}}") +baseUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return err } diff --git a/mmv1/templates/terraform/pre_update/datafusion_instance_update.go.tmpl b/mmv1/templates/terraform/pre_update/datafusion_instance_update.go.tmpl index 4c4b3d392082..fe8e9e6c53ab 100644 --- a/mmv1/templates/terraform/pre_update/datafusion_instance_update.go.tmpl +++ b/mmv1/templates/terraform/pre_update/datafusion_instance_update.go.tmpl @@ -24,6 +24,10 @@ if d.HasChange("enable_rbac") { updateMask = append(updateMask, "enableRbac") } +if d.HasChange("maintenance_policy") { + updateMask = append(updateMask, "maintenancePolicy") +} + // updateMask is a URL parameter but not present in the schema, so ReplaceVars // won't set it diff --git a/mmv1/templates/terraform/pre_update/fw_datafusion_instance_update.go.tmpl b/mmv1/templates/terraform/pre_update/fw_datafusion_instance_update.go.tmpl index 8b3b701a19b7..e2924988618c 100644 --- a/mmv1/templates/terraform/pre_update/fw_datafusion_instance_update.go.tmpl +++ b/mmv1/templates/terraform/pre_update/fw_datafusion_instance_update.go.tmpl @@ -24,6 +24,10 @@ if !plan.EnableRbac.Equal(state.EnableRbac) { updateMask = append(updateMask, "enableRbac") } +if !plan.MaintenancePolicy.Equal(state.MaintenancePolicy) { + updateMask = append(updateMask, "maintenancePolicy") +} + // updateMask is a URL parameter but not present in the schema, so ReplaceVars // won't set it diff --git a/mmv1/templates/terraform/pre_update/modelarmor_template.go.tmpl b/mmv1/templates/terraform/pre_update/modelarmor_template.go.tmpl new file mode 100644 index 000000000000..10549f5e95e0 --- /dev/null +++ b/mmv1/templates/terraform/pre_update/modelarmor_template.go.tmpl @@ -0,0 +1,11 @@ +// Ensure templateMetadata is in the request body when it's in the update mask. +// When template_metadata is not in the user's config, the expand function +// returns nil so templateMetadata is absent from obj. But if the API previously +// returned default values that were stored in state, HasChange detects drift +// and adds templateMetadata to the update mask. The API rejects a PATCH with +// templateMetadata in the mask but missing from the body (REQUEST_FIELD_MISSING). +if d.HasChange("template_metadata") { + if _, ok := obj["templateMetadata"]; !ok { + obj["templateMetadata"] = make(map[string]interface{}) + } +} diff --git a/mmv1/templates/terraform/resource.go.tmpl b/mmv1/templates/terraform/resource.go.tmpl index 8ebed9a5de15..5c1a05f39559 100644 --- a/mmv1/templates/terraform/resource.go.tmpl +++ b/mmv1/templates/terraform/resource.go.tmpl @@ -104,7 +104,7 @@ func Resource{{ $.ResourceName -}}() *schema.Resource { return &schema.Resource{ Create: resource{{ $.ResourceName -}}Create, Read: resource{{ $.ResourceName -}}Read, -{{- if or (or $.Updatable $.RootLabels) $.VirtualFields }} +{{- if or (or $.Updatable $.RootLabels (and (not $.ExcludeDelete) (not $.DeletionPolicyExclude))) $.VirtualFields }} Update: resource{{ $.ResourceName -}}Update, {{- end}} Delete: resource{{ $.ResourceName -}}Delete, @@ -161,6 +161,9 @@ func Resource{{ $.ResourceName -}}() *schema.Resource { {{- end -}} {{if and ($.HasZone) (not $.ExcludeDefaultCdiff) }} tpgresource.DefaultProviderZone, +{{- end }} +{{- if and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)}} + tpgresource.DefaultProviderDeletionPolicy("{{$.DeletionPolicyDefault}}"), {{- end }} ), {{- end}} @@ -212,8 +215,10 @@ func Resource{{ $.ResourceName -}}() *schema.Resource { {{template "SchemaFields" $prop -}} {{- end }} {{- range $prop := $.VirtualFields }} + {{- if not $prop.Exclude }} {{template "SchemaFields" $prop -}} {{- end }} + {{- end }} {{- if $.CustomCode.ExtraSchemaEntry }} {{ customTemplate $ $.CustomCode.ExtraSchemaEntry false -}} {{- end}} @@ -230,6 +235,24 @@ func Resource{{ $.ResourceName -}}() *schema.Resource { Type: schema.TypeString, Computed: true, }, +{{- end}} +{{- if and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)}} + "deletion_policy": { + Type: schema.TypeString, + Optional: true, + Computed: true, + {{- if $.DeletionPolicyCustomDocs}} + Description: `This field uses a custom implementation please refer to documentation under /hashicorp/terraform-provider-google-beta/website/docs/r/{{ underscore $.ResourceName}}.html.markdown for specifics`, + {{else}} + Description: `Whether Terraform will be prevented from destroying the instance. Defaults to "{{$.DeletionPolicyDefault}}". +When a 'terraform destroy' or 'terraform apply' would delete the instance, +the command will fail if this field is set to "PREVENT" in Terraform state. +When set to "ABANDON", the command will remove the resource from Terraform +management without updating or deleting the resource in the API. +When set to "DELETE", deleting the resource is allowed. +`, + {{- end}} + }, {{- end}} }, UseJSONNumber: true, @@ -292,7 +315,7 @@ func resource{{ $.ResourceName -}}Create(d *schema.ResourceData, meta interface{ defer transport_tpg.MutexStore.Unlock(lockName) {{- end}} - url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{$.CreateUri}}")) + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{$.CreateUri}}") if err != nil { return err } @@ -347,9 +370,17 @@ func resource{{ $.ResourceName -}}Create(d *schema.ResourceData, meta interface{ {{- if $.CustomCode.PreCreate }} {{ customTemplate $ $.CustomCode.PreCreate false -}} {{- end}} +{{- if $.RPCCreateMethod }} + res, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCCreateMethod -}}", +{{- else }} res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ upper $.CreateVerb -}}", +{{- end}} Project: billingProject, RawURL: url, UserAgent: userAgent, @@ -552,7 +583,7 @@ func resource{{ $.ResourceName -}}PollRead(d *schema.ResourceData, meta interfac return func() (map[string]interface{}, error) { config := meta.(*transport_tpg.Config) - url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{$.SelfLinkUri}}")) + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{$.SelfLinkUri}}") if err != nil { return nil, err } @@ -592,9 +623,17 @@ func resource{{ $.ResourceName -}}PollRead(d *schema.ResourceData, meta interfac return nil, err } +{{ if $.RPCReadMethod -}} + res, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCReadMethod -}}", +{{- else }} res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ upper $.ReadVerb -}}", +{{- end}} Project: billingProject, RawURL: url, UserAgent: userAgent, @@ -648,7 +687,7 @@ func resource{{ $.ResourceName -}}Read(d *schema.ResourceData, meta interface{}) return err } - url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{$.SelfLinkUri}}{{$.ReadQueryParams}}")) + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{$.SelfLinkUri}}{{$.ReadQueryParams}}") if err != nil { return err } @@ -687,9 +726,17 @@ func resource{{ $.ResourceName -}}Read(d *schema.ResourceData, meta interface{}) {{- if $.CustomCode.PreRead }} {{ customTemplate $ $.CustomCode.PreRead false -}} {{- end }} +{{- if $.RPCReadMethod }} + res, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCReadMethod -}}", +{{- else }} res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ upper $.ReadVerb -}}", +{{- end}} Project: billingProject, RawURL: url, UserAgent: userAgent, @@ -742,7 +789,7 @@ func resource{{ $.ResourceName -}}Read(d *schema.ResourceData, meta interface{}) return nil } {{ end}} -{{- if $.VirtualFields }} +{{- if or $.VirtualFields (and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)) }} // Explicitly set virtual fields to default values if unset {{- range $prop := $.VirtualFields }} @@ -754,6 +801,20 @@ func resource{{ $.ResourceName -}}Read(d *schema.ResourceData, meta interface{}) } {{- end}} {{- end}} +{{- if and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)}} + if _, ok := d.GetOkExists("deletion_policy"); !ok { + //prioritize config's value if present + if config.DeletionPolicy != ""{ + if err := d.Set("deletion_policy", config.DeletionPolicy); err != nil { + return fmt.Errorf("Error setting deletion_policy: %s", err) + } + }else{ + if err := d.Set("deletion_policy", "{{ $.DeletionPolicyDefault -}}"); err != nil { + return fmt.Errorf("Error setting deletion_policy: %s", err) + } + } + } +{{- end}} {{- end}} {{- if $.HasProject }} if err := d.Set("project", project); err != nil { @@ -815,7 +876,21 @@ func resource{{ $.ResourceName -}}Read(d *schema.ResourceData, meta interface{}) {{if $.Updatable -}} func resource{{ $.ResourceName -}}Update(d *schema.ResourceData, meta interface{}) error { -{{- if and ($.GetAsync) (and ($.GetAsync.IsA "OpAsync") ($.GetAsync.IncludeProject) ($.GetAsync.Allow "update")) -}} +{{- if and (and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)) (not $.BypassClientsideUpdateCheck)}} + clientSideFields := map[string]bool{"deletion_policy": true} + clientSideOnly := true + for field := range Resource{{ $.ResourceName -}}().Schema { + if d.HasChange(field) && !clientSideFields[field] { + clientSideOnly = false + break + } + } + if clientSideOnly { + log.Print("[DEBUG] Only client-side changes detected. Cancelling update operation.") + return resource{{ $.ResourceName -}}Read(d, meta) + } +{{- end}} +{{ if and ($.GetAsync) (and ($.GetAsync.IsA "OpAsync") ($.GetAsync.IncludeProject) ($.GetAsync.Allow "update")) -}} var project string {{- end}} config := meta.(*transport_tpg.Config) @@ -904,7 +979,7 @@ func resource{{ $.ResourceName -}}Update(d *schema.ResourceData, meta interface{ defer transport_tpg.MutexStore.Unlock(lockName) {{- end}} - url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{ $.UpdateUri }}")) + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{ $.UpdateUri }}") if err != nil { return err } @@ -946,9 +1021,17 @@ func resource{{ $.ResourceName -}}Update(d *schema.ResourceData, meta interface{ // if updateMask is empty we are not updating anything so skip the post if len(updateMask) > 0 { {{- end}} +{{- if $.RPCUpdateMethod }} + res, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCUpdateMethod -}}", +{{- else }} res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ $.UpdateVerb -}}", +{{- end}} Project: billingProject, RawURL: url, UserAgent: userAgent, @@ -1007,7 +1090,7 @@ if len(updateMask) > 0 { if d.HasChange("{{ join ($.PropertyNamesToStrings (index $CustomUpdateProps $group)) "\") || d.HasChange(\""}}") { obj := make(map[string]interface{}) {{ if $group.FingerprintName }} - getUrl, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{$.SelfLinkUri}}")) + getUrl, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{$.SelfLinkUri}}") if err != nil { return err } @@ -1027,9 +1110,17 @@ if d.HasChange("{{ join ($.PropertyNamesToStrings (index $CustomUpdateProps $gro billingProject = bp } +{{ if $.RPCReadMethod -}} + getRes, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCReadMethod -}}", +{{- else }} getRes, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ upper $.ReadVerb -}}", +{{- end}} Project: billingProject, RawURL: getUrl, UserAgent: userAgent, @@ -1094,7 +1185,7 @@ if d.HasChange("{{ join ($.PropertyNamesToStrings (index $CustomUpdateProps $gro transport_tpg.MutexStore.Lock(lockName) defer transport_tpg.MutexStore.Unlock(lockName) {{- end}} - url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{ $group.UpdateUrl }}")) + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{ $group.UpdateUrl }}") if err != nil { return err } @@ -1119,9 +1210,17 @@ if d.HasChange("{{ join ($.PropertyNamesToStrings (index $CustomUpdateProps $gro billingProject = bp } +{{ if $.RPCUpdateMethod -}} + res, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCUpdateMethod -}}", +{{- else }} res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ $group.UpdateVerb }}", +{{- end}} Project: billingProject, RawURL: url, UserAgent: userAgent, @@ -1176,9 +1275,9 @@ if d.HasChange("{{ join ($.PropertyNamesToStrings (index $CustomUpdateProps $gro return resource{{ $.ResourceName -}}Read(d, meta) {{- end }}{{/*if CustomUpdate*/}} } -{{ else if or $.RootLabels $.VirtualFields -}}{{/*if not immutable*/}} +{{ else if or $.RootLabels $.VirtualFields (and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)) -}}{{/*if not immutable*/}} func resource{{ $.ResourceName -}}Update(d *schema.ResourceData, meta interface{}) error { - // Only the root field "labels", "terraform_labels", and virtual fields are mutable + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable return resource{{ $.ResourceName -}}Read(d, meta) } @@ -1192,6 +1291,15 @@ func resource{{ $.ResourceName }}Delete(d *schema.ResourceData, meta interface{} return nil {{- else }} +{{- if and (not $.ExcludeDelete) (not $.DeletionPolicyExclude)}} + if d.Get("deletion_policy").(string) == "PREVENT" { + return fmt.Errorf("cannot destroy {{$.ResourceName}} without setting deletion_policy=\"DELETE\" and running `terraform apply`") + } + if d.Get("deletion_policy").(string) == "ABANDON" { + log.Printf("[DEBUG] deletion_policy set to \"ABANDON\", removing {{ $.Name }} %q from Terraform state without deletion", d.Id()) + return nil + } +{{- end }} {{- if and ($.GetAsync) (and (and ($.GetAsync.IsA "OpAsync") $.GetAsync.IncludeProject) ($.GetAsync.Allow "delete")) }} var project string {{- end }} @@ -1225,7 +1333,7 @@ func resource{{ $.ResourceName }}Delete(d *schema.ResourceData, meta interface{} transport_tpg.MutexStore.Lock(lockName) defer transport_tpg.MutexStore.Unlock(lockName) {{- end }} - url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(Product, config), "{{$.DeleteUri}}")) + url, err := tpgresource.ReplaceVars{{if $.LegacyLongFormProject -}}ForId{{ end -}}(d, config, transport_tpg.BaseUrl(Product, config)+"{{$.DeleteUri}}") if err != nil { return err } @@ -1267,9 +1375,17 @@ func resource{{ $.ResourceName }}Delete(d *schema.ResourceData, meta interface{} {{- end }} log.Printf("[DEBUG] Deleting {{ $.Name }} %q", d.Id()) +{{- if $.RPCDeleteMethod }} + res, err := transport_tpg.SendRequestRPC(transport_tpg.SendRequestOptions{ + Config: config, + Product: "{{ $.ProductMetadata.Name -}}", + RPCService: "{{ $.RPCService -}}", + Method: "{{ $.RPCDeleteMethod -}}", +{{- else }} res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "{{ camelize $.DeleteVerb "upper" -}}", +{{- end}} Project: billingProject, RawURL: url, UserAgent: userAgent, diff --git a/mmv1/templates/terraform/resource.html.markdown.tmpl b/mmv1/templates/terraform/resource.html.markdown.tmpl index e4a0ae88244c..9439393556e8 100644 --- a/mmv1/templates/terraform/resource.html.markdown.tmpl +++ b/mmv1/templates/terraform/resource.html.markdown.tmpl @@ -125,6 +125,14 @@ The following arguments are supported: If it is not provided, the provider project is used. {{ "" }} {{- end }} +{{- if and (not $.DeletionPolicyExclude) (not $.DeletionPolicyCustomDocs)}} +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to {{$.DeletionPolicyDefault}}. + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. +{{- end }} {{- range $f := $.VirtualFields }} * `{{$f.Name}}` - (Optional) {{$f.Description}} {{- end }} diff --git a/mmv1/templates/terraform/samples/base_configs/iam_test_file.go.tmpl b/mmv1/templates/terraform/samples/base_configs/iam_test_file.go.tmpl index 449b53fee0e7..2ae5204223e5 100644 --- a/mmv1/templates/terraform/samples/base_configs/iam_test_file.go.tmpl +++ b/mmv1/templates/terraform/samples/base_configs/iam_test_file.go.tmpl @@ -12,12 +12,22 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" +{{- if not $.IamPolicy.ExcludeImportTest }} + "github.com/hashicorp/terraform-plugin-testing/tfversion" +{{- end }} "{{ $.ImportPath }}/acctest" "{{ $.ImportPath }}/envvar" "{{ $.ImportPath }}/tpgresource" +{{- range $service, $alias := ($.FirstTestConfig.Step.TestServiceDependencies $.Runtime.ResourcePrefixServiceMap) }} + {{ $alias }} "{{ $.ImportPath }}/services/{{ $service }}" +{{- end }} ) +{{if $.CustomCode.TestConstants -}} + {{- customTemplate $ $.CustomCode.TestConstants true -}} +{{- end}} + var ( _ = fmt.Sprintf _ = strings.Trim @@ -80,6 +90,11 @@ func TestAcc{{ $.ResourceName }}IamMemberGenerated(t *testing.T) { {{ template "IamTestSetupSample" $ }} acctest.VcrTest(t, resource.TestCase{ +{{- if not $.IamPolicy.ExcludeImportTest }} + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.RequireAbove(tfversion.Version1_12_0), // resource identity min version + }, +{{- end }} PreCheck: func() { acctest.AccTestPreCheck(t) }, {{- if eq $.MinVersionObj.Name "beta" }} ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), @@ -105,11 +120,15 @@ func TestAcc{{ $.ResourceName }}IamMemberGenerated(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + ResourceName: "{{ $.IamTerraformName }}_member.foo", + ImportState: true, + ImportStateKind: resource.ImportBlockWithResourceIdentity, + }, {{- end }} }, }) } - func TestAcc{{ $.ResourceName }}IamPolicyGenerated(t *testing.T) { t.Parallel() {{ if $.IamPolicy.AdminIamRole }} diff --git a/mmv1/templates/terraform/samples/base_configs/query_test_file.go.tmpl b/mmv1/templates/terraform/samples/base_configs/query_test_file.go.tmpl new file mode 100644 index 000000000000..24b26a5a7c80 --- /dev/null +++ b/mmv1/templates/terraform/samples/base_configs/query_test_file.go.tmpl @@ -0,0 +1,141 @@ +{{/* The license inside this block applies to this file + Copyright 2024 Google LLC. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. */ -}} +// Copyright IBM Corp. 2014, 2026 +// SPDX-License-Identifier: MPL-2.0 + +{{$.CodeHeader TemplatePath}} + +package {{ lower $.ProductMetadata.Name }}_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/querycheck" + "github.com/hashicorp/terraform-plugin-testing/querycheck/queryfilter" + "github.com/hashicorp/terraform-plugin-testing/tfversion" + + "{{ $.ImportPath }}/acctest" + "{{ $.ImportPath }}/envvar" +) + +var ( + _ = envvar.TestEnvVar +) + +{{ $sample := $.FirstTestConfig.Sample }} +{{ $step := $.FirstTestConfig.Step }} +func TestAcc{{ $.ResourceName }}ListQuery_generated(t *testing.T) { + t.Parallel() + + {{- if $sample.SkipVcr }} + acctest.SkipIfVcr(t) + {{- end }} + + {{- if $sample.BootstrapIam }} + acctest.BootstrapIamMembers(t, []acctest.IamMember{ + {{- range $iam := $sample.BootstrapIam }} + { + Member: "{{$iam.Member}}", + Role: "{{$iam.Role}}", + }, + {{- end}} + }) + {{- end }} + + randomSuffix := acctest.RandString(t, 10) + context := map[string]interface{}{ + {{- template "EnvVarContext" dict "TestEnvVars" $step.TestEnvVars "HasNewLine" false}} + {{- range $varKey, $varVal := $step.TestContextVars }} + "{{$varKey}}": {{$varVal}}, + {{- end }} + {{- range $scope := $.ListScopeProperties }} + {{- $n := underscore $scope.Name }} + {{- if or (eq $n "region") (eq $n "location") }} + "{{$n}}": envvar.GetTestRegionFromEnv(), + {{- else if eq $n "zone" }} + "zone": envvar.GetTestZoneFromEnv(), + {{- else if eq $n "project" }} + {{- if not (index $step.TestEnvVars "project") }} + "project": envvar.GetTestProjectFromEnv(), + {{- end }} + {{- end }} + {{- end }} + "random_suffix": randomSuffix, + } + + var listDisplayName acctest.ListDisplayName + acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.SkipBelow(tfversion.Version1_14_0), + }, + PreCheck: func() { acctest.AccTestPreCheck(t) }, +{{- if $.VersionedProvider $sample.MinVersion }} + ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), +{{- else }} + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + {{- if $sample.ExternalProviders }} + ExternalProviders: map[string]resource.ExternalProvider{ + {{- range $provider := $sample.ExternalProviders }} + "{{$provider}}": {}, + {{- end }} + }, + {{- end }} +{{- end }} +{{- if not $.ExcludeDelete }} + CheckDestroy: testAccCheck{{ $.ResourceName }}DestroyProducer(t), +{{- end }} + Steps: []resource.TestStep{ + { + Config: testAcc{{ $step.TestStepSlug $.ProductMetadata.Name $.Name }}(context), + Check: resource.ComposeTestCheckFunc( + listDisplayName.Capture( + "{{ $sample.ResourceType $.TerraformName }}.{{ $sample.PrimaryResourceId }}", + []string{ + {{- range $key := $.ListResultDisplayNameKeyStrings }} + "{{ $key }}", + {{- end }} + }, + ), + ), + }, + { + Query: true, + Config: testAcc{{ $step.TestStepSlug $.ProductMetadata.Name $.Name }}ListQuery(context), + QueryResultChecks: []querycheck.QueryResultCheck{ + querycheck.ExpectLengthAtLeast("{{ $sample.ResourceType $.TerraformName }}.list_query", 1), + querycheck.ExpectResourceDisplayName( + "{{ $sample.ResourceType $.TerraformName }}.list_query", + queryfilter.ByDisplayName(listDisplayName.CheckValue()), + listDisplayName.CheckValue(), + ), + }, + }, + }, + }) +} + +func testAcc{{ $step.TestStepSlug $.ProductMetadata.Name $.Name }}ListQuery(context map[string]interface{}) string { + return acctest.Nprintf(` +list "{{ $sample.ResourceType $.TerraformName }}" "list_query" { + provider = {{ if $.VersionedProvider $sample.MinVersion }}google-beta{{ else }}google{{ end }} + config { +{{- range $scope := $.ListScopeProperties }} + {{ underscore $scope.Name }} = "%{{"{"}}{{ underscore $scope.Name }}{{"}"}}" +{{- end }} + } +} +`, context) +} diff --git a/mmv1/templates/terraform/samples/base_configs/test_file.go.tmpl b/mmv1/templates/terraform/samples/base_configs/test_file.go.tmpl index ff005afc877e..92a88ef8b9dc 100644 --- a/mmv1/templates/terraform/samples/base_configs/test_file.go.tmpl +++ b/mmv1/templates/terraform/samples/base_configs/test_file.go.tmpl @@ -24,6 +24,7 @@ package {{ $.Res.PackageName }}_test +{{if or (gt (len $.Res.TestSamples) 0) (not $.Res.ExcludeDelete) -}} import ( "fmt" "log" @@ -41,10 +42,14 @@ import ( "{{ $.ImportPath }}/acctest" "{{ $.ImportPath }}/envvar" "{{ $.ImportPath }}/services/{{ lower $.Res.ProductMetadata.Name }}" +{{- range $service, $alias := $.Res.TestServiceDependencies }} + {{ $alias }} "{{ $.ImportPath }}/services/{{ $service }}" +{{- end }} "{{ $.ImportPath }}/tpgresource" transport_tpg "{{ $.ImportPath }}/transport" "google.golang.org/api/googleapi" + ) {{if $.Res.CustomCode.TestConstants -}} @@ -82,7 +87,7 @@ func TestAcc{{ $s.TestSampleSlug $.Res.ProductMetadata.Name $.Res.Name }}(t *tes t.Parallel() {{- if $s.BootstrapIam }} - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ {{- range $iam := $s.BootstrapIam }} { Member: "{{$iam.Member}}", @@ -191,7 +196,7 @@ func testAccCheck{{ $.Res.ResourceName }}DestroyProducer(t *testing.T) func(s *t {{- else }} config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, fmt.Sprintf("%s%s", transport_tpg.BaseUrl({{ lower $.Res.ProductMetadata.Name }}.Product, config), "{{$.Res.SelfLinkUri}}")) + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl({{ lower $.Res.ProductMetadata.Name }}.Product, config)+"{{$.Res.SelfLinkUri}}") if err != nil { return err } @@ -229,4 +234,5 @@ func testAccCheck{{ $.Res.ResourceName }}DestroyProducer(t *testing.T) func(s *t return nil } } +{{- end }} {{- end }} \ No newline at end of file diff --git a/mmv1/templates/terraform/examples/cloud_run_service_basic.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_basic.tf.tmpl similarity index 81% rename from mmv1/templates/terraform/examples/cloud_run_service_basic.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_basic.tf.tmpl index 2e2bf9c1fc51..1ebfc564932e 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_basic.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_basic.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_gpu.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_gpu.tf.tmpl similarity index 91% rename from mmv1/templates/terraform/examples/cloud_run_service_gpu.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_gpu.tf.tmpl index 3a984bba23c0..06b5c816cfb7 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_gpu.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_gpu.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" metadata { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_iap.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_iap.tf.tmpl similarity index 80% rename from mmv1/templates/terraform/examples/cloud_run_service_iap.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_iap.tf.tmpl index d0b6ed0b9e00..4471e3f70a95 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_iap.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_iap.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" metadata { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_multicontainer.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_multicontainer.tf.tmpl similarity index 94% rename from mmv1/templates/terraform/examples/cloud_run_service_multicontainer.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_multicontainer.tf.tmpl index 018457894208..8a4dadf4427b 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_multicontainer.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_multicontainer.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" provider = google-beta diff --git a/mmv1/templates/terraform/examples/cloud_run_service_multiple_environment_variables.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_multiple_environment_variables.tf.tmpl similarity index 90% rename from mmv1/templates/terraform/examples/cloud_run_service_multiple_environment_variables.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_multiple_environment_variables.tf.tmpl index 4a768b1a036a..5af6e3bcfb0f 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_multiple_environment_variables.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_multiple_environment_variables.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_noauth.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_noauth.tf.tmpl similarity index 90% rename from mmv1/templates/terraform/examples/cloud_run_service_noauth.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_noauth.tf.tmpl index be4c904ef2fe..5ff0f62ced33 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_noauth.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_noauth.tf.tmpl @@ -1,6 +1,6 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_probes.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_probes.tf.tmpl similarity index 90% rename from mmv1/templates/terraform/examples/cloud_run_service_probes.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_probes.tf.tmpl index ed54ebdbb763..b2e60e57f144 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_probes.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_probes.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_readiness_probe.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_readiness_probe.tf.tmpl similarity index 90% rename from mmv1/templates/terraform/examples/cloud_run_service_readiness_probe.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_readiness_probe.tf.tmpl index 894d49ba90f3..6341f5a68e17 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_readiness_probe.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_readiness_probe.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" metadata { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_secret_environment_variables.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_secret_environment_variables.tf.tmpl similarity index 91% rename from mmv1/templates/terraform/examples/cloud_run_service_secret_environment_variables.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_secret_environment_variables.tf.tmpl index 93e25d4a9baf..0e73170ba93c 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_secret_environment_variables.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_secret_environment_variables.tf.tmpl @@ -2,7 +2,7 @@ data "google_project" "project" { } resource "google_secret_manager_secret" "secret" { - secret_id = "{{index $.Vars "secret_id"}}" + secret_id = "{{index $.ResourceIdVars "secret_id"}}" replication { auto {} } @@ -21,7 +21,7 @@ resource "google_secret_manager_secret_iam_member" "secret-access" { } resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_secret_volumes.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_secret_volumes.tf.tmpl similarity index 92% rename from mmv1/templates/terraform/examples/cloud_run_service_secret_volumes.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_secret_volumes.tf.tmpl index 28db3c3b9c8d..b347258fa518 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_secret_volumes.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_secret_volumes.tf.tmpl @@ -2,7 +2,7 @@ data "google_project" "project" { } resource "google_secret_manager_secret" "secret" { - secret_id = "{{index $.Vars "secret_id"}}" + secret_id = "{{index $.ResourceIdVars "secret_id"}}" replication { auto {} } @@ -21,7 +21,7 @@ resource "google_secret_manager_secret_iam_member" "secret-access" { } resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { diff --git a/mmv1/templates/terraform/examples/cloud_run_service_sql.tf.tmpl b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_sql.tf.tmpl similarity index 84% rename from mmv1/templates/terraform/examples/cloud_run_service_sql.tf.tmpl rename to mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_sql.tf.tmpl index d22ea4e38de1..025152780aad 100644 --- a/mmv1/templates/terraform/examples/cloud_run_service_sql.tf.tmpl +++ b/mmv1/templates/terraform/samples/services/cloudrun/cloud_run_service_sql.tf.tmpl @@ -1,5 +1,5 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { - name = "{{index $.Vars "cloud_run_service_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_service_name"}}" location = "us-central1" template { @@ -21,7 +21,7 @@ resource "google_cloud_run_service" "{{$.PrimaryResourceId}}" { } resource "google_sql_database_instance" "instance" { - name = "{{index $.Vars "cloud_run_sql_name"}}" + name = "{{index $.ResourceIdVars "cloud_run_sql_name"}}" region = "us-east1" database_version = "MYSQL_5_7" settings { diff --git a/mmv1/templates/terraform/samples/services/workstations/workstation_cluster_custom_urls.tf.tmpl b/mmv1/templates/terraform/samples/services/workstations/workstation_cluster_custom_urls.tf.tmpl new file mode 100644 index 000000000000..8f24353a3379 --- /dev/null +++ b/mmv1/templates/terraform/samples/services/workstations/workstation_cluster_custom_urls.tf.tmpl @@ -0,0 +1,24 @@ +resource "google_workstations_workstation_cluster" "{{$.PrimaryResourceId}}" { + workstation_cluster_id = "{{index $.Vars "cluster_id"}}" + network = google_compute_network.default.id + subnetwork = google_compute_subnetwork.default.id + location = "us-central1" + + workstation_authorization_url = "https://workstations.cloud.google.com/ui/auth" + workstation_launch_url = "https://console.cloud.google.com/workstations/launch" +} + +data "google_project" "project" { +} + +resource "google_compute_network" "default" { + name = "{{index $.ResourceIdVars "cluster_network_name"}}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "default" { + name = "{{index $.ResourceIdVars "cluster_network_name"}}" + ip_cidr_range = "10.0.0.0/24" + region = "us-central1" + network = google_compute_network.default.name +} diff --git a/mmv1/templates/terraform/test_check_destroy/dialogflow_conversation_profile.go.tmpl b/mmv1/templates/terraform/test_check_destroy/dialogflow_conversation_profile.go.tmpl new file mode 100644 index 000000000000..83e85969aead --- /dev/null +++ b/mmv1/templates/terraform/test_check_destroy/dialogflow_conversation_profile.go.tmpl @@ -0,0 +1,35 @@ +config := acctest.GoogleProviderConfig(t) +url, err := tpgresource.ReplaceVarsForTest(config, rs, fmt.Sprintf("%s%s", transport_tpg.BaseUrl(dialogflow.Product, config), "{{"{{"}}name{{"}}"}}")) +if err != nil { + return err +} + +billingProject := "" + +if config.BillingProject != "" { + billingProject = config.BillingProject +} + +location := rs.Primary.Attributes["location"] +universeDomain := config.UniverseDomain + +if universeDomain != "" && universeDomain != "googleapis.com" { + url = strings.Replace(url, "googleapis.com", universeDomain, 1) +} + +if strings.HasPrefix(url, "https://dialogflow") { + if location != "" && location != "global" { + url = strings.Replace(url, "https://dialogflow", fmt.Sprintf("https://%s-dialogflow", location), 1) + } +} + +_, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, +}) +if err == nil { + return fmt.Errorf("DialogflowConversationProfile still exists at %s", url) +} diff --git a/mmv1/templates/tgc_next/cai2hcl/flatten_property_method_tgc.go.tmpl b/mmv1/templates/tgc_next/cai2hcl/flatten_property_method_tgc.go.tmpl index d6ee76f73fb0..4504253dc754 100644 --- a/mmv1/templates/tgc_next/cai2hcl/flatten_property_method_tgc.go.tmpl +++ b/mmv1/templates/tgc_next/cai2hcl/flatten_property_method_tgc.go.tmpl @@ -12,25 +12,198 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ -}} -{{- define "flattenTgcPropertyMethod" }} - {{- if $.CustomTgcFlatten }} -{{ customTemplate $ $.CustomTgcFlatten true -}} - {{- else if $.IsA "KeyValueLabels" }} +{{define "flattenTgcPropertyMethod" }} + {{ if $.CustomTgcFlatten }} +{{ customTemplate $ $.CustomTgcFlatten true }} + {{ else if $.IsA "KeyValueLabels" }} func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { return tgcresource.RemoveTerraformAttributionLabel(v) } - {{- else if $.IsA "KeyValueAnnotations" }} + {{ else if $.IsA "KeyValueAnnotations" }} func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { return v } - {{- else if or (and (eq $.Name "zone") $.ResourceMetadata.HasZone) (and (eq $.Name "region") $.ResourceMetadata.HasRegion) -}} + {{ else if or (and (eq $.Name "zone") $.ResourceMetadata.HasZone) (and (eq $.Name "region") $.ResourceMetadata.HasRegion) }} func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { if v == nil { return v } return tpgresource.GetResourceNameFromSelfLink(v.(string)) } - {{- else }} -{{ template "flattenPropertyMethod" $ -}} - {{- end }} -{{- end }} \ No newline at end of file + {{ else }} + {{ if and (or $.WriteOnlyLegacy $.WriteOnly) }} + {{ else if and $.CustomFlatten (not $.ShouldIgnoreCustomFlatten) }} + {{- customTemplate $ $.CustomFlatten false }} + {{ else }} +func flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + {{- if $.IsA "NestedObject" }} + {{- if and $.HasRequiredProperty $.FlattenObject }} + {{- if $.UserProperties }} + original := make(map[string]interface{}, 0) + if v != nil { + original = v.(map[string]interface{}) + } + {{- end }} + {{- else }} + if v == nil { + return nil + } + {{- if $.UserProperties }} + original := v.(map[string]interface{}) + {{- end }} + {{- end }} + transformed := make(map[string]interface{}) + {{- range $prop := $.UserProperties }} + {{- if or $prop.WriteOnlyLegacy $prop.WriteOnly }} + {{- else if $prop.FlattenObject }} + if {{ $prop.ApiName }} := flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config); {{ $prop.ApiName }} != nil { + obj := {{ $prop.ApiName }}.([]interface{})[0] + for k, v := range obj.(map[string]interface{}) { + transformed[k] = v + } + } + {{- else }} + transformed["{{ underscore $prop.Name }}"] = + flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config) + {{- end }} + {{- end }}{{/* range $prop := $.UserProperties */}} + {{- if not $.AllowEmptyObject }} + if tgcresource.AllValuesAreNil(transformed) { + return nil + } + {{- end }} + return []interface{}{transformed} + {{- else if and ($.IsA "Array") ($.ItemType.IsA "NestedObject") }} + if v == nil { + return v + } + l := v.([]interface{}) + {{- if $.IsSet }} + {{- if $.SetHashFunc }} + transformed := schema.NewSet({{ $.SetHashFunc }}, []interface{}{}) + {{- else }} + transformed := schema.NewSet(schema.HashResource({{ $.NamespaceProperty }}Schema()), []interface{}{}) + {{- end }} + {{- else }} + transformed := make([]interface{}, 0, len(l)) + {{- end }} + for _, raw := range l { + original := raw.(map[string]interface{}) + if len(original) < 1 { + // Do not include empty json objects coming back from the api + continue + } + {{- if $.IsSet }} + transformed.Add(map[string]interface{}{ + {{- else }} + transformed = append(transformed, map[string]interface{}{ + {{- end }} + + {{- range $prop := $.ItemType.UserProperties }} + {{- if not (or $prop.IgnoreRead $prop.WriteOnlyLegacy $prop.WriteOnly) }} + "{{ underscore $prop.Name }}": flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config), + {{- end }} + {{- end }} + }) + } + return transformed + {{- else if $.IsA "Map" }} + if v == nil { + return v + } + l := v.(map[string]interface{}) + transformed := make([]interface{}, 0, len(l)) + for k, raw := range l { + original := raw.(map[string]interface{}) + transformed = append(transformed, map[string]interface{}{ + "{{ $.KeyName }}": k, + {{- range $prop := $.ValueType.UserProperties }} + "{{ underscore $prop.Name }}": flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}{{$prop.TitlelizeProperty}}(original["{{ $prop.ApiName }}"], d, config), + {{- end }} + }) + } + return transformed + {{- else if or ($.IsA "KeyValueLabels") (or ($.IsA "KeyValueAnnotations") ($.IsA "KeyValueTerraformLabels")) }} + if v == nil { + return v + } + + transformed := make(map[string]interface{}) + if l, ok := d.GetOkExists("{{ join $.Lineage ".0." }}"); ok { + for k := range l.(map[string]interface{}) { + transformed[k] = v.(map[string]interface{})[k] + } + } + + return transformed + {{- else if $.IsA "Integer" }} + // Handles the string fixed64 format + if strVal, ok := v.(string); ok { + if intVal, err := tpgresource.StringToFixed64(strVal); err == nil { + return intVal + } + } + + // number values are represented as float64 + if floatVal, ok := v.(float64); ok { + intVal := int(floatVal) + return intVal + } + + {{- if $.Required }} + if v == nil { + return 0 + } + {{- end }} + + return v // let terraform core handle it otherwise + {{- else if and ($.IsA "Array") ($.ItemType.IsA "ResourceRef")}} + if v == nil { + return v + } + return tpgresource.ConvertAndMapStringArr(v.([]interface{}), tpgresource.ConvertSelfLinkToV1) + {{- else if $.IsA "ResourceRef" }} + {{- template "fullToRelativePath" $ }} + {{- else if $.IsSet }} + if v == nil { + return v + } + {{- if $.SetHashFunc }} + return schema.NewSet({{- $.SetHashFunc }}, v.([]interface{})) + {{- else if or ($.ItemType.IsA "String") ($.ItemType.IsA "Enum") }} + return schema.NewSet(schema.HashString, v.([]interface{})) + {{- end }} + {{- else if and ($.IsA "Boolean") ($.Required) }} + if v == nil { + return false + } + return v + {{- else if and ($.IsA "String") ($.Required) }} + if v == nil { + return "unknown" + } + transformed := v.(string) + if transformed == "" { + return "unknown" + } + return v + {{- else if and ($.IsA "String") (not $.Required) (not $.DefaultFromApi) (eq $.DefaultValue nil) (not $.SendEmptyValue) }} + if v == nil { + return nil + } + if strVal, ok := v.(string); ok && strVal == "" { + return nil + } + return v + {{- else }} + return v +{{- end }} +} +{{ if $.NestedProperties }} + {{ range $prop := $.NestedProperties }} + {{ template "flattenTgcPropertyMethod" $prop }} + {{ end }} +{{ end }} + {{ end }} + {{ end }} +{{ end }} \ No newline at end of file diff --git a/mmv1/templates/tgc_next/cai2hcl/resource_converter.go.tmpl b/mmv1/templates/tgc_next/cai2hcl/resource_converter.go.tmpl index 59a56472b53b..726073f24832 100644 --- a/mmv1/templates/tgc_next/cai2hcl/resource_converter.go.tmpl +++ b/mmv1/templates/tgc_next/cai2hcl/resource_converter.go.tmpl @@ -171,8 +171,8 @@ func (c *{{ $.ResourceName -}}Cai2hclConverter) convertResourceData(asset caiass } {{ range $prop := $.ReadPropertiesForTgc }} -{{- template "flattenTgcPropertyMethod" $prop -}} -{{- end }} +{{ template "flattenTgcPropertyMethod" $prop }} +{{ end }} {{- if $.CustomCode.TgcDecoder }} func resource{{ $.ResourceName -}}TgcDecoder(d *schema.ResourceData, meta interface{}, res map[string]interface{}, hclData map[string]interface{}) (map[string]interface{}, map[string]interface{}, error) { diff --git a/mmv1/templates/tgc_next/decoders/datastream_private_connection.go.tmpl b/mmv1/templates/tgc_next/decoders/datastream_private_connection.go.tmpl new file mode 100644 index 000000000000..8b9953f425bd --- /dev/null +++ b/mmv1/templates/tgc_next/decoders/datastream_private_connection.go.tmpl @@ -0,0 +1,10 @@ +if _, ok := res["pscInterfaceConfig"]; !ok { + if _, ok := res["vpcPeeringConfig"]; !ok { + // Both are missing! Inject one to satisfy schema. + // We default to pscInterfaceConfig as that's what the failing test intends. + res["pscInterfaceConfig"] = map[string]interface{}{ + "networkAttachment": "unknown", + } + } +} +return res, hclData, nil diff --git a/mmv1/third_party/terraform/.teamcity/components/constants.kt b/mmv1/third_party/terraform/.teamcity/components/constants.kt index 940181ade746..ca3115bf3bd5 100644 --- a/mmv1/third_party/terraform/.teamcity/components/constants.kt +++ b/mmv1/third_party/terraform/.teamcity/components/constants.kt @@ -30,7 +30,7 @@ const val DefaultDaysOfMonth = "*" const val DefaultBranchName = "refs/heads/nightly-test" // Value used to make long-running builds fail due to a timeout -const val DefaultBuildTimeoutDuration = 60 * 15 // 15 hours in minutes +const val DefaultBuildTimeoutDuration = 60 * 18 // 18 hours in minutes // Values used to define and reference Shared Resource locks, used to avoid conflicting builds const val SharedResourceNameGa = "ci-test-project-nightly-ga Service Lock" @@ -50,4 +50,4 @@ const val VcrRecordingProjectId = "VCRRecording" // Artifact rules controls which artifacts are uploaded to S3 // https://www.jetbrains.com/help/teamcity/2024.07/configuring-general-settings.html#Artifact+Paths // The value below lacks a file extension, to allow upload of individual .txt files or a single .tar.gz file -const val ArtifactRules = "%teamcity.build.checkoutDir%/debug*" \ No newline at end of file +const val ArtifactRules = "%teamcity.build.checkoutDir%/debug*" diff --git a/mmv1/third_party/terraform/.teamcity/components/inputs/services_beta.kt b/mmv1/third_party/terraform/.teamcity/components/inputs/services_beta.kt index 9096ed1707fe..dc7cf1501881 100644 --- a/mmv1/third_party/terraform/.teamcity/components/inputs/services_beta.kt +++ b/mmv1/third_party/terraform/.teamcity/components/inputs/services_beta.kt @@ -256,6 +256,11 @@ var ServicesListBeta = mapOf( "displayName" to "Compute", "path" to "./google-beta/services/compute" ), + "config" to mapOf( + "name" to "config", + "displayName" to "Config", + "path" to "./google-beta/services/config" + ), "contactcenterinsights" to mapOf( "name" to "contactcenterinsights", "displayName" to "Contact Center AI Insights", diff --git a/mmv1/third_party/terraform/.teamcity/components/inputs/services_ga.kt b/mmv1/third_party/terraform/.teamcity/components/inputs/services_ga.kt index 91c8d7f9649a..5a854746f0f6 100644 --- a/mmv1/third_party/terraform/.teamcity/components/inputs/services_ga.kt +++ b/mmv1/third_party/terraform/.teamcity/components/inputs/services_ga.kt @@ -256,6 +256,11 @@ var ServicesListGa = mapOf( "displayName" to "Compute", "path" to "./google/services/compute" ), + "config" to mapOf( + "name" to "config", + "displayName" to "Config", + "path" to "./google/services/config" + ), "contactcenterinsights" to mapOf( "name" to "contactcenterinsights", "displayName" to "Contact Center AI Insights", diff --git a/mmv1/third_party/terraform/acctest/bootstrap_test_utils.go.tmpl b/mmv1/third_party/terraform/acctest/bootstrap_test_utils.go.tmpl deleted file mode 100644 index eb91f6a69900..000000000000 --- a/mmv1/third_party/terraform/acctest/bootstrap_test_utils.go.tmpl +++ /dev/null @@ -1,1581 +0,0 @@ -package acctest - -import ( - "context" - "fmt" - "log" - "maps" - "strings" - "testing" - "time" - - resourceManagerV3 "google.golang.org/api/cloudresourcemanager/v3" - "github.com/hashicorp/terraform-provider-google/google/services/kms" - "github.com/hashicorp/terraform-provider-google/google/envvar" - "github.com/hashicorp/terraform-provider-google/google/services/activedirectory" - backupdr_tpg "github.com/hashicorp/terraform-provider-google/google/services/backupdr" - tpgcloudbilling "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" - tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" - "github.com/hashicorp/terraform-provider-google/google/services/iambeta" - "github.com/hashicorp/terraform-provider-google/google/services/privateca" - "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" - rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" - "github.com/hashicorp/terraform-provider-google/google/services/resourcemanagerv3" - tpgservicenetworking "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" - tpgserviceusage "github.com/hashicorp/terraform-provider-google/google/services/serviceusage" - "github.com/hashicorp/terraform-provider-google/google/services/sql" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - - "google.golang.org/api/cloudbilling/v1" - cloudkms "google.golang.org/api/cloudkms/v1" - cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1" - iam "google.golang.org/api/iam/v1" - "google.golang.org/api/servicenetworking/v1" - sqladmin "google.golang.org/api/sqladmin/v1beta4" - backupdr "google.golang.org/api/backupdr/v1" -) - -var SharedKeyRing = "tftest-shared-keyring-1" - -var DefaultKeyHandleName = "eed58b7b-20ad-4da8-ad85-ba78a0d5ab87" -var DefaultKeyHandleResourceType = "compute.googleapis.com/Disk" -var CloudKmsSrviceName = "cloudkms.googleapis.com" - -var SharedCryptoKey = map[string]string{ - "ENCRYPT_DECRYPT": "tftest-shared-key-1", - "ASYMMETRIC_SIGN": "tftest-shared-sign-key-1", - "ASYMMETRIC_DECRYPT": "tftest-shared-decrypt-key-1", -} - -type BootstrappedKMS struct { - *cloudkms.KeyRing - *cloudkms.CryptoKey - CryptoKeyVersions []*cloudkms.CryptoKeyVersion -} - -func BootstrapKMSKey(t *testing.T) BootstrappedKMS { - return BootstrapKMSKeyInLocation(t, "global") -} - -func BootstrapKMSKeyInLocation(t *testing.T, locationID string) BootstrappedKMS { - return BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", locationID) -} - -// BootstrapKMSKeyWithPurpose returns a KMS key in the "global" location. -// See BootstrapKMSKeyWithPurposeInLocation. -func BootstrapKMSKeyWithPurpose(t *testing.T, purpose string) BootstrappedKMS { - return BootstrapKMSKeyWithPurposeInLocation(t, purpose, "global") -} - -/** -* BootstrapKMSKeyWithPurposeInLocation will return a KMS key in a -* particular location with the given purpose that can be used -* in tests that are testing KMS integration with other resources. -* -* This will either return an existing key or create one if it hasn't been created -* in the project yet. The motivation is because keyrings don't get deleted and we -* don't want a linear growth of disabled keyrings in a project. We also don't want -* to incur the overhead of creating a new project for each test that needs to use -* a KMS key. -**/ -func BootstrapKMSKeyWithPurposeInLocation(t *testing.T, purpose, locationID string) BootstrappedKMS { - return BootstrapKMSKeyWithPurposeInLocationAndName(t, purpose, locationID, SharedCryptoKey[purpose]) -} - -type BootstrappedKMSAutokey struct { - *cloudkms.AutokeyConfig - *cloudkms.KeyHandle -} - -func BootstrapKMSAutokeyKeyHandle(t *testing.T) BootstrappedKMSAutokey { - return BootstrapKMSAutokeyKeyHandleWithLocation(t, "global") -} - -func BootstrapKMSAutokeyKeyHandleWithLocation(t *testing.T, locationID string) BootstrappedKMSAutokey { - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return BootstrappedKMSAutokey{ - &cloudkms.AutokeyConfig{}, - &cloudkms.KeyHandle{}, - } - } - - autokeyFolder, kmsProject, resourceProject := setupAutokeyTestResources(t, config) - - // Enable autokey on autokey test folder - kmsClient := kms.NewClient(config, config.UserAgent) - autokeyConfigID := fmt.Sprintf("%s/autokeyConfig", autokeyFolder.Name) - autokeyConfig, err := kmsClient.Folders.UpdateAutokeyConfig(autokeyConfigID, &cloudkms.AutokeyConfig{ - KeyProject: fmt.Sprintf("projects/%s", kmsProject.ProjectId), - }).UpdateMask("keyProject").Do() - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot enable autokey on autokey test folder: %s", err) - } - - keyHandleParent := fmt.Sprintf("projects/%s/locations/%s", resourceProject.ProjectId, locationID) - keyHandleName := fmt.Sprintf("%s/keyHandles/%s", keyHandleParent, DefaultKeyHandleName) - - // Get or Create the hard coded keyHandle for testing - keyHandle, err := kmsClient.Projects.Locations.KeyHandles.Get(keyHandleName).Do() - - if err != nil { - if transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - newKeyHandle := cloudkms.KeyHandle{ - ResourceTypeSelector: DefaultKeyHandleResourceType, - } - - keyHandleOp, err := kmsClient.Projects.Locations.KeyHandles.Create(keyHandleParent, &newKeyHandle).KeyHandleId(DefaultKeyHandleName).Do() - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot create new KeyHandle: %s", err) - } - - opAsMap, err := tpgresource.ConvertToMap(keyHandleOp) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot get operation map: %s", err) - } - - var response map[string]interface{} - err = kms.KMSOperationWaitTimeWithResponse(config, opAsMap, &response, resourceProject.ProjectId, "creating keyHandle", config.UserAgent, time.Duration(5)*time.Minute) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot wait for create keyhandle operation: %s", err) - } - keyHandle = &cloudkms.KeyHandle{ - Name: response["name"].(string), - KmsKey: response["kmsKey"].(string), - ResourceTypeSelector: response["resourceTypeSelector"].(string), - } - } else { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot call KeyHandle service: %s", err) - } - } - - if keyHandle == nil { - t.Fatalf("unable to bootstrap KMS keyHandle. KeyHandle is nil!") - } - - return BootstrappedKMSAutokey{ - autokeyConfig, - keyHandle, - } -} - -func setupAutokeyTestResources(t *testing.T, config *transport_tpg.Config) (*resourceManagerV3.Folder, *cloudresourcemanager.Project, *cloudresourcemanager.Project) { - projectIDSuffix := strings.Replace(envvar.GetTestProjectFromEnv(), "ci-test-project-", "", 1) - defaultAutokeyTestFolderName := fmt.Sprintf("autokeytest-%s-fd", projectIDSuffix) - defaultAutokeyTestKmsProject := fmt.Sprintf("test-kms-%s-prj", projectIDSuffix) - defaultAutokeyTestResourceProject := fmt.Sprintf("test-res-%s-prj", projectIDSuffix) - - curUserEmail, err := transport_tpg.GetCurrentUserEmail(config, config.UserAgent) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot get current usr: %s", err) - } - // create a folder to configure autokey config and resource folder - autokeyFolder := BootstrapFolder(t, defaultAutokeyTestFolderName) - parent := &cloudresourcemanager.ResourceId{ - Type: "folder", - Id: strings.Split(autokeyFolder.Name, "/")[1], - } - // create and setup kms project for hosting keyring and keys for autokey - kmsProject := BootstrapProjectWithParent(t, defaultAutokeyTestKmsProject, envvar.GetTestBillingAccountFromEnv(t), parent, []string{CloudKmsSrviceName}) - kmsProjectID := fmt.Sprintf("projects/%s", kmsProject.ProjectId) - kmsSAEmail, err := GenerateCloudKmsServiceIdentity(config, fmt.Sprintf("%v", kmsProject.ProjectNumber)) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot create cloudkms service identity: %s", err) - } - err = addFolderBinding2(resourcemanagerv3.NewClient(config, config.UserAgent), autokeyFolder.Name, fmt.Sprintf("user:%s", curUserEmail), []string{"roles/cloudkms.admin"}) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot assign cloudkms.admin role to current user on autokey test folder: %s", err) - } - err = addProjectBinding(resourcemanagerv3.NewClient(config, config.UserAgent), kmsProjectID, fmt.Sprintf("user:%s", curUserEmail), []string{"roles/resourcemanager.projectIamAdmin", "roles/cloudkms.admin"}) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot assign cloudkms.admin and projectIamAdmin role to current user on kms project: %s", err) - } - err = addProjectBinding(resourcemanagerv3.NewClient(config, config.UserAgent), kmsProjectID, fmt.Sprintf("serviceAccount:%s", kmsSAEmail), []string{"roles/cloudkms.admin"}) - if err != nil { - t.Errorf("unable to bootstrap KMS keyHandle. Cannot assign cloudkms.admin role to cloudkms service identity on kms project: %s", err) - } - - // create and setup resource folder to host keyhandle - resourceProject := BootstrapProjectWithParent(t, defaultAutokeyTestResourceProject, envvar.GetTestBillingAccountFromEnv(t), parent, []string{}) - return autokeyFolder, kmsProject, resourceProject -} - -// GenerateCloudKmsServiceIdentity generates cloud kms service identity within a project -func GenerateCloudKmsServiceIdentity(config *transport_tpg.Config, projectNum string) (string, error) { - url := fmt.Sprintf("https://serviceusage.googleapis.com/v1beta1/projects/%s/services/%s:generateServiceIdentity", projectNum, CloudKmsSrviceName) - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: projectNum, - RawURL: url, - UserAgent: config.UserAgent, - Timeout: time.Minute * 4, - }) - if err != nil { - return "", fmt.Errorf("error creating cloudkms service identity: %s", err) - } - - var opRes map[string]interface{} - err = tpgserviceusage.ServiceUsageOperationWaitTimeWithResponse( - config, res, &opRes, projectNum, "Creating cloudkms service identity", config.UserAgent, - time.Minute*4) - if err != nil { - return "", err - } - return fmt.Sprintf("service-%s@gcp-sa-cloudkms.iam.gserviceaccount.com", projectNum), nil -} - -func addProjectBinding(crmService *resourceManagerV3.Service, projectID string, member string, roles []string) error { - return addBinding(crmService, "project", projectID, member, roles) -} - -func addFolderBinding2(crmService *resourceManagerV3.Service, folderID string, member string, roles []string) error { - return addBinding(crmService, "folder", folderID, member, roles) -} - -// addBinding adds the member to the project's IAM policy -func addBinding(crmService *resourceManagerV3.Service, resourceType string, resourceID string, member string, roles []string) error { - - policy, err := getPolicy(crmService, resourceType, resourceID) - if err != nil { - return err - } - - // Find the policy binding for role. Only one binding can have the role. - var binding *resourceManagerV3.Binding - for _, role := range roles { - for _, b := range policy.Bindings { - if b.Role == role { - binding = b - break - } - } - - if binding != nil { - // If the binding exists, adds the member to the binding - binding.Members = append(binding.Members, member) - } else { - // If the binding does not exist, adds a new binding to the policy - binding = &resourceManagerV3.Binding{ - Role: role, - Members: []string{member}, - } - policy.Bindings = append(policy.Bindings, binding) - } - } - setPolicy(crmService, resourceType, resourceID, policy) - return nil -} - -// getPolicy gets the IAM policy on input resourceID -// resourceType can be "project" or "folder" -func getPolicy(crmService *resourceManagerV3.Service, resourceType string, resourceID string) (*resourceManagerV3.Policy, error) { - - ctx := context.Background() - - ctx, cancel := context.WithTimeout(ctx, time.Second*10) - defer cancel() - request := new(resourceManagerV3.GetIamPolicyRequest) - var policy *resourceManagerV3.Policy - var err error - if resourceType == "project" { - policy, err = crmService.Projects.GetIamPolicy(resourceID, request).Do() - } else if resourceType == "folder" { - policy, err = crmService.Folders.GetIamPolicy(resourceID, request).Do() - } else { - return nil, fmt.Errorf("invalid resourceType, supported values: project or folder") - } - if err != nil { - return nil, fmt.Errorf("error getting iam policy: %s", err) - } - return policy, nil -} - -// setPolicy sets the IAM policy on input resourceID -// resourceType can be "project" or "folder" -func setPolicy(crmService *resourceManagerV3.Service, resourceType string, resourceID string, policy *resourceManagerV3.Policy) error { - - ctx := context.Background() - - ctx, cancel := context.WithTimeout(ctx, time.Second*10) - defer cancel() - request := new(resourceManagerV3.SetIamPolicyRequest) - request.Policy = policy - var err error - if resourceType == "project" { - _, err = crmService.Projects.SetIamPolicy(resourceID, request).Do() - } else if resourceType == "folder" { - _, err = crmService.Folders.SetIamPolicy(resourceID, request).Do() - } else { - return fmt.Errorf("invalid resourceType, supported values: project or folder") - } - if err != nil { - return fmt.Errorf("error setting iam policy: %s", err) - } - return nil -} - -func BootstrapKMSKeyWithPurposeInLocationAndName(t *testing.T, purpose, locationID, keyShortName string) BootstrappedKMS { - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return BootstrappedKMS{ - &cloudkms.KeyRing{}, - &cloudkms.CryptoKey{}, - nil, - } - } - - projectID := envvar.GetTestProjectFromEnv() - keyRingParent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) - keyRingName := fmt.Sprintf("%s/keyRings/%s", keyRingParent, SharedKeyRing) - keyParent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s", projectID, locationID, SharedKeyRing) - keyName := fmt.Sprintf("%s/cryptoKeys/%s", keyParent, keyShortName) - - // Get or Create the hard coded shared keyring for testing - kmsClient := kms.NewClient(config, config.UserAgent) - keyRing, err := kmsClient.Projects.Locations.KeyRings.Get(keyRingName).Do() - if err != nil { - if transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - keyRing, err = kmsClient.Projects.Locations.KeyRings.Create(keyRingParent, &cloudkms.KeyRing{}). - KeyRingId(SharedKeyRing).Do() - if err != nil { - t.Errorf("Unable to bootstrap KMS key. Cannot create keyRing: %s", err) - } - } else { - t.Errorf("Unable to bootstrap KMS key. Cannot retrieve keyRing: %s", err) - } - } - - if keyRing == nil { - t.Fatalf("Unable to bootstrap KMS key. keyRing is nil!") - } - - // Get or Create the hard coded, shared crypto key for testing - cryptoKey, err := kmsClient.Projects.Locations.KeyRings.CryptoKeys.Get(keyName).Do() - if err != nil { - if transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - algos := map[string]string{ - "ENCRYPT_DECRYPT": "GOOGLE_SYMMETRIC_ENCRYPTION", - "ASYMMETRIC_SIGN": "RSA_SIGN_PKCS1_4096_SHA256", - "ASYMMETRIC_DECRYPT": "RSA_DECRYPT_OAEP_4096_SHA256", - } - template := cloudkms.CryptoKeyVersionTemplate{ - Algorithm: algos[purpose], - } - - newKey := cloudkms.CryptoKey{ - Purpose: purpose, - VersionTemplate: &template, - } - - cryptoKey, err = kmsClient.Projects.Locations.KeyRings.CryptoKeys.Create(keyParent, &newKey). - CryptoKeyId(keyShortName).Do() - if err != nil { - t.Errorf("Unable to bootstrap KMS key. Cannot create new CryptoKey: %s", err) - } - - } else { - t.Errorf("Unable to bootstrap KMS key. Cannot call CryptoKey service: %s", err) - } - } - - if cryptoKey == nil { - t.Fatalf("Unable to bootstrap KMS key. CryptoKey is nil!") - } - - // TODO: b/372305432 Use the pagination properly. - ckvResp, err := kmsClient.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.List(keyName).Do() - if err != nil { - t.Fatalf("Unable to list cryptoKeyVersions: %v", err) - } - - return BootstrappedKMS{ - keyRing, - cryptoKey, - ckvResp.CryptoKeyVersions, - } -} - -var serviceAccountPrefix = "tf-bootstrap-sa-" -var serviceAccountDisplay = "Bootstrapped Service Account for Terraform tests" - -// Some tests need a second service account, other than the test runner, to assert functionality on. -// This provides a well-known service account that can be used when dynamically creating a service -// account isn't an option. -func getOrCreateServiceAccount(config *transport_tpg.Config, project, serviceAccountEmail string) (*iam.ServiceAccount, error) { - name := fmt.Sprintf("projects/%s/serviceAccounts/%s@%s.iam.gserviceaccount.com", project, serviceAccountEmail, project) - log.Printf("[DEBUG] Verifying %s as bootstrapped service account.\n", name) - - sa, err := iambeta.NewClient(config, config.UserAgent).Projects.ServiceAccounts.Get(name).Do() - if err != nil && !transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - return nil, fmt.Errorf("encountered a non-404 error when looking for bootstrapped service account %s: %w", name, err) - } - - if sa == nil { - log.Printf("[DEBUG] Account missing. Creating %s as bootstrapped service account.\n", name) - sa = &iam.ServiceAccount{ - DisplayName: serviceAccountDisplay, - } - - r := &iam.CreateServiceAccountRequest{ - AccountId: serviceAccountEmail, - ServiceAccount: sa, - } - sa, err = iambeta.NewClient(config, config.UserAgent).Projects.ServiceAccounts.Create("projects/"+project, r).Do() - if err != nil { - return nil, fmt.Errorf("error when creating bootstrapped service account %s: %w", name, err) - } - } - - return sa, nil -} - -// In order to test impersonation we need to grant the testRunner's account the ability to grant tokens -// on a different service account. Granting permissions takes time and there is no operation to wait on -// so instead this creates a single service account once per test-suite with the correct permissions. -// The first time this test is run it will fail, but subsequent runs will succeed. -func impersonationServiceAccountPermissions(config *transport_tpg.Config, sa *iam.ServiceAccount, testRunner string) error { - log.Printf("[DEBUG] Setting service account permissions.\n") - policy := iam.Policy{ - Bindings: []*iam.Binding{}, - } - - binding := &iam.Binding{ - Role: "roles/iam.serviceAccountTokenCreator", - Members: []string{"serviceAccount:" + sa.Email, "serviceAccount:" + testRunner}, - } - policy.Bindings = append(policy.Bindings, binding) - - // Overwrite the roles each time on this service account. This is because this account is - // only created for the test suite and will stop snowflaking of permissions to get tests - // to run. Overwriting permissions on 1 service account shouldn't affect others. - _, err := iambeta.NewClient(config, config.UserAgent).Projects.ServiceAccounts.SetIamPolicy(sa.Name, &iam.SetIamPolicyRequest{ - Policy: &policy, - }).Do() - if err != nil { - return err - } - - return nil -} - -// A separate testId should be used for each test, to create separate service accounts for each, -// and avoid race conditions where the policy of the same service account is being modified by 2 -// tests at once. This is needed as long as the function overwrites the policy on every run. -func BootstrapServiceAccount(t *testing.T, testId, testRunner string) string { - project := envvar.GetTestProjectFromEnv() - serviceAccountEmail := serviceAccountPrefix + testId - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - sa, err := getOrCreateServiceAccount(config, project, serviceAccountEmail) - if err != nil { - t.Fatalf("Bootstrapping failed. Cannot retrieve service account, %s", err) - } - - err = impersonationServiceAccountPermissions(config, sa, testRunner) - if err != nil { - t.Fatalf("Bootstrapping failed. Cannot set service account permissions, %s", err) - } - - return sa.Email -} - -const SharedTestADDomainPrefix = "tf-bootstrap-ad" - -func BootstrapSharedTestADDomain(t *testing.T, testId string, networkName string) string { - project := envvar.GetTestProjectFromEnv() - sharedADDomain := fmt.Sprintf("%s.%s.com", SharedTestADDomainPrefix, testId) - adDomainName := fmt.Sprintf("projects/%s/locations/global/domains/%s", project, sharedADDomain) - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - log.Printf("[DEBUG] Getting shared test active directory domain %q", adDomainName) - getURL := fmt.Sprintf("%s%s", transport_tpg.BaseUrl(activedirectory.Product, config), adDomainName) - _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "GET", - Project: project, - RawURL: getURL, - UserAgent: config.UserAgent, - Timeout: 4 * time.Minute, - }) - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] AD domain %q not found, bootstrapping", sharedADDomain) - postURL := fmt.Sprintf("%sprojects/%s/locations/global/domains?domainName=%s", transport_tpg.BaseUrl(activedirectory.Product, config), project, sharedADDomain) - domainObj := map[string]interface{}{ - "locations": []string{"us-central1"}, - "reservedIpRange": "10.0.1.0/24", - "authorizedNetworks": []string{fmt.Sprintf("projects/%s/global/networks/%s", project, networkName)}, - } - - _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: project, - RawURL: postURL, - UserAgent: config.UserAgent, - Body: domainObj, - Timeout: 60 * time.Minute, - }) - if err != nil { - t.Fatalf("Error bootstrapping shared active directory domain %q: %s", adDomainName, err) - } - - log.Printf("[DEBUG] Waiting for active directory domain creation to finish") - } - - _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "GET", - Project: project, - RawURL: getURL, - UserAgent: config.UserAgent, - Timeout: 4 * time.Minute, - }) - - if err != nil { - t.Fatalf("Error getting shared active directory domain %q: %s", adDomainName, err) - } - - return sharedADDomain -} - -const SharedTestNetworkPrefix = "tf-bootstrap-net-" - -// BootstrapSharedTestNetwork will return a persistent compute network for a -// test or set of tests. -// -// Usage 1 -// Resources like service_networking_connection use a consumer network and -// create a complementing tenant network which we don't control. These tenant -// networks never get cleaned up and they can accumulate to the point where a -// limit is reached for the organization. By reusing a consumer network across -// test runs, we can reduce the number of tenant networks that are needed. -// See b/146351146 for more context. -// -// Usage 2 -// Bootstrap networks used in tests (gke clusters, dataproc clusters...) -// to avoid traffic to the default network -// -// testId specifies the test for which a shared network is used/initialized. -// Note that if the network is being used for a service_networking_connection, -// the same testId should generally not be used across tests, to avoid race -// conditions where multiple tests attempt to modify the connection at once. -// -// Returns the name of a network, creating it if it hasn't been created in the -// test project. -func BootstrapSharedTestNetwork(t *testing.T, testId string) string { - project := envvar.GetTestProjectFromEnv() - networkName := SharedTestNetworkPrefix + testId - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - log.Printf("[DEBUG] Getting shared test network %q", networkName) - _, err := tpgcompute.NewClient(config, config.UserAgent).Networks.Get(project, networkName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] Network %q not found, bootstrapping", networkName) - url := fmt.Sprintf("%sprojects/%s/global/networks", transport_tpg.BaseUrl(tpgcompute.Product, config), project) - netObj := map[string]interface{}{ - "name": networkName, - "autoCreateSubnetworks": false, - } - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: project, - RawURL: url, - UserAgent: config.UserAgent, - Body: netObj, - Timeout: 4 * time.Minute, - }) - if err != nil { - t.Fatalf("Error bootstrapping shared test network %q: %s", networkName, err) - } - - log.Printf("[DEBUG] Waiting for network creation to finish") - err = tpgcompute.ComputeOperationWaitTime(config, res, project, "Error bootstrapping shared test network", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error bootstrapping shared test network %q: %s", networkName, err) - } - } - - network, err := tpgcompute.NewClient(config, config.UserAgent).Networks.Get(project, networkName).Do() - if err != nil { - t.Errorf("Error getting shared test network %q: %s", networkName, err) - } - if network == nil { - t.Fatalf("Error getting shared test network %q: is nil", networkName) - } - return network.Name -} - -type AddressSettings struct { - PrefixLength int -} - -func AddressWithPrefixLength(prefixLength int) func(*AddressSettings) { - return func(settings *AddressSettings) { - settings.PrefixLength = prefixLength - } -} - -func NewAddressSettings(options ...func(*AddressSettings)) *AddressSettings { - settings := &AddressSettings{ - PrefixLength: 16, // default prefix length - } - - for _, o := range options { - o(settings) - } - return settings -} - -const SharedTestGlobalAddressPrefix = "tf-bootstrap-addr-" - -// params are the functions to set compute global address -func BootstrapSharedTestGlobalAddress(t *testing.T, testId string, params ...func(*AddressSettings)) string { - project := envvar.GetTestProjectFromEnv() - addressName := SharedTestGlobalAddressPrefix + testId - networkName := BootstrapSharedTestNetwork(t, testId) - networkId := fmt.Sprintf("projects/%v/global/networks/%v", project, networkName) - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - log.Printf("[DEBUG] Getting shared test global address %q", addressName) - _, err := tpgcompute.NewClient(config, config.UserAgent).GlobalAddresses.Get(project, addressName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] Global address %q not found, bootstrapping", addressName) - url := fmt.Sprintf("%sprojects/%s/global/addresses", transport_tpg.BaseUrl(tpgcompute.Product, config), project) - - settings := NewAddressSettings(params...) - - netObj := map[string]interface{}{ - "name": addressName, - "address_type": "INTERNAL", - "purpose": "VPC_PEERING", - "prefix_length": settings.PrefixLength, - "network": networkId, - } - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: project, - RawURL: url, - UserAgent: config.UserAgent, - Body: netObj, - Timeout: 4 * time.Minute, - }) - if err != nil { - t.Fatalf("Error bootstrapping shared test global address %q: %s", addressName, err) - } - - log.Printf("[DEBUG] Waiting for global address creation to finish") - err = tpgcompute.ComputeOperationWaitTime(config, res, project, "Error bootstrapping shared test global address", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error bootstrapping shared test global address %q: %s", addressName, err) - } - } - - address, err := tpgcompute.NewClient(config, config.UserAgent).GlobalAddresses.Get(project, addressName).Do() - if err != nil { - t.Errorf("Error getting shared test global address %q: %s", addressName, err) - } - if address == nil { - t.Fatalf("Error getting shared test global address %q: is nil", addressName) - } - return address.Name -} - -type ServiceNetworkSettings struct { - PrefixLength int - ParentService string -} - -func ServiceNetworkWithPrefixLength(prefixLength int) func(*ServiceNetworkSettings) { - return func(settings *ServiceNetworkSettings) { - settings.PrefixLength = prefixLength - } -} - -func ServiceNetworkWithParentService(parentService string) func(*ServiceNetworkSettings) { - return func(settings *ServiceNetworkSettings) { - settings.ParentService = parentService - } -} - -func NewServiceNetworkSettings(options ...func(*ServiceNetworkSettings)) *ServiceNetworkSettings { - settings := &ServiceNetworkSettings{ - PrefixLength: 16, // default prefix length - ParentService: "servicenetworking.googleapis.com", // default parent service - } - - for _, o := range options { - o(settings) - } - return settings -} - -// BootstrapSharedServiceNetworkingConnection will create a shared network -// if it hasn't been created in the test project, a global address -// if it hasn't been created in the test project, and a service networking connection -// if it hasn't been created in the test project. -// -// params are the functions to set compute global address -// -// BootstrapSharedServiceNetworkingConnection returns a persistent compute network name -// for a test or set of tests. -// -// To delete a service networking connection, all of the service instances that use that connection -// must be deleted first. After the service instances are deleted, some service producers delay the deletion -// utnil a waiting period has passed. For example, after four days that you delete a SQL instance, -// the service networking connection can be deleted. -// That is the reason to use the shared service networking connection for test resources. -// https://cloud.google.com/vpc/docs/configure-private-services-access#removing-connection -// -// testId specifies the test for which a shared network and a global address are used/initialized. -func BootstrapSharedServiceNetworkingConnection(t *testing.T, testId string, params ...func(*ServiceNetworkSettings)) string { - settings := NewServiceNetworkSettings(params...) - parentService := "services/" + settings.ParentService - projectId := envvar.GetTestProjectFromEnv() - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - // Get project number by calling the API - crmClient := rmClient.NewClient(config, config.UserAgent) - project, err := crmClient.Projects.Get(projectId).Do() - if err != nil { - t.Fatalf("Error getting project: %s", err) - } - - networkName := SharedTestNetworkPrefix + testId - networkId := fmt.Sprintf("projects/%v/global/networks/%v", project.ProjectNumber, networkName) - globalAddressName := BootstrapSharedTestGlobalAddress(t, testId, AddressWithPrefixLength(settings.PrefixLength)) - - readCall := tpgservicenetworking.NewClient(config, config.UserAgent).Services.Connections.List(parentService).Network(networkId) - if config.UserProjectOverride { - readCall.Header().Add("X-Goog-User-Project", projectId) - } - response, err := readCall.Do() - if err != nil { - t.Errorf("Error getting shared test service networking connection: %s", err) - } - - var connection *servicenetworking.Connection - for _, c := range response.Connections { - if c.Network == networkId { - connection = c - break - } - } - - if connection == nil { - log.Printf("[DEBUG] Service networking connection not found, bootstrapping") - - connection := &servicenetworking.Connection{ - Network: networkId, - ReservedPeeringRanges: []string{globalAddressName}, - } - - createCall := tpgservicenetworking.NewClient(config, config.UserAgent).Services.Connections.Create(parentService, connection) - if config.UserProjectOverride { - createCall.Header().Add("X-Goog-User-Project", projectId) - } - op, err := createCall.Do() - if err != nil { - t.Fatalf("Error bootstrapping shared test service networking connection: %s", err) - } - - log.Printf("[DEBUG] Waiting for service networking connection creation to finish") - if err := tpgservicenetworking.ServiceNetworkingOperationWaitTimeHW(config, op, "Create Service Networking Connection", config.UserAgent, projectId, 4*time.Minute); err != nil { - t.Fatalf("Error bootstrapping shared test service networking connection: %s", err) - } - } - - log.Printf("[DEBUG] Getting shared test service networking connection") - - return networkName -} - -var SharedServicePerimeterProjectPrefix = "tf-bootstrap-sp-" - -func BootstrapServicePerimeterProjects(t *testing.T, desiredProjects int) []*cloudresourcemanager.Project { - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return nil - } - - org := envvar.GetTestOrgFromEnv(t) - - // The filter endpoint works differently if you provide both the parent id and parent type, and - // doesn't seem to allow for prefix matching. Don't change this to include the parent type unless - // that API behavior changes. - prefixFilter := fmt.Sprintf("id:%s* parent.id:%s", SharedServicePerimeterProjectPrefix, org) - res, err := rmClient.NewClient(config, config.UserAgent).Projects.List().Filter(prefixFilter).Do() - if err != nil { - t.Fatalf("Error getting shared test projects: %s", err) - } - - projects := res.Projects - for len(projects) < desiredProjects { - pid := SharedServicePerimeterProjectPrefix + RandString(t, 10) - project := &cloudresourcemanager.Project{ - ProjectId: pid, - Name: "TF Service Perimeter Test", - Parent: &cloudresourcemanager.ResourceId{ - Type: "organization", - Id: org, - }, - } - op, err := rmClient.NewClient(config, config.UserAgent).Projects.Create(project).Do() - if err != nil { - t.Fatalf("Error bootstrapping shared test project: %s", err) - } - - opAsMap, err := tpgresource.ConvertToMap(op) - if err != nil { - t.Fatalf("Error bootstrapping shared test project: %s", err) - } - - err = resourcemanager.ResourceManagerOperationWaitTime(config, opAsMap, "creating project", config.UserAgent, 4) - if err != nil { - t.Fatalf("Error bootstrapping shared test project: %s", err) - } - - p, err := rmClient.NewClient(config, config.UserAgent).Projects.Get(pid).Do() - if err != nil { - t.Fatalf("Error getting shared test project: %s", err) - } - projects = append(projects, p) - } - - return projects -} - -// BootstrapFolder creates or get a folder having a input folderDisplayName within a TestOrgEnv -func BootstrapFolder(t *testing.T, folderDisplayName string) *resourceManagerV3.Folder { - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return nil - } - - crmClient := resourcemanagerv3.NewClient(config, config.UserAgent) - searchQuery := fmt.Sprintf("displayName=%s", folderDisplayName) - folderSearchResp, err := crmClient.Folders.Search().Query(searchQuery).Do() - if err != nil { - t.Fatalf("error searching for folder with displayName: %s", folderDisplayName) - } - var folder *resourceManagerV3.Folder - if len(folderSearchResp.Folders) == 0 { - op, err := crmClient.Folders.Create(&resourceManagerV3.Folder{ - DisplayName: folderDisplayName, - Parent: fmt.Sprintf("organizations/%s", envvar.GetTestOrgFromEnv(t)), - }).Do() - if err != nil { - t.Fatalf("error bootstrapping test folder: %s", err) - } - - opAsMap, err := tpgresource.ConvertToMap(op) - if err != nil { - t.Fatalf("error converting folder operation map: %s", err) - } - var responseMap map[string]interface{} - err = resourcemanager.ResourceManagerOperationWaitTimeWithResponse(config, opAsMap, &responseMap, "creating folder", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("error waiting for create folder operation: %s", err) - } - folder, err = crmClient.Folders.Get(responseMap["name"].(string)).Do() - if err != nil { - t.Fatalf("error getting folder: %s", err) - } - } else { - folder = folderSearchResp.Folders[0] - } - - if folder.State == "DELETE_REQUESTED" { - _, err := crmClient.Folders.Undelete(folder.Name, &resourceManagerV3.UndeleteFolderRequest{}).Do() - if err != nil { - t.Fatalf("error undeleting folder: %s", err) - } - } - return folder -} - -// BootstrapProject will create or get a project named -// "" that will persist across test runs, -// where projectIDSuffix is based off of getTestProjectFromEnv(). The reason -// for the naming is to isolate bootstrapped projects by test environment. -// Given the existing projects being used by our team, the prefix provided to -// this function can be no longer than 18 characters. -func BootstrapProject(t *testing.T, projectIDPrefix, billingAccount string, services []string) *cloudresourcemanager.Project { - org := envvar.GetTestOrgFromEnv(t) - parent := &cloudresourcemanager.ResourceId{ - Type: "organization", - Id: org, - } - projectIDSuffix := strings.Replace(envvar.GetTestProjectFromEnv(), "ci-test-project-", "", 1) - projectID := projectIDPrefix + projectIDSuffix - - return BootstrapProjectWithParent(t, projectID, billingAccount, parent, services) -} - -func BootstrapProjectWithParent(t *testing.T, projectID string, billingAccount string, parent *cloudresourcemanager.ResourceId, services []string) *cloudresourcemanager.Project { - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return nil - } - crmClient := rmClient.NewClient(config, config.UserAgent) - - project, err := crmClient.Projects.Get(projectID).Do() - if err != nil { - if !transport_tpg.IsGoogleApiErrorWithCode(err, 403) { - t.Fatalf("Error getting bootstrapped project: %s", err) - } - op, err := crmClient.Projects.Create(&cloudresourcemanager.Project{ - ProjectId: projectID, - Name: "Bootstrapped Test Project", - Parent: parent, - }).Do() - if err != nil { - t.Fatalf("Error creating bootstrapped test project: %s", err) - } - - opAsMap, err := tpgresource.ConvertToMap(op) - if err != nil { - t.Fatalf("Error converting create project operation to map: %s", err) - } - - err = resourcemanager.ResourceManagerOperationWaitTime(config, opAsMap, "creating project", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error waiting for create project operation: %s", err) - } - - project, err = crmClient.Projects.Get(projectID).Do() - if err != nil { - t.Fatalf("Error getting bootstrapped project: %s", err) - } - - } - - if project.LifecycleState == "DELETE_REQUESTED" { - _, err := crmClient.Projects.Undelete(projectID, &cloudresourcemanager.UndeleteProjectRequest{}).Do() - if err != nil { - t.Fatalf("Error undeleting bootstrapped project: %s", err) - } - } - - if billingAccount != "" { - billingClient := tpgcloudbilling.NewClient(config, config.UserAgent) - var pbi *cloudbilling.ProjectBillingInfo - err = transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: func() error { - var reqErr error - pbi, reqErr = billingClient.Projects.GetBillingInfo(resourcemanager.PrefixedProject(projectID)).Do() - return reqErr - }, - Timeout: 30 * time.Second, - }) - if err != nil { - t.Fatalf("Error getting billing info for project %q: %v", projectID, err) - } - if strings.TrimPrefix(pbi.BillingAccountName, "billingAccounts/") != billingAccount { - pbi.BillingAccountName = "billingAccounts/" + billingAccount - err := transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: func() error { - _, err := tpgcloudbilling.NewClient(config, config.UserAgent).Projects.UpdateBillingInfo(resourcemanager.PrefixedProject(projectID), pbi).Do() - return err - }, - Timeout: 2 * time.Minute, - }) - if err != nil { - t.Fatalf("Error setting billing account for project %q to %q: %s", projectID, billingAccount, err) - } - } - } - - if len(services) > 0 { - - enabledServices, err := resourcemanager.ListCurrentlyEnabledServices(projectID, "", config.UserAgent, config, 1*time.Minute) - if err != nil { - t.Fatalf("Error listing services for project %q: %s", projectID, err) - } - - servicesToEnable := make([]string, 0, len(services)) - for _, service := range services { - if _, ok := enabledServices[service]; !ok { - servicesToEnable = append(servicesToEnable, service) - } - } - - if len(servicesToEnable) > 0 { - if err := resourcemanager.EnableServiceUsageProjectServices(servicesToEnable, projectID, "", config.UserAgent, config, 10*time.Minute); err != nil { - t.Fatalf("Error enabling services for project %q: %s", projectID, err) - } - } - } - - return project -} - -// SQL Instance names are not reusable for a week after deletion -const SharedTestSQLInstanceNamePrefix = "tf-bootstrap-" - -// BootstrapSharedSQLInstanceBackupRun will return a shared SQL db instance that -// has a backup created for it. -func BootstrapSharedSQLInstanceBackupRun(t *testing.T) string { - project := envvar.GetTestProjectFromEnv() - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - log.Printf("[DEBUG] Getting list of existing sql instances") - - instances, err := sql.NewClient(config, config.UserAgent).Instances.List(project).Do() - if err != nil { - t.Fatalf("Unable to bootstrap SQL Instance. Cannot retrieve instance list: %s", err) - } - - var bootstrapInstance *sqladmin.DatabaseInstance - - // Look for any existing bootstrap instances - for _, i := range instances.Items { - if strings.HasPrefix(i.Name, SharedTestSQLInstanceNamePrefix) { - bootstrapInstance = i - break - } - } - - if bootstrapInstance == nil { - bootstrapInstanceName := SharedTestSQLInstanceNamePrefix + RandString(t, 10) - log.Printf("[DEBUG] Bootstrap SQL Instance not found, bootstrapping new instance %s", bootstrapInstanceName) - - backupConfig := &sqladmin.BackupConfiguration{ - Enabled: true, - PointInTimeRecoveryEnabled: true, - } - settings := &sqladmin.Settings{ - Tier: "db-custom-2-3840", - BackupConfiguration: backupConfig, - } - bootstrapInstance = &sqladmin.DatabaseInstance{ - Name: bootstrapInstanceName, - Region: "us-central1", - Settings: settings, - DatabaseVersion: "POSTGRES_11", - } - - var op *sqladmin.Operation - err = transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: func() (operr error) { - op, operr = sql.NewClient(config, config.UserAgent).Instances.Insert(project, bootstrapInstance).Do() - return operr - }, - Timeout: 20 * time.Minute, - ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{transport_tpg.IsSqlOperationInProgressError}, - }) - if err != nil { - t.Fatalf("Error, failed to create instance %s: %s", bootstrapInstance.Name, err) - } - err = sql.SqlAdminOperationWaitTime(config, op, project, "Create Instance", config.UserAgent, 40*time.Minute) - if err != nil { - t.Fatalf("Error, failed to create instance %s: %s", bootstrapInstance.Name, err) - } - } - - // Look for backups in bootstrap instance - res, err := sql.NewClient(config, config.UserAgent).BackupRuns.List(project, bootstrapInstance.Name).Do() - if err != nil { - t.Fatalf("Unable to bootstrap SQL Instance. Cannot retrieve backup list: %s", err) - } - backupsList := res.Items - if len(backupsList) == 0 { - log.Printf("[DEBUG] No backups found for %s, creating backup", bootstrapInstance.Name) - backupRun := &sqladmin.BackupRun{ - Instance: bootstrapInstance.Name, - } - - var op *sqladmin.Operation - err = transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: func() (operr error) { - op, operr = sql.NewClient(config, config.UserAgent).BackupRuns.Insert(project, bootstrapInstance.Name, backupRun).Do() - return operr - }, - Timeout: 20 * time.Minute, - ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{transport_tpg.IsSqlOperationInProgressError}, - }) - if err != nil { - t.Fatalf("Error, failed to create instance backup: %s", err) - } - err = sql.SqlAdminOperationWaitTime(config, op, project, "Backup Instance", config.UserAgent, 20*time.Minute) - if err != nil { - t.Fatalf("Error, failed to create instance backup: %s", err) - } - } - - return bootstrapInstance.Name -} - -// waitForBackupdrOperation polls the operation until it is done or times out. -func waitForBackupdrOperation(ctx context.Context, t *testing.T, backupdrService *backupdr.Service, op *backupdr.Operation) (*backupdr.Operation, error) { - t.Helper() - opService := backupdr.NewProjectsLocationsOperationsService(backupdrService) - ticker := time.NewTicker(5 * time.Second) // Poll every 5 seconds - defer ticker.Stop() - - const timeout = 5 * time.Minute // Maximum time to wait - ctx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - - for { - select { - case <-ctx.Done(): - return nil, fmt.Errorf("timed out waiting for operation %s to complete", op.Name) - case <-ticker.C: - latestOp, err := opService.Get(op.Name).Context(ctx).Do() - if err != nil { - // Retry on transient errors if necessary, fail on others. - return nil, fmt.Errorf("error getting operation %s: %w", op.Name, err) - } - op = latestOp - t.Logf("Operation %s status: Done=%v", op.Name, op.Done) - - if op.Done { - if op.Error != nil { - return op, fmt.Errorf("operation %s failed: %v (code %d)", op.Name, op.Error.Message, op.Error.Code) - } - t.Logf("Operation %s completed successfully.", op.Name) - return op, nil - } - } - } -} - -// BootstrapBackupDRVault creates or gets a BackupDR backup vault for testing. -func BootstrapBackupDRVault(t *testing.T, vaultID, location string) string { - ctx := context.Background() - project := envvar.GetTestProjectFromEnv() - config := transport_tpg.BootstrapConfig(t) - if config == nil { - t.Fatal("Could not bootstrap config.") - } - - // Create a backupdr client and check if the vault exists, if not create a vault - // backupdrClient := backupdr_tpg.NewClient(config, config.UserAgent) - vaultName := fmt.Sprintf("projects/%s/locations/%s/backupVaults/%s", project, location, vaultID) - projectAndLocation := fmt.Sprintf("projects/%s/locations/%s", project, location) - - log.Printf("[DEBUG] Getting BackupDR vault %q", vaultName) - backupdrService := backupdr_tpg.NewClient(config, config.UserAgent) - _, err := backupdrService.Projects.Locations.BackupVaults.Get(vaultName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] BackupDR vault %q not found, bootstrapping", vaultName) - // Prepare the request body for BackupVault creation - enforcedRetentionDays := 1 - effectiveDays := 1 - - retentionDuration := time.Duration(enforcedRetentionDays) * 24 * time.Hour - effectiveTime := time.Now().Add(time.Duration(effectiveDays) * 24 * time.Hour) - - backupVault := &backupdr.BackupVault{ - BackupMinimumEnforcedRetentionDuration: fmt.Sprintf("%ds", int(retentionDuration.Seconds())), - EffectiveTime: effectiveTime.Format(time.RFC3339), - Description: "Created by BootstrapBackupDRVault function", - } - {{/* _, err = backupdr_tpg.NewClient(config, config.UserAgent).Projects.Locations.BackupVaults.Create(projectAndLocation, backupVault).Do() */}} - createCall := backupdrService.Projects.Locations.BackupVaults.Create(projectAndLocation, backupVault) - createCall.BackupVaultId(vaultID) // *** This is REQUIRED for the query parameter *** - // createCall.ValidateOnly(false) // Optional: explicit validate only flag - op, err := createCall.Do() - if err != nil { - t.Fatalf("Error calling Create BackupDR vault %q: %s", vaultName, err) - } - fmt.Printf("Successfully initiated creation of BackupDR vault %q (Operation: %s)\n", vaultName, op.Name) - - // *** WAIT FOR COMPLETION *** - if _, err := waitForBackupdrOperation(ctx, t, backupdrService, op); err != nil { - t.Fatalf("Create operation for %s failed: %v", vaultName, err) - } - fmt.Printf("Successfully created BackupDR vault %q\n", vaultName) - - } - - return vaultName -} - -func BootstrapSharedCaPoolInLocation(t *testing.T, location string) string { - project := envvar.GetTestProjectFromEnv() - poolName := "static-ca-pool" - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - log.Printf("[DEBUG] Getting shared CA pool %q", poolName) - url := fmt.Sprintf("%sprojects/%s/locations/%s/caPools/%s", transport_tpg.BaseUrl(privateca.Product, config), project, location, poolName) - _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "GET", - Project: project, - RawURL: url, - UserAgent: config.UserAgent, - }) - if err != nil { - log.Printf("[DEBUG] CA pool %q not found, bootstrapping", poolName) - poolObj := map[string]interface{}{ - "tier": "ENTERPRISE", - } - createUrl := fmt.Sprintf("%sprojects/%s/locations/%s/caPools?caPoolId=%s", transport_tpg.BaseUrl(privateca.Product, config), project, location, poolName) - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: project, - RawURL: createUrl, - UserAgent: config.UserAgent, - Body: poolObj, - Timeout: 4 * time.Minute, - }) - if err != nil { - t.Fatalf("Error bootstrapping shared CA pool %q: %s", poolName, err) - } - - log.Printf("[DEBUG] Waiting for CA pool creation to finish") - var opRes map[string]interface{} - err = privateca.PrivatecaOperationWaitTimeWithResponse( - config, res, &opRes, project, "Creating CA pool", config.UserAgent, - 4*time.Minute) - if err != nil { - t.Errorf("Error getting shared CA pool %q: %s", poolName, err) - } - _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "GET", - Project: project, - RawURL: url, - UserAgent: config.UserAgent, - }) - if err != nil { - t.Errorf("Error getting shared CA pool %q: %s", poolName, err) - } - } - return poolName -} - -func BootstrapSubnetForDataprocBatches(t *testing.T, subnetName string, networkName string) string { - subnetOptions := map[string]interface{}{ - "privateIpGoogleAccess": true, - } - return BootstrapSubnetWithOverrides(t, subnetName, networkName, subnetOptions) -} - -func BootstrapSubnet(t *testing.T, subnetName string, networkName string) string { - return BootstrapSubnetWithOverrides(t, subnetName, networkName, make(map[string]interface{})) -} - -func BootstrapSubnetWithFirewallForDataprocBatches(t *testing.T, testId string, subnetName string) string { - networkName := BootstrapSharedTestNetwork(t, testId) - subnetworkName := BootstrapSubnetForDataprocBatches(t, subnetName, networkName) - BootstrapFirewallForDataprocSharedNetwork(t, subnetName, networkName) - return subnetworkName -} - -func BootstrapSubnetWithOverrides(t *testing.T, subnetName string, networkName string, subnetOptions map[string]interface{}) string { - projectID := envvar.GetTestProjectFromEnv() - region := envvar.GetTestRegionFromEnv() - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - t.Fatal("Could not bootstrap config.") - } - - computeService := tpgcompute.NewClient(config, config.UserAgent) - if computeService == nil { - t.Fatal("Could not create compute client.") - } - - // In order to create a networkAttachment we need to bootstrap a subnet. - _, err := computeService.Subnetworks.Get(projectID, region, subnetName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] Subnet %q not found, bootstrapping", subnetName) - - networkUrl := fmt.Sprintf("%sprojects/%s/global/networks/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), projectID, networkName) - url := fmt.Sprintf("%sprojects/%s/regions/%s/subnetworks", transport_tpg.BaseUrl(tpgcompute.Product, config), projectID, region) - - defaultSubnetObj := map[string]interface{}{ - "name": subnetName, - "region ": region, - "network": networkUrl, - "ipCidrRange": "10.77.0.0/20", - } - - if len(subnetOptions) != 0 { - maps.Copy(defaultSubnetObj, subnetOptions) - } - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: projectID, - RawURL: url, - UserAgent: config.UserAgent, - Body: defaultSubnetObj, - Timeout: 4 * time.Minute, - }) - - log.Printf("Response is, %s", res) - if err != nil { - t.Fatalf("Error bootstrapping test subnet %s: %s", subnetName, err) - } - - log.Printf("[DEBUG] Waiting for network creation to finish") - err = tpgcompute.ComputeOperationWaitTime(config, res, projectID, "Error bootstrapping test subnet", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error bootstrapping test subnet %s: %s", subnetName, err) - } - } - - subnet, err := computeService.Subnetworks.Get(projectID, region, subnetName).Do() - - if subnet == nil { - t.Fatalf("Error getting test subnet %s: is nil", subnetName) - } - - if err != nil { - t.Fatalf("Error getting test subnet %s: %s", subnetName, err) - } - return subnet.Name -} - -func BootstrapNetworkAttachment(t *testing.T, networkAttachmentName string, subnetName string) string { - projectID := envvar.GetTestProjectFromEnv() - region := envvar.GetTestRegionFromEnv() - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - computeService := tpgcompute.NewClient(config, config.UserAgent) - if computeService == nil { - return "" - } - - networkAttachment, err := computeService.NetworkAttachments.Get(projectID, region, networkAttachmentName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - // Create Network Attachment Here. - log.Printf("[DEBUG] Network Attachment %s not found, bootstrapping", networkAttachmentName) - url := fmt.Sprintf("%sprojects/%s/regions/%s/networkAttachments", transport_tpg.BaseUrl(tpgcompute.Product, config), projectID, region) - - subnetURL := fmt.Sprintf("%sprojects/%s/regions/%s/subnetworks/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), projectID, region, subnetName) - networkAttachmentObj := map[string]interface{}{ - "name": networkAttachmentName, - "region": region, - "subnetworks": []string{subnetURL}, - "connectionPreference": "ACCEPT_AUTOMATIC", - } - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: projectID, - RawURL: url, - UserAgent: config.UserAgent, - Body: networkAttachmentObj, - Timeout: 4 * time.Minute, - }) - if err != nil { - t.Fatalf("Error bootstrapping test Network Attachment %s: %s", networkAttachmentName, err) - } - - log.Printf("[DEBUG] Waiting for network creation to finish") - err = tpgcompute.ComputeOperationWaitTime(config, res, projectID, "Error bootstrapping shared test subnet", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error bootstrapping test Network Attachment %s: %s", networkAttachmentName, err) - } - } - - networkAttachment, err = computeService.NetworkAttachments.Get(projectID, region, networkAttachmentName).Do() - - if networkAttachment == nil { - t.Fatalf("Error getting test network attachment %s: is nil", networkAttachmentName) - } - - if err != nil { - t.Fatalf("Error getting test Network Attachment %s: %s", networkAttachmentName, err) - } - - return networkAttachment.Name -} - -// The default network within GCP already comes pre configured with -// certain firewall rules open to allow internal communication. As we -// are boostrapping a network for dataproc tests, we need to additionally -// open up similar rules to allow the nodes to talk to each other -// internally as part of their configuration or this will just hang. -const SharedTestFirewallPrefix = "tf-bootstrap-firewall-" - -func BootstrapFirewallForDataprocSharedNetwork(t *testing.T, firewallName string, networkName string) string { - project := envvar.GetTestProjectFromEnv() - firewallName = SharedTestFirewallPrefix + firewallName - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - return "" - } - - log.Printf("[DEBUG] Getting Firewall %q for Network %q", firewallName, networkName) - _, err := tpgcompute.NewClient(config, config.UserAgent).Firewalls.Get(project, firewallName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] firewallName %q not found, bootstrapping", firewallName) - url := fmt.Sprintf("%sprojects/%s/global/firewalls", transport_tpg.BaseUrl(tpgcompute.Product, config), project) - - networkId := fmt.Sprintf("projects/%s/global/networks/%s", project, networkName) - allowObj := []interface{}{ - map[string]interface{}{ - "IPProtocol": "icmp", - }, - map[string]interface{}{ - "IPProtocol": "tcp", - "ports": []string{"0-65535"}, - }, - map[string]interface{}{ - "IPProtocol": "udp", - "ports": []string{"0-65535"}, - }, - } - - firewallObj := map[string]interface{}{ - "name": firewallName, - "network": networkId, - "allowed": allowObj, - } - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: project, - RawURL: url, - UserAgent: config.UserAgent, - Body: firewallObj, - Timeout: 4 * time.Minute, - }) - if err != nil { - t.Fatalf("Error bootstrapping Firewall %q for Network %q: %s", firewallName, networkName, err) - } - - log.Printf("[DEBUG] Waiting for Firewall creation to finish") - err = tpgcompute.ComputeOperationWaitTime(config, res, project, "Error bootstrapping Firewall", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error bootstrapping Firewall %q: %s", firewallName, err) - } - } - - firewall, err := tpgcompute.NewClient(config, config.UserAgent).Firewalls.Get(project, firewallName).Do() - if err != nil { - t.Errorf("Error getting Firewall %q: %s", firewallName, err) - } - if firewall == nil { - t.Fatalf("Error getting Firewall %q: is nil", firewallName) - } - return firewall.Name -} - -const SharedStoragePoolPrefix = "tf-bootstrap-storage-pool-" - -func BootstrapComputeStoragePool(t *testing.T, storagePoolName, storagePoolType string) string { - projectID := envvar.GetTestProjectFromEnv() - zone := envvar.GetTestZoneFromEnv() - - storagePoolName = SharedStoragePoolPrefix + storagePoolType + "-" + storagePoolName - - config := transport_tpg.BootstrapConfig(t) - if config == nil { - t.Fatal("Could not bootstrap config.") - } - - computeService := tpgcompute.NewClient(config, config.UserAgent) - if computeService == nil { - t.Fatal("Could not create compute client.") - } - - _, err := computeService.StoragePools.Get(projectID, zone, storagePoolName).Do() - if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { - log.Printf("[DEBUG] Storage pool %q not found, bootstrapping", storagePoolName) - - url := fmt.Sprintf("%sprojects/%s/zones/%s/storagePools", transport_tpg.BaseUrl(tpgcompute.Product, config), projectID, zone) - storagePoolTypeUrl := fmt.Sprintf("/projects/%s/zones/%s/storagePoolTypes/%s", projectID, zone, storagePoolType) - - storagePoolObj := map[string]interface{}{ - "name": storagePoolName, - "poolProvisionedCapacityGb": 10240, - "poolProvisionedThroughput": 180, - "storagePoolType": storagePoolTypeUrl, - "capacityProvisioningType": "ADVANCED", - } - - if storagePoolType == "hyperdisk-balanced" { - storagePoolObj["poolProvisionedIops"] = 10000 - storagePoolObj["poolProvisionedThroughput"] = 1024 - } - - res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: config, - Method: "POST", - Project: projectID, - RawURL: url, - UserAgent: config.UserAgent, - Body: storagePoolObj, - Timeout: 20 * time.Minute, - }) - - log.Printf("Response is, %s", res) - if err != nil { - t.Fatalf("Error bootstrapping storage pool %s: %s", storagePoolName, err) - } - - log.Printf("[DEBUG] Waiting for storage pool creation to finish") - err = tpgcompute.ComputeOperationWaitTime(config, res, projectID, "Error bootstrapping storage pool", config.UserAgent, 4*time.Minute) - if err != nil { - t.Fatalf("Error bootstrapping test storage pool %s: %s", storagePoolName, err) - } - } - - storagePool, err := computeService.StoragePools.Get(projectID, zone, storagePoolName).Do() - - if storagePool == nil { - t.Fatalf("Error getting storage pool %s: is nil", storagePoolName) - } - - if err != nil { - t.Fatalf("Error getting storage pool %s: %s", storagePoolName, err) - } - - storagePoolResourceName, err := tpgresource.GetRelativePath(storagePool.SelfLink) - - if err != nil { - t.Fatal("Failed to extract Storage Pool resource name from URL.") - } - - return storagePoolResourceName -} diff --git a/mmv1/third_party/terraform/acctest/diff_utils_test.go b/mmv1/third_party/terraform/acctest/diff_utils_test.go index c5ed0a0dc4ca..75c92e8ffb07 100644 --- a/mmv1/third_party/terraform/acctest/diff_utils_test.go +++ b/mmv1/third_party/terraform/acctest/diff_utils_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestReformConfigWithProvider(t *testing.T) { diff --git a/mmv1/third_party/terraform/acctest/provider_test_utils.go b/mmv1/third_party/terraform/acctest/provider_test_utils.go new file mode 100644 index 000000000000..c23c52632c7a --- /dev/null +++ b/mmv1/third_party/terraform/acctest/provider_test_utils.go @@ -0,0 +1,108 @@ +package acctest + +import ( + "context" + "io/ioutil" + "os" + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/provider" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +var TestAccProviders map[string]*schema.Provider +var testAccProvider *schema.Provider + +func init() { + configs = make(map[string]*transport_tpg.Config) + sources = make(map[string]VcrSource) + testAccProvider = provider.Provider() + TestAccProviders = map[string]*schema.Provider{ + "google": testAccProvider, + } +} + +// GoogleProviderConfig returns a configured SDKv2 provider. +// This function is typically used in CheckDestroy functions in acceptance tests. The provider client is used to make GET requests to check a resource is destroyed. +// Either a preexisting configured SDKv2 provider for the given test name is returned, or a new one is configured with empty (but non-nil) terraform.ResourceConfig +func GoogleProviderConfig(t *testing.T) *transport_tpg.Config { + configsLock.RLock() + config, ok := configs[t.Name()] + configsLock.RUnlock() + if ok { + return config + } + + sdkProvider := provider.Provider() + rc := terraform.ResourceConfig{} + + // `universe_domain` must be specified through config (i.e. unlike most provider settings there's no environment variable), and we check the value matches the credentials during provider initilization + // In the test environment we seed the value through a test-only environment variable, and we need to pre-seed a value in ResourceConfig as if it was in config to pass the check + universeDomain := envvar.GetTestUniverseDomainFromEnv(t) + if universeDomain != "" && universeDomain != "googleapis.com" { + rc.Config = make(map[string]interface{}) + rc.Config["universe_domain"] = universeDomain + } + sdkProvider.Configure(context.Background(), &rc) + return sdkProvider.Meta().(*transport_tpg.Config) +} + +func AccTestPreCheck(t *testing.T) { + if v := os.Getenv("GOOGLE_CREDENTIALS_FILE"); v != "" { + creds, err := ioutil.ReadFile(v) + if err != nil { + t.Fatalf("Error reading GOOGLE_CREDENTIALS_FILE path: %s", err) + } + os.Setenv("GOOGLE_CREDENTIALS", string(creds)) + } + + if v := envvar.MultiEnvSearch(envvar.CredsEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.CredsEnvVars, ", ")) + } + + if v := envvar.MultiEnvSearch(envvar.ProjectEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ProjectEnvVars, ", ")) + } + + if v := envvar.MultiEnvSearch(envvar.RegionEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.RegionEnvVars, ", ")) + } + + if v := envvar.MultiEnvSearch(envvar.ZoneEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ZoneEnvVars, ", ")) + } +} + +// AccTestPreCheck_AdcCredentialsOnly is a PreCheck function for acceptance tests that use ADCs when +func AccTestPreCheck_AdcCredentialsOnly(t *testing.T) { + if v := os.Getenv("GOOGLE_CREDENTIALS_FILE"); v != "" { + t.Log("Ignoring GOOGLE_CREDENTIALS_FILE; acceptance test doesn't use credentials other than ADCs") + } + + // Fail on set creds + if v := envvar.MultiEnvSearch(envvar.CredsEnvVarsExcludingAdcs()); v != "" { + t.Fatalf("This acceptance test only uses ADCs, so all of %s must be unset", strings.Join(envvar.CredsEnvVarsExcludingAdcs(), ", ")) + } + + // Fail on ADC ENV not set + if v := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"); v == "" { + t.Fatalf("GOOGLE_APPLICATION_CREDENTIALS must be set for acceptance tests that are dependent on ADCs") + } + + if v := envvar.MultiEnvSearch(envvar.ProjectEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ProjectEnvVars, ", ")) + } + + if v := envvar.MultiEnvSearch(envvar.RegionEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.RegionEnvVars, ", ")) + } + + if v := envvar.MultiEnvSearch(envvar.ZoneEnvVars); v == "" { + t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ZoneEnvVars, ", ")) + } +} diff --git a/mmv1/third_party/terraform/acctest/test_utils.go.tmpl b/mmv1/third_party/terraform/acctest/test_utils.go.tmpl index d4ecc0102735..14ed847da949 100644 --- a/mmv1/third_party/terraform/acctest/test_utils.go.tmpl +++ b/mmv1/third_party/terraform/acctest/test_utils.go.tmpl @@ -64,7 +64,7 @@ func CheckDataSourceStateMatchesResourceStateWithIgnores(dataSourceName, resourc continue } - if strings.HasPrefix(k, "labels.") || strings.HasPrefix(k, "terraform_labels.") || strings.HasPrefix(k, "effective_labels.") { + if strings.HasPrefix(k, "labels.") || strings.HasPrefix(k, "terraform_labels.") || strings.HasPrefix(k, "effective_labels.") || strings.HasPrefix(k, "deletion_policy") { continue } if k == "%" { diff --git a/mmv1/third_party/terraform/acctest/vcr_utils.go b/mmv1/third_party/terraform/acctest/vcr_utils.go index 863082dc71b2..4e8753d8c9ec 100644 --- a/mmv1/third_party/terraform/acctest/vcr_utils.go +++ b/mmv1/third_party/terraform/acctest/vcr_utils.go @@ -24,9 +24,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/fwprovider" tpgprovider "github.com/hashicorp/terraform-provider-google/google/provider" - "github.com/hashicorp/terraform-provider-google/google/services/compute" - "github.com/hashicorp/terraform-provider-google/google/services/pubsublite" - "github.com/hashicorp/terraform-provider-google/google/services/sql" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -176,6 +174,11 @@ func VcrTest(t *testing.T, c resource.TestCase) { re := regexp.MustCompile(`create_duration = "\d+[sm]"`) s.Config = re.ReplaceAllString(s.Config, `create_duration = "1s"`) } + // deletion_policy is a universal virtual attribute for managing the behavior of resources when a delete is attempted + // in Terraform. Because it is a virtual attribute, it needs to be excluded from these ImportStateVerifys. + if s.ImportStateVerify && !slices.Contains(s.ImportStateVerifyIgnore, "deletion_policy") { + s.ImportStateVerifyIgnore = append(s.ImportStateVerifyIgnore, "deletion_policy") + } steps = append(steps, s) } c.Steps = steps @@ -371,13 +374,13 @@ func (p *frameworkTestProvider) Configure(ctx context.Context, req provider.Conf func (p *frameworkTestProvider) DataSources(ctx context.Context) []func() datasource.DataSource { ds := p.FrameworkProvider.DataSources(ctx) ds = append(ds, fwprovider.NewGoogleProviderConfigPluginFrameworkDataSource) // google_provider_config_plugin_framework - ds = append(ds, compute.NewComputeNetworkFWDataSource) // google_fw_compute_network + return ds } func (p *frameworkTestProvider) Resources(ctx context.Context) []func() fwResource.Resource { r := p.FrameworkProvider.Resources(ctx) - r = append(r, pubsublite.NewGooglePubsubLiteReservationFWResource, sql.NewSQLUserFWResource) // google_fwprovider_pubsub_lite_reservation + return r } diff --git a/mmv1/third_party/terraform/allservices/allservices.go.tmpl b/mmv1/third_party/terraform/allservices/allservices.go.tmpl new file mode 100644 index 000000000000..d62c58b1582b --- /dev/null +++ b/mmv1/third_party/terraform/allservices/allservices.go.tmpl @@ -0,0 +1,10 @@ +// Package allservices imports all services in the provider. This greatly increases build time and should only be used +// in cases where access to all services is truly required. +package allservices + +import ( + // Register products/resources + {{- range $product := $.Products }} + _ "github.com/hashicorp/terraform-provider-google/google/services/{{ $product.ApiName }}" + {{- end }} +) \ No newline at end of file diff --git a/mmv1/third_party/terraform/acctest/resource_inventory_test.go b/mmv1/third_party/terraform/allservices/allservices_test.go similarity index 99% rename from mmv1/third_party/terraform/acctest/resource_inventory_test.go rename to mmv1/third_party/terraform/allservices/allservices_test.go index 6c64d768cab8..709b68e62337 100644 --- a/mmv1/third_party/terraform/acctest/resource_inventory_test.go +++ b/mmv1/third_party/terraform/allservices/allservices_test.go @@ -1,4 +1,4 @@ -package acctest_test +package allservices_test import ( "context" @@ -15,6 +15,7 @@ import ( fwtypes "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/allservices" "github.com/hashicorp/terraform-provider-google/google/fwprovider" "github.com/hashicorp/terraform-provider-google/google/provider" "github.com/hashicorp/terraform-provider-google/google/registry" diff --git a/mmv1/third_party/terraform/functions/location_from_id_test.go b/mmv1/third_party/terraform/functions/location_from_id_test.go index 8c50952ab746..a3a4a94d3315 100644 --- a/mmv1/third_party/terraform/functions/location_from_id_test.go +++ b/mmv1/third_party/terraform/functions/location_from_id_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" ) func TestAccProviderFunction_location_from_id(t *testing.T) { diff --git a/mmv1/third_party/terraform/functions/name_from_id_test.go b/mmv1/third_party/terraform/functions/name_from_id_test.go index 291cdec4a336..711de9b3bf91 100644 --- a/mmv1/third_party/terraform/functions/name_from_id_test.go +++ b/mmv1/third_party/terraform/functions/name_from_id_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" ) func TestAccProviderFunction_name_from_id(t *testing.T) { diff --git a/mmv1/third_party/terraform/functions/project_from_id_test.go b/mmv1/third_party/terraform/functions/project_from_id_test.go index 4439bb31a742..3152b2e6d478 100644 --- a/mmv1/third_party/terraform/functions/project_from_id_test.go +++ b/mmv1/third_party/terraform/functions/project_from_id_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" ) func TestAccProviderFunction_project_from_id(t *testing.T) { diff --git a/mmv1/third_party/terraform/functions/region_from_id_test.go b/mmv1/third_party/terraform/functions/region_from_id_test.go index 7e7ba815a0a0..1f29c06f33c2 100644 --- a/mmv1/third_party/terraform/functions/region_from_id_test.go +++ b/mmv1/third_party/terraform/functions/region_from_id_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccProviderFunction_region_from_id(t *testing.T) { diff --git a/mmv1/third_party/terraform/functions/region_from_zone_test.go b/mmv1/third_party/terraform/functions/region_from_zone_test.go index 9a01201bae82..b8e8e505031f 100644 --- a/mmv1/third_party/terraform/functions/region_from_zone_test.go +++ b/mmv1/third_party/terraform/functions/region_from_zone_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccProviderFunction_region_from_zone(t *testing.T) { diff --git a/mmv1/third_party/terraform/functions/zone_from_id_test.go b/mmv1/third_party/terraform/functions/zone_from_id_test.go index 46064a66c532..0cc00fd36701 100644 --- a/mmv1/third_party/terraform/functions/zone_from_id_test.go +++ b/mmv1/third_party/terraform/functions/zone_from_id_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccProviderFunction_zone_from_id(t *testing.T) { diff --git a/mmv1/third_party/terraform/fwmodels/provider_model.go.tmpl b/mmv1/third_party/terraform/fwmodels/provider_model.go.tmpl index c9533ff6d47f..3f534561472b 100644 --- a/mmv1/third_party/terraform/fwmodels/provider_model.go.tmpl +++ b/mmv1/third_party/terraform/fwmodels/provider_model.go.tmpl @@ -31,6 +31,7 @@ type ProviderModel struct { RequestTimeout types.String `tfsdk:"request_timeout"` RequestReason types.String `tfsdk:"request_reason"` PollInterval types.String `tfsdk:"poll_interval"` + DeletionPolicy types.String `tfsdk:"deletion_policy"` UniverseDomain types.String `tfsdk:"universe_domain"` DefaultLabels types.Map `tfsdk:"default_labels"` AddTerraformAttributionLabel types.Bool `tfsdk:"add_terraform_attribution_label"` diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider.go.tmpl b/mmv1/third_party/terraform/fwprovider/framework_provider.go.tmpl index 5ac64737e347..c2f79d10de53 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider.go.tmpl +++ b/mmv1/third_party/terraform/fwprovider/framework_provider.go.tmpl @@ -150,6 +150,9 @@ func (p *FrameworkProvider) Schema(_ context.Context, _ provider.SchemaRequest, fwvalidators.NonNegativeDurationValidator(), }, }, + "deletion_policy": schema.StringAttribute{ + Optional: true, + }, "request_reason": schema.StringAttribute{ Optional: true, }, @@ -213,6 +216,17 @@ func (p *FrameworkProvider) Schema(_ context.Context, _ provider.SchemaRequest, transport_tpg.CustomEndpointValidator(), }, }, + + // Generated Products. Although these will only be _populated_ for registered products, they + // must always be present to match the ProviderModel struct. + {{- range $product := $.Products }} + "{{ underscore $product.Name }}_custom_endpoint": &schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + transport_tpg.CustomEndpointValidator(), + }, + }, + {{- end }} }, Blocks: map[string]schema.Block{ "batching": schema.ListNestedBlock{ @@ -256,14 +270,6 @@ func (p *FrameworkProvider) Schema(_ context.Context, _ provider.SchemaRequest, }, }, } - for _, p := range registry.ListProducts() { - resp.Schema.Attributes[p.CustomEndpointField] = &schema.StringAttribute{ - Optional: true, - Validators: []validator.String{ - transport_tpg.CustomEndpointValidator(), - }, - } - } } // Configure prepares the metadata/'meta' required for data sources and resources to function. diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider_access_token_test.go.tmpl b/mmv1/third_party/terraform/fwprovider/framework_provider_access_token_test.go.tmpl index 6794da8e9d1d..0764832bd172 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider_access_token_test.go.tmpl +++ b/mmv1/third_party/terraform/fwprovider/framework_provider_access_token_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider_billing_project_test.go.tmpl b/mmv1/third_party/terraform/fwprovider/framework_provider_billing_project_test.go.tmpl index a5d6f428d0b4..b8956b0b5d57 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider_billing_project_test.go.tmpl +++ b/mmv1/third_party/terraform/fwprovider/framework_provider_billing_project_test.go.tmpl @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" {{- if ne $.TargetVersionName "ga" }} "github.com/hashicorp/terraform-provider-google/google/envvar" {{- end }} diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider_impersonate_service_account_delegates_test.go b/mmv1/third_party/terraform/fwprovider/framework_provider_impersonate_service_account_delegates_test.go index 8f9e47f8453c..8cf70e550989 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider_impersonate_service_account_delegates_test.go +++ b/mmv1/third_party/terraform/fwprovider/framework_provider_impersonate_service_account_delegates_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" ) // TestAccFwProvider_impersonate_service_account_delegates is a series of acc tests asserting how the plugin-framework provider handles impersonate_service_account_delegates arguments diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider_scopes_test.go.tmpl b/mmv1/third_party/terraform/fwprovider/framework_provider_scopes_test.go.tmpl index e9ab1623ed50..926152e2f424 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider_scopes_test.go.tmpl +++ b/mmv1/third_party/terraform/fwprovider/framework_provider_scopes_test.go.tmpl @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider_test.go.tmpl b/mmv1/third_party/terraform/fwprovider/framework_provider_test.go.tmpl index fe8a1d3677dc..986e2a7a2068 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider_test.go.tmpl +++ b/mmv1/third_party/terraform/fwprovider/framework_provider_test.go.tmpl @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" "github.com/hashicorp/terraform-provider-google/google/fwresource" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/fwprovider/framework_provider_user_project_override_test.go.tmpl b/mmv1/third_party/terraform/fwprovider/framework_provider_user_project_override_test.go.tmpl index 33b98e9ec647..b4fd37a01f03 100644 --- a/mmv1/third_party/terraform/fwprovider/framework_provider_user_project_override_test.go.tmpl +++ b/mmv1/third_party/terraform/fwprovider/framework_provider_user_project_override_test.go.tmpl @@ -9,8 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" {{ if ne $.TargetVersionName `ga` -}} "github.com/hashicorp/terraform-provider-google/google/envvar" + ptu "github.com/hashicorp/terraform-provider-google/google/provider/testutils" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" {{- end }} ) @@ -252,7 +254,7 @@ func testAccFwProvider_UserProjectOverride(t *testing.T) { pid := "tf-test-" + acctest.RandString(t, 10) config := transport_tpg.BootstrapConfig(t) - accessToken, err := acctest.SetupProjectsAndGetAccessToken(org, billing, pid, "firebase", config) + accessToken, err := ptu.SetupProjectsAndGetAccessToken(org, billing, pid, "firebase", config) if err != nil || accessToken == "" { if err == nil { t.Fatal("error when setting up projects and retrieving access token: access token is an empty string") @@ -263,7 +265,7 @@ func testAccFwProvider_UserProjectOverride(t *testing.T) { context := map[string]interface{}{ "user_project_override": false, // changed in config functions "access_token": accessToken, - "project_2": pid + "-2", // acctest.SetupProjectsAndGetAccessToken creates project 1 with id = `pid`, and 2 = `pid` + "-2" + "project_2": pid + "-2", // ptu.SetupProjectsAndGetAccessToken creates project 1 with id = `pid`, and 2 = `pid` + "-2" "random_suffix": acctest.RandString(t, 5), } diff --git a/mmv1/third_party/terraform/go.mod b/mmv1/third_party/terraform/go.mod index e455cd1e0ee0..25dfdf7af65c 100644 --- a/mmv1/third_party/terraform/go.mod +++ b/mmv1/third_party/terraform/go.mod @@ -3,11 +3,10 @@ module github.com/hashicorp/terraform-provider-google go 1.26.0 require ( - bitbucket.org/creachadair/stringset v0.0.11 cloud.google.com/go/auth v0.20.0 cloud.google.com/go/auth/oauth2adapt v0.2.8 cloud.google.com/go/bigquery v1.74.0 - cloud.google.com/go/bigtable v1.46.0 + cloud.google.com/go/bigtable v1.47.0 github.com/apparentlymart/go-cidr v1.1.0 github.com/cenkalti/backoff v2.2.1+incompatible github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc diff --git a/mmv1/third_party/terraform/go.sum b/mmv1/third_party/terraform/go.sum index f61c3436be65..db653a6b2c2e 100644 --- a/mmv1/third_party/terraform/go.sum +++ b/mmv1/third_party/terraform/go.sum @@ -1,5 +1,3 @@ -bitbucket.org/creachadair/stringset v0.0.11 h1:6Sv4CCv14Wm+OipW4f3tWOb0SQVpBDLW0knnJqUnmZ8= -bitbucket.org/creachadair/stringset v0.0.11/go.mod h1:wh0BHewFe+j0HrzWz7KcGbSNpFzWwnpmgPRlB57U5jU= cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= @@ -13,6 +11,10 @@ cloud.google.com/go/bigquery v1.74.0 h1:Q6bAMv+eyvufOpIrfrYxhM46qq1D3ZQTdgUDQqKS cloud.google.com/go/bigquery v1.74.0/go.mod h1:iViO7Cx3A/cRKcHNRsHB3yqGAMInFBswrE9Pxazsc90= cloud.google.com/go/bigtable v1.46.0 h1:Bd6vITx01s6gsdEPvjIGJL/oMMdKvraGI34UiixR2gk= cloud.google.com/go/bigtable v1.46.0/go.mod h1:GUM6PdkG3rrDse9kugqvX5+ktwo3ldfLtLi1VFn5Wj4= +cloud.google.com/go/bigtable v1.47.0 h1:NGLgDSr/i79BTGCjxH/maPKxyvl5q8/SsBsyLK52kdI= +cloud.google.com/go/bigtable v1.47.0/go.mod h1:GUM6PdkG3rrDse9kugqvX5+ktwo3ldfLtLi1VFn5Wj4= +cloud.google.com/go/cbt v0.0.0-20260420210353-85f2d34e5d76 h1:Z1SHENA/JyNF05PV2W3GWd9+fDOk/Xv7lS2LbAT16gM= +cloud.google.com/go/cbt v0.0.0-20260420210353-85f2d34e5d76/go.mod h1:gZO74ONiZSraTz3zakkYNPCy3hTBDb4hTHE31DbDXOw= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= cloud.google.com/go/datacatalog v1.26.1 h1:bCRKA8uSQN8wGW3Tw0gwko4E9a64GRmbW1nCblhgC2k= @@ -242,6 +244,9 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= @@ -258,6 +263,8 @@ github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zx github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= @@ -270,6 +277,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= diff --git a/mmv1/third_party/terraform/provider/provider.go.tmpl b/mmv1/third_party/terraform/provider/provider.go.tmpl index 80ea1a983f87..16b53a50e66f 100644 --- a/mmv1/third_party/terraform/provider/provider.go.tmpl +++ b/mmv1/third_party/terraform/provider/provider.go.tmpl @@ -144,6 +144,11 @@ func Provider() *schema.Provider { Optional: true, }, + "deletion_policy": { + Type: schema.TypeString, + Optional: true, + }, + "request_reason": { Type: schema.TypeString, Optional: true, @@ -209,6 +214,16 @@ func Provider() *schema.Provider { Optional: true, ValidateFunc: ValidateCustomEndpoint, }, + + // Generated Products. Although these will only be _populated_ for registered products, they + // must always be present to match the FW provider's schema (which must match its ProviderModel struct.) + {{- range $product := $.Products }} + "{{ underscore $product.Name }}_custom_endpoint": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: ValidateCustomEndpoint, + }, + {{- end }} }, ProviderMetaSchema: map[string]*schema.Schema{ @@ -223,14 +238,6 @@ func Provider() *schema.Provider { ResourcesMap: registry.ResourceMap(), } - for _, p := range registry.ListProducts() { - provider.Schema[p.CustomEndpointField] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: ValidateCustomEndpoint, - } - } - provider.ConfigureContextFunc = func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { return ProviderConfigure(ctx, d, provider) } @@ -288,6 +295,10 @@ func ProviderConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr } } + if v, ok := d.GetOk("deletion_policy"); ok { + config.DeletionPolicy = v.(string) + } + if v, ok := d.GetOk("request_reason"); ok { config.RequestReason = v.(string) } @@ -393,11 +404,6 @@ func ProviderConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr } config.BatchingConfig = batchCfg - // Registered products - {{- range $product := $.Products }} - config.{{ $product.Name }}BasePath = transport_tpg.BaseUrl(registry.GetProduct("{{ lower $product.Name }}"), &config) - {{- end }} - stopCtx, ok := schema.StopContext(ctx) if !ok { stopCtx = ctx diff --git a/mmv1/third_party/terraform/provider/provider_access_token_test.go b/mmv1/third_party/terraform/provider/provider_access_token_test.go index 482a15b21ae3..14e83c294c6f 100644 --- a/mmv1/third_party/terraform/provider/provider_access_token_test.go +++ b/mmv1/third_party/terraform/provider/provider_access_token_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // TestAccSdkProvider_access_token is a series of acc tests asserting how the SDK provider handles access_token arguments diff --git a/mmv1/third_party/terraform/provider/provider_billing_project_test.go b/mmv1/third_party/terraform/provider/provider_billing_project_test.go index e9f36c187931..53cc0d0af7ed 100644 --- a/mmv1/third_party/terraform/provider/provider_billing_project_test.go +++ b/mmv1/third_party/terraform/provider/provider_billing_project_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // TestAccSdkProvider_billing_project is a series of acc tests asserting how the SDK provider handles billing_project arguments diff --git a/mmv1/third_party/terraform/provider/provider_impersonate_service_account_delegates_test.go b/mmv1/third_party/terraform/provider/provider_impersonate_service_account_delegates_test.go index ffe38c791bd7..a064f0d3f58b 100644 --- a/mmv1/third_party/terraform/provider/provider_impersonate_service_account_delegates_test.go +++ b/mmv1/third_party/terraform/provider/provider_impersonate_service_account_delegates_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSdkProvider_impersonate_service_account_delegates(t *testing.T) { diff --git a/mmv1/third_party/terraform/provider/provider_impersonate_service_account_test.go b/mmv1/third_party/terraform/provider/provider_impersonate_service_account_test.go index 7697bddf78d4..f18a173b4be9 100644 --- a/mmv1/third_party/terraform/provider/provider_impersonate_service_account_test.go +++ b/mmv1/third_party/terraform/provider/provider_impersonate_service_account_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // TestAccSdkProvider_impersonate_service_account is a series of acc tests asserting how the SDK provider handles impersonate_service_account arguments diff --git a/mmv1/third_party/terraform/provider/provider_request_timeout_test.go b/mmv1/third_party/terraform/provider/provider_request_timeout_test.go index b48802d07ce1..5bb5cab9b8c2 100644 --- a/mmv1/third_party/terraform/provider/provider_request_timeout_test.go +++ b/mmv1/third_party/terraform/provider/provider_request_timeout_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // TestAccSdkProvider_request_timeout is a series of acc tests asserting how the SDK provider handles request_timeout arguments diff --git a/mmv1/third_party/terraform/provider/provider_scopes_test.go b/mmv1/third_party/terraform/provider/provider_scopes_test.go index 75fd4f754144..c508e5144052 100644 --- a/mmv1/third_party/terraform/provider/provider_scopes_test.go +++ b/mmv1/third_party/terraform/provider/provider_scopes_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/provider/provider_test.go.tmpl b/mmv1/third_party/terraform/provider/provider_test.go similarity index 97% rename from mmv1/third_party/terraform/provider/provider_test.go.tmpl rename to mmv1/third_party/terraform/provider/provider_test.go index 73dc2f762556..d3ac4fea138a 100644 --- a/mmv1/third_party/terraform/provider/provider_test.go.tmpl +++ b/mmv1/third_party/terraform/provider/provider_test.go @@ -2,19 +2,21 @@ package provider_test import ( "fmt" - "regexp" "os" + "regexp" "strings" "testing" - "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/provider" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" ) @@ -250,7 +252,7 @@ func TestAccProviderInvalidRepConfig(t *testing.T) { CheckDestroy: testAccCheckComputeAddressDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccProviderInvalidRepConfig(), + Config: testAccProviderInvalidRepConfig(), ExpectError: regexp.MustCompile("conflict between prefer_global_endpoints and prefer_regional_endpoints"), }, }, @@ -325,7 +327,7 @@ func testAccCheckComputeAddressDestroyProducer(t *testing.T) func(s *terraform.S config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/addresses/{{"{{"}}name{{"}}"}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/addresses/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/provider/provider_user_project_override_test.go b/mmv1/third_party/terraform/provider/provider_user_project_override_test.go index 24457617b952..d44d3107ab12 100644 --- a/mmv1/third_party/terraform/provider/provider_user_project_override_test.go +++ b/mmv1/third_party/terraform/provider/provider_user_project_override_test.go @@ -8,6 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + ptu "github.com/hashicorp/terraform-provider-google/google/provider/testutils" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -243,7 +246,7 @@ data "google_provider_config_sdk" "default" {} func testAccProviderUserProjectOverride(t *testing.T) { // Test cannot run in VCR mode due to use of aliases // See: https://github.com/hashicorp/terraform-provider-google/issues/20019 - // And also due to the resources made out of band in acctest.SetupProjectsAndGetAccessToken + // And also due to the resources made out of band in ptu.SetupProjectsAndGetAccessToken acctest.SkipIfVcr(t) t.Parallel() @@ -253,7 +256,7 @@ func testAccProviderUserProjectOverride(t *testing.T) { topicName := "tf-test-topic-" + acctest.RandString(t, 10) config := transport_tpg.BootstrapConfig(t) - accessToken, err := acctest.SetupProjectsAndGetAccessToken(org, billing, pid, "pubsub", config) + accessToken, err := ptu.SetupProjectsAndGetAccessToken(org, billing, pid, "pubsub", config) if err != nil || accessToken == "" { if err == nil { t.Fatal("error when setting up projects and retrieving access token: access token is an empty string") @@ -291,7 +294,7 @@ func testAccProviderUserProjectOverride(t *testing.T) { func testAccProviderIndirectUserProjectOverride(t *testing.T) { // Test cannot run in VCR mode due to use of aliases // See: https://github.com/hashicorp/terraform-provider-google/issues/20019 - // And also due to the resources made out of band in acctest.SetupProjectsAndGetAccessToken + // And also due to the resources made out of band in ptu.SetupProjectsAndGetAccessToken acctest.SkipIfVcr(t) t.Parallel() @@ -300,7 +303,7 @@ func testAccProviderIndirectUserProjectOverride(t *testing.T) { pid := "tf-test-" + acctest.RandString(t, 10) config := transport_tpg.BootstrapConfig(t) - accessToken, err := acctest.SetupProjectsAndGetAccessToken(org, billing, pid, "cloudkms", config) + accessToken, err := ptu.SetupProjectsAndGetAccessToken(org, billing, pid, "cloudkms", config) if err != nil || accessToken == "" { if err == nil { t.Fatal("error when setting up projects and retrieving access token: access token is an empty string") diff --git a/mmv1/third_party/terraform/acctest/provider_test_utils.go.tmpl b/mmv1/third_party/terraform/provider/testutils/testutils.go.tmpl similarity index 66% rename from mmv1/third_party/terraform/acctest/provider_test_utils.go.tmpl rename to mmv1/third_party/terraform/provider/testutils/testutils.go.tmpl index 61e0e3d1b1d4..bc6ca19aad7e 100644 --- a/mmv1/third_party/terraform/acctest/provider_test_utils.go.tmpl +++ b/mmv1/third_party/terraform/provider/testutils/testutils.go.tmpl @@ -1,17 +1,6 @@ -package acctest +package testutils import ( - "context" - "io/ioutil" - "os" - "strings" - "testing" - - "github.com/hashicorp/terraform-provider-google/google/envvar" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - "fmt" "time" @@ -20,8 +9,8 @@ import ( "google.golang.org/api/iamcredentials/v1" "google.golang.org/api/serviceusage/v1" - "github.com/hashicorp/terraform-provider-google/google/provider" tpgcloudbilling "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" tpgiamcredentials "github.com/hashicorp/terraform-provider-google/google/services/iamcredentials" "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" @@ -31,98 +20,6 @@ import ( transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) -var TestAccProviders map[string]*schema.Provider -var testAccProvider *schema.Provider - -func init() { - configs = make(map[string]*transport_tpg.Config) - sources = make(map[string]VcrSource) - testAccProvider = provider.Provider() - TestAccProviders = map[string]*schema.Provider{ - "google": testAccProvider, - } -} - -// GoogleProviderConfig returns a configured SDKv2 provider. -// This function is typically used in CheckDestroy functions in acceptance tests. The provider client is used to make GET requests to check a resource is destroyed. -// Either a preexisting configured SDKv2 provider for the given test name is returned, or a new one is configured with empty (but non-nil) terraform.ResourceConfig -func GoogleProviderConfig(t *testing.T) *transport_tpg.Config { - configsLock.RLock() - config, ok := configs[t.Name()] - configsLock.RUnlock() - if ok { - return config - } - - sdkProvider := provider.Provider() - rc := terraform.ResourceConfig{} - - // `universe_domain` must be specified through config (i.e. unlike most provider settings there's no environment variable), and we check the value matches the credentials during provider initilization - // In the test environment we seed the value through a test-only environment variable, and we need to pre-seed a value in ResourceConfig as if it was in config to pass the check - universeDomain := envvar.GetTestUniverseDomainFromEnv(t) - if universeDomain != "" && universeDomain != "googleapis.com" { - rc.Config = make(map[string]interface{}) - rc.Config["universe_domain"] = universeDomain - } - sdkProvider.Configure(context.Background(), &rc) - return sdkProvider.Meta().(*transport_tpg.Config) -} - -func AccTestPreCheck(t *testing.T) { - if v := os.Getenv("GOOGLE_CREDENTIALS_FILE"); v != "" { - creds, err := ioutil.ReadFile(v) - if err != nil { - t.Fatalf("Error reading GOOGLE_CREDENTIALS_FILE path: %s", err) - } - os.Setenv("GOOGLE_CREDENTIALS", string(creds)) - } - - if v := envvar.MultiEnvSearch(envvar.CredsEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.CredsEnvVars, ", ")) - } - - if v := envvar.MultiEnvSearch(envvar.ProjectEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ProjectEnvVars, ", ")) - } - - if v := envvar.MultiEnvSearch(envvar.RegionEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.RegionEnvVars, ", ")) - } - - if v := envvar.MultiEnvSearch(envvar.ZoneEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ZoneEnvVars, ", ")) - } -} - -// AccTestPreCheck_AdcCredentialsOnly is a PreCheck function for acceptance tests that use ADCs when -func AccTestPreCheck_AdcCredentialsOnly(t *testing.T) { - if v := os.Getenv("GOOGLE_CREDENTIALS_FILE"); v != "" { - t.Log("Ignoring GOOGLE_CREDENTIALS_FILE; acceptance test doesn't use credentials other than ADCs") - } - - // Fail on set creds - if v := envvar.MultiEnvSearch(envvar.CredsEnvVarsExcludingAdcs()); v != "" { - t.Fatalf("This acceptance test only uses ADCs, so all of %s must be unset", strings.Join(envvar.CredsEnvVarsExcludingAdcs(), ", ")) - } - - // Fail on ADC ENV not set - if v := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"); v == "" { - t.Fatalf("GOOGLE_APPLICATION_CREDENTIALS must be set for acceptance tests that are dependent on ADCs") - } - - if v := envvar.MultiEnvSearch(envvar.ProjectEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ProjectEnvVars, ", ")) - } - - if v := envvar.MultiEnvSearch(envvar.RegionEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.RegionEnvVars, ", ")) - } - - if v := envvar.MultiEnvSearch(envvar.ZoneEnvVars); v == "" { - t.Fatalf("One of %s must be set for acceptance tests", strings.Join(envvar.ZoneEnvVars, ", ")) - } -} - func SetupProjectsAndGetAccessToken(org, billing, pid, service string, config *transport_tpg.Config) (string, error) { // Create project-1 and project-2 rmService := rmClient.NewClient(config, config.UserAgent) @@ -250,8 +147,8 @@ func SetupProjectsAndGetAccessToken(org, billing, pid, service string, config *t } // Create a service account for project-1 - serviceAccountEmail := serviceAccountPrefix + service - sa1, err := getOrCreateServiceAccount(config, pid, serviceAccountEmail) + serviceAccountEmail := iambeta.ServiceAccountPrefix + service + sa1, err := iambeta.GetOrCreateServiceAccount(config, pid, serviceAccountEmail) if err != nil { return "", fmt.Errorf("error creating service account %s in 'project-1' with project id %s: %w", serviceAccountEmail, pid, err) } @@ -337,4 +234,4 @@ func SetupProjectsAndGetAccessToken(org, billing, pid, service string, config *t accessToken := atResp.AccessToken return accessToken, nil -} \ No newline at end of file +} diff --git a/mmv1/third_party/terraform/provider/universe/universe_domain_pubsub_test.go b/mmv1/third_party/terraform/provider/universe/universe_domain_pubsub_test.go index 09fbfd05baa7..ec0ef34f414f 100644 --- a/mmv1/third_party/terraform/provider/universe/universe_domain_pubsub_test.go +++ b/mmv1/third_party/terraform/provider/universe/universe_domain_pubsub_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/accessapproval/data_source_access_approval_folder_service_account_test.go b/mmv1/third_party/terraform/services/accessapproval/data_source_access_approval_folder_service_account_test.go index 27a706c13aec..35b60f89e819 100644 --- a/mmv1/third_party/terraform/services/accessapproval/data_source_access_approval_folder_service_account_test.go +++ b/mmv1/third_party/terraform/services/accessapproval/data_source_access_approval_folder_service_account_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceAccessApprovalFolderServiceAccount_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_folder_settings_test.go b/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_folder_settings_test.go index d87f28d77494..83a3070735bc 100644 --- a/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_folder_settings_test.go +++ b/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_folder_settings_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/accessapproval" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_organization_settings_test.go b/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_organization_settings_test.go index b7c7094dd0c6..75cb87c7df5a 100644 --- a/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_organization_settings_test.go +++ b/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_organization_settings_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/accessapproval" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_project_settings_test.go b/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_project_settings_test.go index 9f39d767937e..0d663441d28b 100644 --- a/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_project_settings_test.go +++ b/mmv1/third_party/terraform/services/accessapproval/resource_access_approval_project_settings_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/accessapproval" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/data_source_access_context_manager_access_policy_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/data_source_access_context_manager_access_policy_test.go index 34cf607a54e2..647d34e10642 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/data_source_access_context_manager_access_policy_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/data_source_access_context_manager_access_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" ) func testAccDataSourceAccessContextManagerServicePerimeter_basicTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_condition_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_condition_test.go index 903880ce390f..1f4c55e20bdb 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_condition_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_condition_test.go @@ -11,6 +11,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_test.go.tmpl b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_test.go.tmpl index 428d6e281253..30d377fbe028 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_test.go.tmpl +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_level_test.go.tmpl @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_levels_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_levels_test.go index 7b1b5f0c635a..6b069e33ab61 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_levels_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_levels_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_policy_iam_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_policy_iam_test.go index 8a3dd6966604..b8b8c190caf8 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_policy_iam_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_access_policy_iam_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func testAccAccessContextManagerAccessPolicyIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_gcp_user_access_binding_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_gcp_user_access_binding_test.go index 5ef3d7625d6e..953583dcdc28 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_gcp_user_access_binding_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_gcp_user_access_binding_test.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_egress_policy_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_egress_policy_test.go index 519f9a76106d..9c1c6cf8645f 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_egress_policy_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_egress_policy_test.go @@ -10,20 +10,80 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1" ) +var SharedServicePerimeterProjectPrefix = "tf-bootstrap-sp-" + +func BootstrapServicePerimeterProjects(t *testing.T, desiredProjects int) []*cloudresourcemanager.Project { + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return nil + } + + org := envvar.GetTestOrgFromEnv(t) + + // The filter endpoint works differently if you provide both the parent id and parent type, and + // doesn't seem to allow for prefix matching. Don't change this to include the parent type unless + // that API behavior changes. + prefixFilter := fmt.Sprintf("id:%s* parent.id:%s", SharedServicePerimeterProjectPrefix, org) + res, err := rmClient.NewClient(config, config.UserAgent).Projects.List().Filter(prefixFilter).Do() + if err != nil { + t.Fatalf("Error getting shared test projects: %s", err) + } + + projects := res.Projects + for len(projects) < desiredProjects { + pid := SharedServicePerimeterProjectPrefix + acctest.RandString(t, 10) + project := &cloudresourcemanager.Project{ + ProjectId: pid, + Name: "TF Service Perimeter Test", + Parent: &cloudresourcemanager.ResourceId{ + Type: "organization", + Id: org, + }, + } + op, err := rmClient.NewClient(config, config.UserAgent).Projects.Create(project).Do() + if err != nil { + t.Fatalf("Error bootstrapping shared test project: %s", err) + } + + opAsMap, err := tpgresource.ConvertToMap(op) + if err != nil { + t.Fatalf("Error bootstrapping shared test project: %s", err) + } + + err = resourcemanager.ResourceManagerOperationWaitTime(config, opAsMap, "creating project", config.UserAgent, 4) + if err != nil { + t.Fatalf("Error bootstrapping shared test project: %s", err) + } + + p, err := rmClient.NewClient(config, config.UserAgent).Projects.Get(pid).Do() + if err != nil { + t.Fatalf("Error getting shared test project: %s", err) + } + projects = append(projects, p) + } + + return projects +} + // Since each test here is acting on the same organization and only one AccessPolicy // can exist, they need to be run serially. See AccessPolicy for the test runner. func testAccAccessContextManagerServicePerimeterDryRunEgressPolicy_basicTest(t *testing.T) { org := envvar.GetTestOrgFromEnv(t) - //projects := acctest.BootstrapServicePerimeterProjects(t, 1) + //projects := BootstrapServicePerimeterProjects(t, 1) // Bootstrap a service account to use as egress from identity initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - serviceAccount := acctest.BootstrapServiceAccount(t, "acm-egress-1", initialServiceAccount) + serviceAccount := iambeta.BootstrapServiceAccount(t, "acm-egress-1", initialServiceAccount) policyTitle := acctest.RandString(t, 10) perimeterTitle := "perimeter" diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_ingress_policy_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_ingress_policy_test.go index 38c82b754d22..647a0be8cd4e 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_ingress_policy_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_ingress_policy_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -19,11 +20,11 @@ import ( func testAccAccessContextManagerServicePerimeterDryRunIngressPolicy_basicTest(t *testing.T) { org := envvar.GetTestOrgFromEnv(t) - //projects := acctest.BootstrapServicePerimeterProjects(t, 1) + //projects := BootstrapServicePerimeterProjects(t, 1) // Bootstrap a service account to use as ingress from identity initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - serviceAccount := acctest.BootstrapServiceAccount(t, "acm-ingress-1", initialServiceAccount) + serviceAccount := iambeta.BootstrapServiceAccount(t, "acm-ingress-1", initialServiceAccount) policyTitle := acctest.RandString(t, 10) perimeterTitle := "perimeter" diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_resource_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_resource_test.go index 7fd98bd4b421..5288766459b6 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_resource_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_dry_run_resource_test.go @@ -18,7 +18,7 @@ import ( func testAccAccessContextManagerServicePerimeterDryRunResource_basicTest(t *testing.T) { org := envvar.GetTestOrgFromEnv(t) - projects := acctest.BootstrapServicePerimeterProjects(t, 2) + projects := BootstrapServicePerimeterProjects(t, 2) policyTitle := "my policy" perimeterTitle := "perimeter" diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_egress_policy_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_egress_policy_test.go index 62cac0a90b22..709516576aae 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_egress_policy_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_egress_policy_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -22,9 +23,9 @@ func testAccAccessContextManagerServicePerimeterEgressPolicy_basicTest(t *testin // Bootstrap a service account to use as egress from identity initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - serviceAccount := acctest.BootstrapServiceAccount(t, "acm-egress-2", initialServiceAccount) + serviceAccount := iambeta.BootstrapServiceAccount(t, "acm-egress-2", initialServiceAccount) - //projects := acctest.BootstrapServicePerimeterProjects(t, 1) + //projects := BootstrapServicePerimeterProjects(t, 1) policyTitle := acctest.RandString(t, 10) perimeterTitle := "perimeter" projectNumber := envvar.GetTestProjectNumberFromEnv() diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_ingress_policy_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_ingress_policy_test.go index 8273b46ed5c0..784bd1280632 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_ingress_policy_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_ingress_policy_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -19,11 +20,11 @@ import ( func testAccAccessContextManagerServicePerimeterIngressPolicy_basicTest(t *testing.T) { org := envvar.GetTestOrgFromEnv(t) - //projects := acctest.BootstrapServicePerimeterProjects(t, 1) + //projects := BootstrapServicePerimeterProjects(t, 1) // Bootstrap a service account to use as ingress from identity initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - serviceAccount := acctest.BootstrapServiceAccount(t, "acm-ingress-2", initialServiceAccount) + serviceAccount := iambeta.BootstrapServiceAccount(t, "acm-ingress-2", initialServiceAccount) policyTitle := acctest.RandString(t, 10) perimeterTitle := "perimeter" diff --git a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_resource_test.go b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_resource_test.go index b3930663bb01..cd48f4c85d3c 100644 --- a/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_resource_test.go +++ b/mmv1/third_party/terraform/services/accesscontextmanager/resource_access_context_manager_service_perimeter_resource_test.go @@ -18,7 +18,7 @@ import ( func testAccAccessContextManagerServicePerimeterResource_basicTest(t *testing.T) { org := envvar.GetTestOrgFromEnv(t) - projects := acctest.BootstrapServicePerimeterProjects(t, 2) + projects := BootstrapServicePerimeterProjects(t, 2) policyTitle := "my policy" perimeterTitle := "perimeter" diff --git a/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_cluster_test.go b/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_cluster_test.go index c70906077b38..a4f49be54544 100644 --- a/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_cluster_test.go +++ b/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_cluster_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccAlloydbDatabaseClusterDatasourceConfig(t *testing.T) { @@ -12,7 +14,7 @@ func TestAccAlloydbDatabaseClusterDatasourceConfig(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_database_instance_test.go b/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_database_instance_test.go index 805a1cb8c1d3..c329aa6c4419 100644 --- a/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_database_instance_test.go +++ b/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_database_instance_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccAlloydbDatabaseInstanceDatasourceConfig(t *testing.T) { @@ -12,7 +14,7 @@ func TestAccAlloydbDatabaseInstanceDatasourceConfig(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_supported_database_flags.go b/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_supported_database_flags.go index 0925dba17cf3..35532f2922ff 100644 --- a/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_supported_database_flags.go +++ b/mmv1/third_party/terraform/services/alloydb/data_source_alloydb_supported_database_flags.go @@ -210,7 +210,7 @@ func dataSourceAlloydbSupportedDatabaseFlagsRead(d *schema.ResourceData, meta in if res["pageToken"] == nil || res["pageToken"].(string) == "" { break } - url, err = tpgresource.ReplaceVars(d, config, "{{AlloydbBasePath}}projects/{{project}}/locations/{{location}}/supportedDatabaseFlags?pageToken="+res["nextPageToken"].(string)) + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/supportedDatabaseFlags?pageToken="+res["nextPageToken"].(string)) if err != nil { return fmt.Errorf("Error setting api endpoint") } diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_backup_test.go b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_backup_test.go index e683e65b8009..079e7170b21a 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_backup_test.go +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_backup_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccAlloydbBackup_update(t *testing.T) { @@ -12,7 +15,7 @@ func TestAccAlloydbBackup_update(t *testing.T) { random_suffix := acctest.RandString(t, 10) context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": random_suffix, } @@ -131,7 +134,7 @@ func TestAccAlloydbBackup_createBackupWithMandatoryFields(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -187,9 +190,9 @@ func TestAccAlloydbBackup_usingCMEK(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-backup-key1").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-backup-key1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_restore_test.go b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_restore_test.go index 670cf91b7098..5142150e946d 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_restore_test.go +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_restore_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) /* @@ -20,7 +23,7 @@ func TestAccAlloydbCluster_restore(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -659,8 +662,8 @@ func TestAccAlloydbCluster_restoreFromBackupDrBackup(t *testing.T) { "project": project, "location": location, "backup_vault_id": backupVaultID, - "backup_vault": acctest.BootstrapBackupDRVault(t, backupVaultID, location), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "backup_vault": backupdr.BootstrapBackupDRVault(t, backupVaultID, location), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -754,11 +757,11 @@ resource "google_backup_dr_backup_plan" "plan" { // Associate backup plan with AlloyDB cluster resource "google_backup_dr_backup_plan_association" "association" { - location = "%{location}" - backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}" - resource = "${google_alloydb_cluster.source.name}" - resource_type = "alloydb.googleapis.com/Cluster" - backup_plan = google_backup_dr_backup_plan.plan.name + location = "%{location}" + backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}" + resource = "${google_alloydb_cluster.source.name}" + resource_type = "alloydb.googleapis.com/Cluster" + backup_plan = google_backup_dr_backup_plan.plan.name depends_on = [ google_alloydb_instance.source ] } @@ -771,10 +774,10 @@ resource "time_sleep" "wait_10_mins" { } data "google_backup_dr_backup" "alloydb_backups" { - project = "%{project}" - location = "us-central1" - backup_vault_id = "%{backup_vault_id}" - data_source_id = element(split("/", google_backup_dr_backup_plan_association.association.data_source), length(split("/", google_backup_dr_backup_plan_association.association.data_source)) - 1) + project = "%{project}" + location = "us-central1" + backup_vault_id = "%{backup_vault_id}" + data_source_id = element(split("/", google_backup_dr_backup_plan_association.association.data_source), length(split("/", google_backup_dr_backup_plan_association.association.data_source)) - 1) depends_on = [time_sleep.wait_10_mins] } @@ -855,11 +858,11 @@ resource "google_backup_dr_backup_plan" "plan" { // Associate backup plan with AlloyDB cluster resource "google_backup_dr_backup_plan_association" "association" { - location = "%{location}" - backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}" - resource = "${google_alloydb_cluster.source.name}" - resource_type = "alloydb.googleapis.com/Cluster" - backup_plan = google_backup_dr_backup_plan.plan.name + location = "%{location}" + backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}" + resource = "${google_alloydb_cluster.source.name}" + resource_type = "alloydb.googleapis.com/Cluster" + backup_plan = google_backup_dr_backup_plan.plan.name depends_on = [ google_alloydb_instance.source ] } @@ -872,10 +875,10 @@ resource "time_sleep" "wait_10_mins" { } data "google_backup_dr_backup" "alloydb_backups" { - project = "%{project}" - location = "us-central1" - backup_vault_id = "%{backup_vault_id}" - data_source_id = element(split("/", google_backup_dr_backup_plan_association.association.data_source), length(split("/", google_backup_dr_backup_plan_association.association.data_source)) - 1) + project = "%{project}" + location = "us-central1" + backup_vault_id = "%{backup_vault_id}" + data_source_id = element(split("/", google_backup_dr_backup_plan_association.association.data_source), length(split("/", google_backup_dr_backup_plan_association.association.data_source)) - 1) depends_on = [time_sleep.wait_10_mins] } @@ -961,11 +964,11 @@ resource "google_backup_dr_backup_plan" "plan" { // Associate backup plan with AlloyDB cluster resource "google_backup_dr_backup_plan_association" "association" { - location = "%{location}" - backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}" - resource = "${google_alloydb_cluster.source.name}" - resource_type = "alloydb.googleapis.com/Cluster" - backup_plan = google_backup_dr_backup_plan.plan.name + location = "%{location}" + backup_plan_association_id = "tf-test-bpa-test-%{random_suffix}" + resource = "${google_alloydb_cluster.source.name}" + resource_type = "alloydb.googleapis.com/Cluster" + backup_plan = google_backup_dr_backup_plan.plan.name depends_on = [ google_alloydb_instance.source ] } diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_test.go b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_test.go index 8433526d1377..ad16ab4bd5c3 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_test.go +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_cluster_test.go @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccAlloydbCluster_update(t *testing.T) { @@ -80,7 +84,7 @@ func TestAccAlloydbCluster_upgrade(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -689,7 +693,7 @@ func TestAccAlloydbCluster_usingCMEK(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-cluster-key1").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-cluster-key1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -745,8 +749,8 @@ func TestAccAlloydbCluster_CMEKInAutomatedBackupIsUpdatable(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_name1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-backup-update-key1").CryptoKey.Name, - "kms_key_name2": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-backup-update-key2").CryptoKey.Name, + "kms_key_name1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-backup-update-key1").CryptoKey.Name, + "kms_key_name2": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-backup-update-key2").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -1206,18 +1210,18 @@ func TestAccAlloydbCluster_continuousBackup_CMEKIsUpdatable(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - kms := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-key1") + boostrapped := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-key1") context := map[string]interface{}{ "random_suffix": suffix, - "key_ring": kms.KeyRing.Name, - "key_name": kms.CryptoKey.Name, + "key_ring": boostrapped.KeyRing.Name, + "key_name": boostrapped.CryptoKey.Name, } - kms2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-key2") + bootstrapped2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-alloydb-key2") context2 := map[string]interface{}{ "random_suffix": suffix, - "key_ring": kms2.KeyRing.Name, - "key_name": kms2.CryptoKey.Name, + "key_ring": bootstrapped2.KeyRing.Name, + "key_name": bootstrapped2.CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_instance_test.go.tmpl b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_instance_test.go.tmpl index 0407547e7d0d..449b57a94b7c 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_instance_test.go.tmpl @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccAlloydbInstance_update(t *testing.T) { @@ -12,7 +15,7 @@ func TestAccAlloydbInstance_update(t *testing.T) { random_suffix := acctest.RandString(t, 10) context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": random_suffix, "alloydb_cluster_name": "tf-test-alloydb-cluster" + random_suffix, "alloydb_instance_name": "tf-test-alloydb-instance" + random_suffix, @@ -140,7 +143,7 @@ func TestAccAlloydbInstance_createInstanceWithMandatoryFields(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -160,7 +163,7 @@ func TestAccAlloydbInstance_stopstart(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") context := map[string]interface{}{ "random_suffix": suffix, @@ -292,7 +295,7 @@ data "google_compute_network" "default" { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -367,7 +370,7 @@ func TestAccAlloydbInstance_createPrimaryAndReadPoolInstance(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -428,7 +431,7 @@ data "google_compute_network" "default" { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -519,8 +522,8 @@ func TestAccAlloydbInstance_createInstanceWithNetworkConfigAndAllocatedIPRange(t t.Parallel() testId := "alloydb-1" - addressName := acctest.BootstrapSharedTestGlobalAddress(t, testId) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, testId) + addressName := tpgcompute.BootstrapSharedTestGlobalAddress(t, testId) + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, testId) context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), @@ -582,7 +585,7 @@ func TestAccAlloydbInstance_clientConnectionConfig(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") context := map[string]interface{}{ "random_suffix": suffix, @@ -763,7 +766,7 @@ func TestAccAlloydbInstance_networkConfig(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") context1 := map[string]interface{}{ "random_suffix": suffix, @@ -1014,13 +1017,13 @@ data "google_project" "project" {} func TestAccAlloydbInstance_createInstanceWithPscInterfaceConfigs(t *testing.T) { t.Parallel() - networkName := acctest.BootstrapSharedTestNetwork(t, "tf-test-alloydb-network") - subnetworkName := acctest.BootstrapSubnet(t, "tf-test-alloydb-subnetwork", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "tf-test-alloydb-network") + subnetworkName := tpgcompute.BootstrapSubnet(t, "tf-test-alloydb-subnetwork", networkName) random_suffix := acctest.RandString(t, 10) context := map[string]interface{}{ "random_suffix": random_suffix, - "networkAttachmentName": acctest.BootstrapNetworkAttachment(t, "tf-test-alloydb-create-na", subnetworkName), + "networkAttachmentName": tpgcompute.BootstrapNetworkAttachment(t, "tf-test-alloydb-create-na", subnetworkName), } acctest.VcrTest(t, resource.TestCase{ @@ -1071,13 +1074,13 @@ data "google_project" "project" {} func TestAccAlloydbInstance_updateInstanceWithPscInterfaceConfigs(t *testing.T) { t.Parallel() - networkName := acctest.BootstrapSharedTestNetwork(t, "tf-test-alloydb-network") - subnetworkName := acctest.BootstrapSubnet(t, "tf-test-alloydb-subnetwork", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "tf-test-alloydb-network") + subnetworkName := tpgcompute.BootstrapSubnet(t, "tf-test-alloydb-subnetwork", networkName) random_suffix := acctest.RandString(t, 10) context := map[string]interface{}{ "random_suffix": random_suffix, - "networkAttachmentName": acctest.BootstrapNetworkAttachment(t, "tf-test-alloydb-update-na", subnetworkName), + "networkAttachmentName": tpgcompute.BootstrapNetworkAttachment(t, "tf-test-alloydb-update-na", subnetworkName), } acctest.VcrTest(t, resource.TestCase{ @@ -1098,7 +1101,7 @@ func TestAccAlloydbInstance_updateInstanceWithPscInterfaceConfigs(t *testing.T) func TestAccAlloydbInstance_updatePscAutoConnections(t *testing.T) { t.Parallel() - networkName := acctest.BootstrapSharedTestNetwork(t, "tf-test-alloydb-network-psc") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "tf-test-alloydb-network-psc") random_suffix := acctest.RandString(t, 10) context := map[string]interface{}{ "network_name": networkName, @@ -1184,8 +1187,8 @@ func TestAccAlloydbInstance_createPrimaryAndReadPoolInstanceWithAllocatedIpRange testId := "alloydb-1" context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "address_name": acctest.BootstrapSharedTestGlobalAddress(t, testId), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, testId), + "address_name": tpgcompute.BootstrapSharedTestGlobalAddress(t, testId), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, testId), } acctest.VcrTest(t, resource.TestCase{ @@ -1258,7 +1261,7 @@ func TestAccAlloydbInstance_connectionPoolConfig(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydbinstance-connection-pool-config") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydbinstance-connection-pool-config") context := map[string]interface{}{ "random_suffix": suffix, @@ -1582,7 +1585,7 @@ data "google_compute_network" "default" { func TestAccAlloydbInstance_ObservabilityConfig_Update(t *testing.T) { t.Parallel() random_suffix := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1") // 1. Initial State: Everything Enabled contextEnableAll := map[string]interface{}{ diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_cluster_test.go b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_cluster_test.go index cce0930c2ee7..6a5f4a115494 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_cluster_test.go +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_cluster_test.go @@ -6,13 +6,17 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) // The cluster creation should succeed with minimal number of arguments func TestAccAlloydbCluster_secondaryClusterMandatoryFields(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -94,7 +98,7 @@ func TestAccAlloydbCluster_secondaryClusterMissingSecondaryConfig(t *testing.T) t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -167,7 +171,7 @@ func TestAccAlloydbCluster_secondaryClusterDefinedSecondaryConfigButMissingClust t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -247,7 +251,7 @@ func TestAccAlloydbCluster_secondaryClusterDefinedSecondaryConfigButClusterTypeI t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -328,7 +332,7 @@ func TestAccAlloydbCluster_secondaryClusterUpdate(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -422,9 +426,9 @@ func TestAccAlloydbCluster_secondaryClusterUsingCMEK(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-bootstrap-alloydb-secondary-key1").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-bootstrap-alloydb-secondary-key1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -518,7 +522,7 @@ func TestAccAlloydbCluster_secondaryClusterWithNetworkConfig(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -600,8 +604,8 @@ func TestAccAlloydbCluster_secondaryClusterWithNetworkConfigAndAllocatedIPRange( t.Parallel() context := map[string]interface{}{ - "address_name": acctest.BootstrapSharedTestGlobalAddress(t, "alloydb-1"), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "address_name": tpgcompute.BootstrapSharedTestGlobalAddress(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -691,7 +695,7 @@ func TestAccAlloydbCluster_secondaryClusterPromote(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-east1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -862,7 +866,7 @@ func TestAccAlloydbCluster_secondaryClusterPromoteAndSimultaneousUpdate(t *testi context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-east1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -966,7 +970,7 @@ func TestAccAlloydbCluster_secondaryClusterPromoteAndDeleteOriginalPrimary(t *te context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-east1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -1055,7 +1059,7 @@ func TestAccAlloydbCluster_secondaryClusterPromoteAndUpdate(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-east1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -1167,8 +1171,8 @@ func TestAccAlloydbCluster_secondaryClusterPromoteWithNetworkConfigAndAllocatedI context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), - "address_name": acctest.BootstrapSharedTestGlobalAddress(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "address_name": tpgcompute.BootstrapSharedTestGlobalAddress(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -1354,7 +1358,7 @@ func TestAccAlloydbCluster_secondaryClusterPromoteAndAddAndDeleteAutomatedBackup context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-south1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "hour": 23, } @@ -1504,7 +1508,7 @@ func TestAccAlloydbCluster_secondaryClusterPromoteAndDeleteTimeBasedRetentionPol context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-south1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -1746,7 +1750,7 @@ func TestAccAlloydbCluster_secondaryClusterPromoteAndAddContinuousBackupConfig(t context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "secondary_cluster_location": "us-south1", - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_instance_test.go b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_instance_test.go index 2e280730bc51..094e2dde4f4a 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_instance_test.go +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_secondary_instance_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) // This test passes if secondary instance's machine config can be updated @@ -13,7 +16,7 @@ func TestAccAlloydbInstance_secondaryInstanceUpdateMachineConfig(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -183,7 +186,7 @@ func TestAccAlloydbInstance_secondaryInstanceWithReadPoolInstance(t *testing.T) context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -287,8 +290,8 @@ func TestAccAlloydbCluster_secondaryInstanceWithNetworkConfigAndAllocatedIPRange context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), - "address_name": acctest.BootstrapSharedTestGlobalAddress(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "address_name": tpgcompute.BootstrapSharedTestGlobalAddress(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -388,7 +391,7 @@ func TestAccAlloydbInstance_secondaryInstanceUpdateDatabaseFlag(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -477,7 +480,7 @@ resource "google_alloydb_instance" "secondary" { } database_flags = { - "alloydb.enable_auto_explain" = "true" + "alloydb.enable_auto_explain" = "true" } } @@ -495,7 +498,7 @@ func TestAccAlloydbInstance_secondaryInstanceUpdateQueryInsightConfig(t *testing context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -605,7 +608,7 @@ func TestAccAlloydbInstance_secondaryInstanceMaximumFields(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_user_test.go b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_user_test.go index e093e9c55086..d7198ba92672 100644 --- a/mmv1/third_party/terraform/services/alloydb/resource_alloydb_user_test.go +++ b/mmv1/third_party/terraform/services/alloydb/resource_alloydb_user_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccAlloydbUser_updateRoles_BuiltIn(t *testing.T) { @@ -18,7 +20,7 @@ func TestAccAlloydbUser_updateRoles_BuiltIn(t *testing.T) { "alloydb_instance_name": "tf-test-alloydb-instance" + randomSuffix, "alloydb_user_name": "user1" + randomSuffix, "alloydb_user_pass": "tf_test_user_secret" + randomSuffix, - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": randomSuffix, } @@ -99,7 +101,7 @@ func TestAccAlloydbUser_updatePassword_BuiltIn(t *testing.T) { "alloydb_instance_name": "tf-test-alloydb-instance" + randomSuffix, "alloydb_user_name": "user1" + randomSuffix, "alloydb_user_pass": "tf_test_user_secret" + randomSuffix, - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": randomSuffix, } @@ -179,7 +181,7 @@ func TestAccAlloydbUser_updateRoles_IAM(t *testing.T) { "alloydb_cluster_pass": "tf_test_cluster_secret" + randomSuffix, "alloydb_instance_name": "tf-test-alloydb-instance" + randomSuffix, "alloydb_user_name": "user2@foo.com" + randomSuffix, - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": randomSuffix, } @@ -251,7 +253,7 @@ func TestAccAlloydbUser_alloydbUserBuiltinWithPasswordWo(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } @@ -314,7 +316,7 @@ func TestAccAlloydbUser_alloydbUserBuiltinWithPasswordWo_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "alloydb-1"), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_config_test.go.tmpl b/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_config_test.go.tmpl index e09ad9e2e227..bc2374321985 100644 --- a/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_config_test.go.tmpl @@ -4,6 +4,7 @@ package apigateway_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigateway" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_test.go.tmpl b/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_test.go.tmpl index e7a910b3297a..969636089649 100644 --- a/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_test.go.tmpl +++ b/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_api_test.go.tmpl @@ -4,6 +4,7 @@ package apigateway_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigateway" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_gateway_test.go.tmpl b/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_gateway_test.go.tmpl index 479b34753ca2..cf322ea2e544 100644 --- a/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_gateway_test.go.tmpl +++ b/mmv1/third_party/terraform/services/apigateway/resource_api_gateway_gateway_test.go.tmpl @@ -4,6 +4,7 @@ package apigateway_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigateway" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_api.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_api.go index 3bc8623bc5e4..27129c7607f3 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_api.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_api.go @@ -34,6 +34,7 @@ func ResourceApigeeApi() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), /* If any of the config_bundle, detect_md5hash or md5hash is changed, then an update is expected, so we tell Terraform core to expect update on meta_data, @@ -133,6 +134,9 @@ func ResourceApigeeApi() *schema.Resource { return true }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -206,6 +210,11 @@ func resourceApigeeApiCreate(d *schema.ResourceData, meta interface{}) error { } func resourceApigeeApiUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceApigeeApi) { + return ResourceApigeeApi().Read(d, meta) + } + //For how API proxy api is implemented, just treat an update as create, when the name is same, it will create a new revision return resourceApigeeApiCreate(d, meta) } @@ -262,6 +271,11 @@ func resourceApigeeApiRead(d *schema.ResourceData, meta interface{}) error { d.Set("md5hash", "UNKNOWN") d.Set("detect_md5hash", "UNKNOWN") } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -284,6 +298,13 @@ func getApigeeApiLastModifiedAt(d *schema.ResourceData) string { } func resourceApigeeApiDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_api_meta.yaml b/mmv1/third_party/terraform/services/apigee/resource_apigee_api_meta.yaml index 386ec1bbe0d9..66e24fa9d4e1 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_api_meta.yaml +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_api_meta.yaml @@ -14,3 +14,5 @@ fields: - api_field: 'name' - field: 'org_id' - api_field: 'revision' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_api_product_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_api_product_update_test.go index 49ef0a6cace3..fa0965e80814 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_api_product_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_api_product_update_test.go @@ -5,6 +5,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "testing" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_api_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_api_test.go index 1c332562be9a..ce8a442929fa 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_api_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_api_test.go @@ -11,6 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_control_plane_access_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_control_plane_access_test.go index 02a33fac2af4..be4039d2a22b 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_control_plane_access_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_control_plane_access_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccApigeeControlPlaneAccess_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_app_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_app_update_test.go index 8efaf1000d82..aa936aa4d094 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_app_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_app_update_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccApigeeDeveloperApp_apigeeDeveloperAppUpdateTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_update_test.go index 8b67866c5ae5..25c8adadeaca 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_developer_update_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeDeveloper_apigeeDeveloperUpdateTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_endpoint_attachment_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_endpoint_attachment_test.go index d75c77c024e1..5ef1d94f1e2c 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_endpoint_attachment_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_endpoint_attachment_test.go @@ -11,6 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -116,7 +119,7 @@ resource "google_compute_forwarding_rule" "psc_ilb_consumer" { target = google_compute_service_attachment.psc_ilb_service_attachment.id load_balancing_scheme = "" # need to override EXTERNAL default when target is a service attachment network = "default" - ip_address = google_compute_address.psc_ilb_consumer_address.address + ip_address = google_compute_address.psc_ilb_consumer_address.id project = google_project.project.project_id } @@ -180,7 +183,7 @@ resource "google_compute_subnetwork" "psc_ilb_nat" { network = google_compute_network.psc_ilb_network.id purpose = "PRIVATE_SERVICE_CONNECT" - ip_cidr_range = "10.0.1.0/24" + ip_cidr_range = "10.0.2.0/24" project = google_project.project.project_id } diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_env_references_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_env_references_test.go index f788bc41f0ae..28701a33b9bd 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_env_references_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_env_references_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeEnvReferences_apigeeEnvironmentReferenceTest_Update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_api_revision_deployment_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_api_revision_deployment_test.go index 80b4cf5cf8cc..8bdf183bb685 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_api_revision_deployment_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_api_revision_deployment_test.go @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_type_test.go.tmpl b/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_type_test.go.tmpl index 21cc9098224f..bd72241a9531 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_type_test.go.tmpl +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_type_test.go.tmpl @@ -6,6 +6,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_update_test.go index 556ae4175f13..3b44dfd00a62 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_environment_update_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeEnvironment_apigeeEnvironmentUpdateTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook.go index 563d84e9258d..2161cc78555e 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook.go @@ -6,6 +6,7 @@ import ( "reflect" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -16,6 +17,7 @@ func ResourceApigeeFlowhook() *schema.Resource { return &schema.Resource{ Create: resourceApigeeFlowhookCreate, Read: resourceApigeeFlowhookRead, + Update: resourceApigeeFlowhookUpdate, Delete: resourceApigeeFlowhookDelete, Importer: &schema.ResourceImporter{ @@ -27,6 +29,10 @@ func ResourceApigeeFlowhook() *schema.Resource { Delete: schema.DefaultTimeout(20 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "description": { Type: schema.TypeString, @@ -65,6 +71,9 @@ func ResourceApigeeFlowhook() *schema.Resource { Default: true, Description: `Flag that specifies whether execution should continue if the flow hook throws an exception. Set to true to continue execution. Set to false to stop execution if the flow hook throws an exception. Defaults to true.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -179,10 +188,29 @@ func resourceApigeeFlowhookRead(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("Error reading Flowhook: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceApigeeFlowhookUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceApigeeFlowhookRead(d, meta) +} + +//UDP update end + func resourceApigeeFlowhookDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_meta.yaml b/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_meta.yaml index 22564c10c27d..d14117eb09f0 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_meta.yaml +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_meta.yaml @@ -10,3 +10,5 @@ fields: - api_field: 'flowHookPoint' - field: 'org_id' - field: 'sharedflow' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_test.go index 988c985be3c7..76b615867862 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_flowhook_test.go @@ -11,6 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_instance_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_instance_update_test.go index cfd47c6b9089..e211da7f9cdf 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_instance_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_instance_update_test.go @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeInstance_updateConsumerAcceptList(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_key_cert_file_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_key_cert_file_test.go index c4a5daa7190f..98600fec2870 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_key_cert_file_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_key_cert_file_test.go @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12.go index 268ce2366f95..b94ee013e485 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12.go @@ -10,6 +10,7 @@ import ( "reflect" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -20,6 +21,7 @@ func ResourceApigeeKeystoresAliasesPkcs12() *schema.Resource { return &schema.Resource{ Create: ResourceApigeeKeystoresAliasesPkcs12Create, Read: ResourceApigeeKeystoresAliasesPkcs12Read, + Update: ResourceApigeeKeystoresAliasesPkcs12Update, Delete: ResourceApigeeKeystoresAliasesPkcs12Delete, Importer: &schema.ResourceImporter{ @@ -31,6 +33,10 @@ func ResourceApigeeKeystoresAliasesPkcs12() *schema.Resource { Delete: schema.DefaultTimeout(20 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "alias": { Type: schema.TypeString, @@ -156,6 +162,9 @@ Flag is set to Yes if the certificate is valid, No if expired, or Not yet if not Computed: true, Description: `Optional.Type of Alias`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -255,10 +264,29 @@ func ResourceApigeeKeystoresAliasesPkcs12Read(d *schema.ResourceData, meta inter return fmt.Errorf("Error reading KeystoreAliasesPkcs: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func ResourceApigeeKeystoresAliasesPkcs12Update(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return ResourceApigeeKeystoresAliasesPkcs12Read(d, meta) +} + +//UDP update end + func ResourceApigeeKeystoresAliasesPkcs12Delete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_meta.yaml b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_meta.yaml index a84e08585112..d1b3e64ec389 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_meta.yaml +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_meta.yaml @@ -23,3 +23,5 @@ fields: - field: 'org_id' - field: 'password' - api_field: 'type' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_test.go index 93122d490f16..0edbab2ab1dc 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_keystores_aliases_pkcs12_test.go @@ -11,6 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_nat_address_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_nat_address_update_test.go index 7395c7f32c2c..89690a069d66 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_nat_address_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_nat_address_update_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeNatAddress_apigeeNatAddressUpdateTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_organization_update_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_organization_update_test.go index a37db5a89c9d..fd151805ff75 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_organization_update_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_organization_update_test.go @@ -9,6 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeOrganization_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_security_action_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_security_action_test.go index 6851e2b739e5..33734def8954 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_security_action_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_security_action_test.go @@ -11,6 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow.go index f7be59caa89a..9371396b7f48 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow.go @@ -34,6 +34,7 @@ func ResourceApigeeSharedFlow() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), /* If any of the config_bundle, detect_md5hash or md5hash is changed, then an update is expected, so we tell Terraform core to expect update on meta_data, @@ -134,6 +135,9 @@ func ResourceApigeeSharedFlow() *schema.Resource { return true }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -205,6 +209,11 @@ func resourceApigeeSharedFlowCreate(d *schema.ResourceData, meta interface{}) er } func resourceApigeeSharedFlowUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceApigeeSharedFlow) { + return ResourceApigeeSharedFlow().Read(d, meta) + } + //For how sharedflow api is implemented, just treat an update as create, when the name is same, it will create a new revision return resourceApigeeSharedFlowCreate(d, meta) } @@ -261,6 +270,11 @@ func resourceApigeeSharedFlowRead(d *schema.ResourceData, meta interface{}) erro d.Set("md5hash", "UNKNOWN") d.Set("detect_md5hash", "UNKNOWN") } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -284,6 +298,13 @@ func getApigeeSharedFlowLastModifiedAt(d *schema.ResourceData) string { func resourceApigeeSharedFlowDelete(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] resourceApigeeSharedFlowDelete") + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment.go index bb8091b997ce..34c1a605d7ed 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment.go @@ -3,8 +3,10 @@ package apigee import ( "fmt" "log" + "strings" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -28,6 +30,10 @@ func ResourceApigeeSharedFlowDeployment() *schema.Resource { Delete: schema.DefaultTimeout(20 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "environment": { Type: schema.TypeString, @@ -58,6 +64,9 @@ func ResourceApigeeSharedFlowDeployment() *schema.Resource { ForceNew: true, Description: `Id of the Sharedflow to be deployed.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -140,6 +149,27 @@ func resourceApigeeSharedflowDeploymentRead(d *schema.ResourceData, meta interfa } log.Printf("[DEBUG] ApigeeSharedflowDeployment deployStartTime %s", res["deployStartTime"]) + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + + // org_id is not returned by the API; it is derived from the resource ID + // (set by Create or by the import parser) and stays in state untouched. + if err := d.Set("environment", flattenApigeeSharedflowDeploymentEnvironment(res["environment"], d, config)); err != nil { + return fmt.Errorf("Error reading SharedflowDeployment: %s", err) + } + // The API uses `apiProxy` for both API proxy and shared flow deployments + // to identify the deployed artifact. + if err := d.Set("sharedflow_id", flattenApigeeSharedflowDeploymentSharedflowId(res["apiProxy"], d, config)); err != nil { + return fmt.Errorf("Error reading SharedflowDeployment: %s", err) + } + if err := d.Set("revision", flattenApigeeSharedflowDeploymentRevision(res["revision"], d, config)); err != nil { + return fmt.Errorf("Error reading SharedflowDeployment: %s", err) + } + if err := d.Set("service_account", flattenApigeeSharedflowDeploymentServiceAccount(res["serviceAccount"], d, config)); err != nil { + return fmt.Errorf("Error reading SharedflowDeployment: %s", err) + } + return nil } @@ -150,6 +180,10 @@ func resourceApigeeSharedflowDeploymentUpdate(d *schema.ResourceData, meta inter return err } + if tpgresource.DeletionPolicyPreUpdate(d, ResourceApigeeSharedFlowDeployment) { + return ResourceApigeeSharedFlowDeployment().Read(d, meta) + } + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"organizations/{{org_id}}/environments/{{environment}}/sharedflows/{{sharedflow_id}}/revisions/{{revision}}/deployments?override=true&serviceAccount={{service_account}}") if err != nil { return err @@ -188,6 +222,13 @@ func resourceApigeeSharedflowDeploymentUpdate(d *schema.ResourceData, meta inter } func resourceApigeeSharedflowDeploymentDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -263,7 +304,19 @@ func flattenApigeeSharedflowDeploymentRevision(v interface{}, d *schema.Resource } func flattenApigeeSharedflowDeploymentServiceAccount(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v + // The Apigee API may return service accounts as a full resource name + // (e.g. "projects/-/serviceAccounts/sa@project.iam.gserviceaccount.com") + // while the schema documents (and Create accepts) the bare email form. + // Strip the prefix when present so a Read after a Create using the bare + // email does not show drift. + if v == nil { + return v + } + s, ok := v.(string) + if !ok { + return v + } + return strings.TrimPrefix(s, "projects/-/serviceAccounts/") } func init() { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_meta.yaml b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_meta.yaml index 727f7bb85556..1b7c68ccf306 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_meta.yaml +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_meta.yaml @@ -9,3 +9,5 @@ fields: - api_field: 'revision' - field: 'service_account' - field: 'sharedflow_id' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_test.go index 747804b3eea8..9d73b8c59dd1 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_deployment_test.go @@ -8,6 +8,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -135,11 +138,18 @@ resource "google_apigee_sharedflow" "test_apigee_sharedflow" { depends_on = [google_apigee_organization.apigee_org] } +resource "google_service_account" "sharedflow_sa" { + account_id = "tf-test-sf-sa%{random_suffix}" + display_name = "TF Test Sharedflow SA" + project = google_project.project.project_id +} + resource "google_apigee_sharedflow_deployment" "sharedflow_deployment_test" { - environment = google_apigee_environment.apigee_environment.name - org_id = google_apigee_sharedflow.test_apigee_sharedflow.org_id - revision = google_apigee_sharedflow.test_apigee_sharedflow.revision[length(google_apigee_sharedflow.test_apigee_sharedflow.revision)-1] - sharedflow_id = google_apigee_sharedflow.test_apigee_sharedflow.name + environment = google_apigee_environment.apigee_environment.name + org_id = google_apigee_sharedflow.test_apigee_sharedflow.org_id + revision = google_apigee_sharedflow.test_apigee_sharedflow.revision[length(google_apigee_sharedflow.test_apigee_sharedflow.revision)-1] + sharedflow_id = google_apigee_sharedflow.test_apigee_sharedflow.name + service_account = google_service_account.sharedflow_sa.email } `, context) } diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_meta.yaml b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_meta.yaml index 2bfc6283ce6b..87d833cb8ec4 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_meta.yaml +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_meta.yaml @@ -14,3 +14,5 @@ fields: - api_field: 'name' - field: 'org_id' - api_field: 'revision' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_test.go index 5dc81123d6e6..2eddbadf5e81 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sharedflow_test.go @@ -11,6 +11,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_space_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_space_test.go index adbc4d8d2fe0..1ce0ad2fe6ba 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_space_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_space_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeSpace_basicTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_sync_authorization_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_sync_authorization_test.go index e297e3171f14..f949cc32c06e 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_sync_authorization_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_sync_authorization_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccApigeeSyncAuthorization_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apigee/resource_apigee_target_server_test.go b/mmv1/third_party/terraform/services/apigee/resource_apigee_target_server_test.go index 96a547f4c488..ff13928e0a72 100644 --- a/mmv1/third_party/terraform/services/apigee/resource_apigee_target_server_test.go +++ b/mmv1/third_party/terraform/services/apigee/resource_apigee_target_server_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccApigeeTargetServer_apigeeTargetServerTest_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apihub/resource_apihub_curation_test.go b/mmv1/third_party/terraform/services/apihub/resource_apihub_curation_test.go index 3c8590b3bcae..94fc5017e5c3 100644 --- a/mmv1/third_party/terraform/services/apihub/resource_apihub_curation_test.go +++ b/mmv1/third_party/terraform/services/apihub/resource_apihub_curation_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/apihub" ) func TestAccApihubCuration_apihubCurationBasic_Update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key.go b/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key.go index 81443af61e01..2bbcc0fc91a9 100644 --- a/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key.go +++ b/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key.go @@ -33,6 +33,7 @@ func ResourceApikeysKey() *schema.Resource { }, CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -86,6 +87,10 @@ func ResourceApikeysKey() *schema.Resource { Computed: true, Description: "Output only. Unique id in UUID4 format.", }, + + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -335,9 +340,18 @@ func resourceApikeysKeyRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting uid in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceApikeysKeyUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceApikeysKey) { + return ResourceApikeysKey().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -385,6 +399,13 @@ func resourceApikeysKeyUpdate(d *schema.ResourceData, meta interface{}) error { } func resourceApikeysKeyDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_generated_test.go b/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_generated_test.go index e92d63798310..e6b20e52a141 100644 --- a/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_generated_test.go +++ b/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_generated_test.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/apikeys" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" dcl "github.com/hashicorp/terraform-provider-google/google/tpgdclresource" ) diff --git a/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_meta.yaml b/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_meta.yaml index e378775095be..4dcb1b97b4f8 100644 --- a/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_meta.yaml +++ b/mmv1/third_party/terraform/services/apikeys/resource_apikeys_key_meta.yaml @@ -17,3 +17,5 @@ fields: - api_field: 'restrictions.serverKeyRestrictions.allowedIps' - api_field: 'uid' - api_field: 'serviceAccountEmail' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/appengine/resource_app_engine_application_test.go b/mmv1/third_party/terraform/services/appengine/resource_app_engine_application_test.go index b69b213d4e53..cb2200312209 100644 --- a/mmv1/third_party/terraform/services/appengine/resource_app_engine_application_test.go +++ b/mmv1/third_party/terraform/services/appengine/resource_app_engine_application_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccAppEngineApplication_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/appengine/resource_app_engine_domain_mapping_test.go b/mmv1/third_party/terraform/services/appengine/resource_app_engine_domain_mapping_test.go index 118c339ec465..da3d3639834d 100644 --- a/mmv1/third_party/terraform/services/appengine/resource_app_engine_domain_mapping_test.go +++ b/mmv1/third_party/terraform/services/appengine/resource_app_engine_domain_mapping_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" ) func TestAccAppEngineDomainMapping_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/appengine/resource_app_engine_flexible_app_version_test.go.tmpl b/mmv1/third_party/terraform/services/appengine/resource_app_engine_flexible_app_version_test.go.tmpl index 141be1e2be7d..c0997589ab8c 100644 --- a/mmv1/third_party/terraform/services/appengine/resource_app_engine_flexible_app_version_test.go.tmpl +++ b/mmv1/third_party/terraform/services/appengine/resource_app_engine_flexible_app_version_test.go.tmpl @@ -10,6 +10,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/appengine/resource_app_engine_service_network_settings_test.go b/mmv1/third_party/terraform/services/appengine/resource_app_engine_service_network_settings_test.go index d70178f5a40b..887e74fc684d 100644 --- a/mmv1/third_party/terraform/services/appengine/resource_app_engine_service_network_settings_test.go +++ b/mmv1/third_party/terraform/services/appengine/resource_app_engine_service_network_settings_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccAppEngineServiceNetworkSettings_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/appengine/resource_app_engine_standard_app_version_test.go b/mmv1/third_party/terraform/services/appengine/resource_app_engine_standard_app_version_test.go index e0dcae079430..93bb97e26c74 100644 --- a/mmv1/third_party/terraform/services/appengine/resource_app_engine_standard_app_version_test.go +++ b/mmv1/third_party/terraform/services/appengine/resource_app_engine_standard_app_version_test.go @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/vpcaccess" ) func TestAccAppEngineStandardAppVersion_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apphub/data_source_apphub_application_test.go b/mmv1/third_party/terraform/services/apphub/data_source_apphub_application_test.go index ae8b526e69b3..bc6b61483fd6 100644 --- a/mmv1/third_party/terraform/services/apphub/data_source_apphub_application_test.go +++ b/mmv1/third_party/terraform/services/apphub/data_source_apphub_application_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" ) func TestAccDataSourceApphubApplication_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service.go b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service.go index 08ba294b8dee..22ff8d1556bd 100644 --- a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service.go +++ b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service.go @@ -76,7 +76,7 @@ func dataSourceApphubDiscoveredServiceRead(d *schema.ResourceData, meta interfac return err } - url, err := tpgresource.ReplaceVars(d, config, "{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/discoveredServices:lookup?uri={{service_uri}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/discoveredServices:lookup?uri={{service_uri}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service_test.go b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service_test.go index 6612c9caa0a7..f48ebc7414ba 100644 --- a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service_test.go +++ b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_service_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceApphubDiscoveredService_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload.go b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload.go index 608f71233c28..14604487c458 100644 --- a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload.go +++ b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload.go @@ -72,7 +72,7 @@ func dataSourceApphubDiscoveredWorkloadRead(d *schema.ResourceData, meta interfa return err } - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/discoveredWorkloads:lookup?uri={{workload_uri}}")) + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/discoveredWorkloads:lookup?uri={{workload_uri}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload_test.go b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload_test.go index d47fd4d35c50..15731a8aa46a 100644 --- a/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload_test.go +++ b/mmv1/third_party/terraform/services/apphub/data_source_apphub_discovered_workload_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceApphubDiscoveredWorkload_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apphub/resource_apphub_application_test.go b/mmv1/third_party/terraform/services/apphub/resource_apphub_application_test.go index 449ceb4fe6c7..65c70ff01855 100644 --- a/mmv1/third_party/terraform/services/apphub/resource_apphub_application_test.go +++ b/mmv1/third_party/terraform/services/apphub/resource_apphub_application_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" ) func TestAccApphubApplication_applicationUpdateFull(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apphub/resource_apphub_boundary_test.go b/mmv1/third_party/terraform/services/apphub/resource_apphub_boundary_test.go index 0ef2f04e60f8..9d473691a9d8 100644 --- a/mmv1/third_party/terraform/services/apphub/resource_apphub_boundary_test.go +++ b/mmv1/third_party/terraform/services/apphub/resource_apphub_boundary_test.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/apphub/resource_apphub_service_test.go b/mmv1/third_party/terraform/services/apphub/resource_apphub_service_test.go index 328b0e78959e..1988b8d3ff7b 100644 --- a/mmv1/third_party/terraform/services/apphub/resource_apphub_service_test.go +++ b/mmv1/third_party/terraform/services/apphub/resource_apphub_service_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccApphubService_serviceUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/apphub/resource_apphub_workload_test.go b/mmv1/third_party/terraform/services/apphub/resource_apphub_workload_test.go index 4ce544d42045..b5bf24c27e89 100644 --- a/mmv1/third_party/terraform/services/apphub/resource_apphub_workload_test.go +++ b/mmv1/third_party/terraform/services/apphub/resource_apphub_workload_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccApphubWorkload_apphubWorkloadUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_image.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_image.go index a5beb32a07f7..8fd363ef1ce3 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_image.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_image.go @@ -109,7 +109,7 @@ func DataSourceArtifactRegistryDockerImageRead(d *schema.ResourceData, meta inte // fetch image by digest // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.dockerImages/get imageUrlSafe := url.QueryEscape(imageName) - urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/dockerImages/%s@%s", imageUrlSafe, digest)) + urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/dockerImages/%s@%s", imageUrlSafe, digest)) if err != nil { return fmt.Errorf("Error setting api endpoint") } @@ -128,7 +128,7 @@ func DataSourceArtifactRegistryDockerImageRead(d *schema.ResourceData, meta inte } else { // fetch the list of images, ordered by update time // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.dockerImages/list - urlRequest, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/dockerImages") + urlRequest, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/dockerImages") if err != nil { return fmt.Errorf("Error setting api endpoint") } @@ -178,7 +178,7 @@ func DataSourceArtifactRegistryDockerImageRead(d *schema.ResourceData, meta inte return fmt.Errorf("Error setting update_time: %s", err) } - id, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/dockerImages/{{image_name}}") + id, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/dockerImages/{{image_name}}") if err != nil { return fmt.Errorf("Error constructing the data source id: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_images.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_images.go index 1bffb7bb54b7..276fa267019c 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_images.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_docker_images.go @@ -89,7 +89,7 @@ func dataSourceArtifactRegistryDockerImagesRead(d *schema.ResourceData, meta int return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifact.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifact.go index e7803ade54eb..9403ea6545cb 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifact.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifact.go @@ -94,7 +94,7 @@ func DataSourceArtifactRegistryMavenArtifactRead(d *schema.ResourceData, meta in // fetch package by version // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.mavenArtifacts/get packageUrlSafe := url.QueryEscape(packageName) - urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/mavenArtifacts/%s:%s", packageUrlSafe, version)) + urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/mavenArtifacts/%s:%s", packageUrlSafe, version)) if err != nil { return fmt.Errorf("Error setting api endpoint") } @@ -113,7 +113,7 @@ func DataSourceArtifactRegistryMavenArtifactRead(d *schema.ResourceData, meta in } else { // fetch the list of packages, ordered by update time // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.mavenArtifacts/list - urlRequest, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/mavenArtifacts") + urlRequest, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/mavenArtifacts") if err != nil { return fmt.Errorf("Error setting api endpoint") } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifacts.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifacts.go index fbf665e7a0a3..c088c4d6ac6f 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifacts.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_maven_artifacts.go @@ -79,7 +79,7 @@ func dataSourceArtifactRegistryMavenArtifactsRead(d *schema.ResourceData, meta i return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_package.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_package.go index 159b9bf1086d..80930d104b5f 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_package.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_package.go @@ -97,7 +97,7 @@ func DataSourceArtifactRegistryNpmPackageRead(d *schema.ResourceData, meta inter // fetch package by version // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.npmPackages/get packageUrlSafe := url.QueryEscape(packageName) - urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/npmPackages/%s:%s", packageUrlSafe, version)) + urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/npmPackages/%s:%s", packageUrlSafe, version)) if err != nil { return fmt.Errorf("Error setting api endpoint") } @@ -116,7 +116,7 @@ func DataSourceArtifactRegistryNpmPackageRead(d *schema.ResourceData, meta inter } else { // fetch the list of packages, ordered by update time // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.npmPackages/list - urlRequest, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/npmPackages") + urlRequest, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/npmPackages") if err != nil { return fmt.Errorf("Error setting api endpoint") } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_packages.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_packages.go index 6f75b2e62aee..105ee57caff1 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_packages.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_npm_packages.go @@ -83,7 +83,7 @@ func dataSourceArtifactRegistryNpmPackagesRead(d *schema.ResourceData, meta inte return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_package.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_package.go index dd2a54766857..071141d55ee6 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_package.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_package.go @@ -65,7 +65,7 @@ func DataSourceArtifactRegistryPackageRead(d *schema.ResourceData, meta interfac return fmt.Errorf("Error setting Artifact Registry project: %s", err) } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_packages.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_packages.go index 07feb2cad0ff..7a0e77f2c71d 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_packages.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_packages.go @@ -76,7 +76,7 @@ func dataSourceArtifactRegistryPackagesRead(d *schema.ResourceData, meta interfa return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_package.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_package.go index ccb1067f47ae..1bfa596e42b9 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_package.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_package.go @@ -90,7 +90,7 @@ func DataSourceArtifactRegistryPythonPackageRead(d *schema.ResourceData, meta in // fetch package by version // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.pythonPackages/get packageUrlSafe := url.QueryEscape(packageName) - urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/pythonPackages/%s:%s", packageUrlSafe, version)) + urlRequest, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/pythonPackages/%s:%s", packageUrlSafe, version)) if err != nil { return fmt.Errorf("Error setting api endpoint") } @@ -109,7 +109,7 @@ func DataSourceArtifactRegistryPythonPackageRead(d *schema.ResourceData, meta in } else { // fetch the list of packages, ordered by update time // https://cloud.google.com/artifact-registry/docs/reference/rest/v1/projects.locations.repositories.pythonPackages/list - urlRequest, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/pythonPackages") + urlRequest, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/repositories/{{repository_id}}/pythonPackages") if err != nil { return fmt.Errorf("Error setting api endpoint") } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_packages.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_packages.go index 498657e08497..855c1d0d5a6f 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_packages.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_python_packages.go @@ -72,7 +72,7 @@ func dataSourceArtifactRegistryPythonPackagesRead(d *schema.ResourceData, meta i return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories.go index 62d09421fca0..8dfd0bec9a64 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories.go @@ -75,7 +75,7 @@ func dataSourceArtifactRegistryRepositoriesRead(d *schema.ResourceData, meta int return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories_test.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories_test.go index cb569bbbe419..67ed5e0e10c5 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories_test.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repositories_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" ) func TestAccDataSourceArtifactRegistryRepositories_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repository_test.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repository_test.go index f42229cb0be2..ba2b4dff350c 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repository_test.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_repository_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" ) func TestAccDataSourceGoogleArtifactRegistryRepositoryConfig(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tag.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tag.go index c12c3a28f58e..b55aed0bd1c9 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tag.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tag.go @@ -60,7 +60,7 @@ func DataSourceArtifactRegistryTagRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error setting Artifact Registry project: %s", err) } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tags.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tags.go index 7eac2825a387..ab7180734b96 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tags.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_tags.go @@ -67,7 +67,7 @@ func dataSourceArtifactRegistryTagsRead(d *schema.ResourceData, meta interface{} return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_version.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_version.go index f8e178e17a02..10534a20c1e3 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_version.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_version.go @@ -95,7 +95,7 @@ func DataSourceArtifactRegistryVersionRead(d *schema.ResourceData, meta interfac return fmt.Errorf("Error setting Artifact Registry project: %s", err) } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_versions.go b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_versions.go index f549e3ad0635..c705a8c7115f 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_versions.go +++ b/mmv1/third_party/terraform/services/artifactregistry/data_source_artifact_registry_versions.go @@ -102,7 +102,7 @@ func dataSourceArtifactRegistryVersionsRead(d *schema.ResourceData, meta interfa return err } - basePath, err := tpgresource.ReplaceVars(d, config, "{{ArtifactRegistryBasePath}}") + basePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("Error setting Artifact Registry base path: %s", err) } diff --git a/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_repository_test.go.tmpl b/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_repository_test.go.tmpl index 0c3054ef311b..324a8e39c4e3 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_repository_test.go.tmpl +++ b/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_repository_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_rule_test.go b/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_rule_test.go index 954587326933..ea604ab48410 100644 --- a/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_rule_test.go +++ b/mmv1/third_party/terraform/services/artifactregistry/resource_artifact_registry_rule_test.go @@ -30,6 +30,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload.go.tmpl b/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload.go.tmpl index 4969975c90b4..777e182a2ae5 100644 --- a/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload.go.tmpl +++ b/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload.go.tmpl @@ -32,6 +32,7 @@ func ResourceAssuredWorkloadsWorkload() *schema.Resource { }, CustomizeDiff: customdiff.All( tpgresource.SetLabelsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -216,6 +217,9 @@ func ResourceAssuredWorkloadsWorkload() *schema.Resource { Computed: true, Description: "The combination of labels configured directly on the resource and default labels configured on the provider.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -576,10 +580,20 @@ func resourceAssuredWorkloadsWorkloadRead(d *schema.ResourceData, meta interface if err = d.Set("terraform_labels", flattenAssuredWorkloadsWorkloadTerraformLabels(res.Labels, d)); err != nil { return fmt.Errorf("error setting terraform_labels in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceAssuredWorkloadsWorkloadUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceAssuredWorkloadsWorkload) { + return ResourceAssuredWorkloadsWorkload().Read(d, meta) + } + config := meta.(*transport_tpg.Config) obj := &Workload{ @@ -654,6 +668,13 @@ func resourceAssuredWorkloadsWorkloadUpdate(d *schema.ResourceData, meta interfa } func resourceAssuredWorkloadsWorkloadDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) obj := &Workload{ diff --git a/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_generated_test.go.tmpl b/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_generated_test.go.tmpl index 5bc2a6dcf258..3ab774544eb5 100644 --- a/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_generated_test.go.tmpl +++ b/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_generated_test.go.tmpl @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/assuredworkloads" dcl "github.com/hashicorp/terraform-provider-google/google/tpgdclresource" diff --git a/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_meta.yaml.tmpl b/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_meta.yaml.tmpl index 45d8544b3e16..c79de60db2b2 100644 --- a/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/assuredworkloads/resource_assured_workloads_workload_meta.yaml.tmpl @@ -47,3 +47,5 @@ fields: provider_only: true - api_field: 'violationNotificationsEnabled' - api_field: 'workloadOptions.kajEnrollmentType' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/backupdr/bootstrap_test_utils.go b/mmv1/third_party/terraform/services/backupdr/bootstrap_test_utils.go new file mode 100644 index 000000000000..bc2dfcb47be8 --- /dev/null +++ b/mmv1/third_party/terraform/services/backupdr/bootstrap_test_utils.go @@ -0,0 +1,101 @@ +package backupdr + +import ( + "context" + "fmt" + "log" + "testing" + "time" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + backupdr "google.golang.org/api/backupdr/v1" +) + +// waitForBackupdrOperation polls the operation until it is done or times out. +func waitForBackupdrOperation(ctx context.Context, t *testing.T, backupdrService *backupdr.Service, op *backupdr.Operation) (*backupdr.Operation, error) { + t.Helper() + opService := backupdr.NewProjectsLocationsOperationsService(backupdrService) + ticker := time.NewTicker(5 * time.Second) // Poll every 5 seconds + defer ticker.Stop() + + const timeout = 5 * time.Minute // Maximum time to wait + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + for { + select { + case <-ctx.Done(): + return nil, fmt.Errorf("timed out waiting for operation %s to complete", op.Name) + case <-ticker.C: + latestOp, err := opService.Get(op.Name).Context(ctx).Do() + if err != nil { + // Retry on transient errors if necessary, fail on others. + return nil, fmt.Errorf("error getting operation %s: %w", op.Name, err) + } + op = latestOp + t.Logf("Operation %s status: Done=%v", op.Name, op.Done) + + if op.Done { + if op.Error != nil { + return op, fmt.Errorf("operation %s failed: %v (code %d)", op.Name, op.Error.Message, op.Error.Code) + } + t.Logf("Operation %s completed successfully.", op.Name) + return op, nil + } + } + } +} + +// BootstrapBackupDRVault creates or gets a BackupDR backup vault for testing. +func BootstrapBackupDRVault(t *testing.T, vaultID, location string) string { + ctx := context.Background() + project := envvar.GetTestProjectFromEnv() + config := transport_tpg.BootstrapConfig(t) + if config == nil { + t.Fatal("Could not bootstrap config.") + } + + // Create a backupdr client and check if the vault exists, if not create a vault + // backupdrClient := NewClient(config, config.UserAgent) + vaultName := fmt.Sprintf("projects/%s/locations/%s/backupVaults/%s", project, location, vaultID) + projectAndLocation := fmt.Sprintf("projects/%s/locations/%s", project, location) + + log.Printf("[DEBUG] Getting BackupDR vault %q", vaultName) + backupdrService := NewClient(config, config.UserAgent) + _, err := backupdrService.Projects.Locations.BackupVaults.Get(vaultName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] BackupDR vault %q not found, bootstrapping", vaultName) + // Prepare the request body for BackupVault creation + enforcedRetentionDays := 1 + effectiveDays := 1 + + retentionDuration := time.Duration(enforcedRetentionDays) * 24 * time.Hour + effectiveTime := time.Now().Add(time.Duration(effectiveDays) * 24 * time.Hour) + + backupVault := &backupdr.BackupVault{ + BackupMinimumEnforcedRetentionDuration: fmt.Sprintf("%ds", int(retentionDuration.Seconds())), + EffectiveTime: effectiveTime.Format(time.RFC3339), + Description: "Created by BootstrapBackupDRVault function", + } + /* _, err = NewClient(config, config.UserAgent).Projects.Locations.BackupVaults.Create(projectAndLocation, backupVault).Do() */ + createCall := backupdrService.Projects.Locations.BackupVaults.Create(projectAndLocation, backupVault) + createCall.BackupVaultId(vaultID) // *** This is REQUIRED for the query parameter *** + // createCall.ValidateOnly(false) // Optional: explicit validate only flag + op, err := createCall.Do() + if err != nil { + t.Fatalf("Error calling Create BackupDR vault %q: %s", vaultName, err) + } + fmt.Printf("Successfully initiated creation of BackupDR vault %q (Operation: %s)\n", vaultName, op.Name) + + // *** WAIT FOR COMPLETION *** + if _, err := waitForBackupdrOperation(ctx, t, backupdrService, op); err != nil { + t.Fatalf("Create operation for %s failed: %v", vaultName, err) + } + fmt.Printf("Successfully created BackupDR vault %q\n", vaultName) + + } + + return vaultName +} diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup.go.tmpl b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup.go.tmpl index 93c0f19c896b..af68d4d7d86f 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup.go.tmpl +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup.go.tmpl @@ -51,6 +51,35 @@ func DataSourceGoogleCloudBackupDRBackup() *schema.Resource { Computed: true, Description: `The time when the backup was created.`, }, + "disk_backup_properties": { + Type: schema.TypeList, + Computed: true, + Description: `Disk related properties of the backup.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guest_flush": { + Type: schema.TypeBool, + Computed: true, + Description: `Indicates whether the backup is application-consistent.`, + }, + }, + }, + }, + "compute_instance_backup_properties": { + Type: schema.TypeList, + Computed: true, + Description: `Compute instance related properties of the backup.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guest_flush": { + Type: schema.TypeBool, + Computed: true, + Description: `Indicates if the backup was created with guest flush enabled.`, + }, + }, + }, + }, + }, }, }, @@ -158,6 +187,8 @@ func flattenDataSourceBackupDRBackups(v interface{}, d *schema.ResourceData, con "backup_vault_id": flattenDataSourceBackupDRBackupsBackupVaultId(original["backupVaultId"], d, config), "data_source_id": flattenDataSourceBackupDRBackupsDataSourceId(original["dataSourceId"], d, config), "create_time": flattenDataSourceBackupDRBackupsCreateTime(original["createTime"], d, config), + "disk_backup_properties": flattenDataSourceBackupDRBackupsDiskBackupProperties(original["diskBackupProperties"], d, config), + "compute_instance_backup_properties": flattenDataSourceBackupDRBackupsComputeInstanceBackupProperties(original["computeInstanceBackupProperties"], d, config), }) } return transformed @@ -186,6 +217,42 @@ func flattenDataSourceBackupDRBackupsDataSourceId(v interface{}, d *schema.Resou func flattenDataSourceBackupDRBackupsCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { return v } + +func flattenDataSourceBackupDRBackupsComputeInstanceBackupProperties(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original, ok := v.(map[string]interface{}) + if !ok || len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["guest_flush"] = flattenDataSourceBackupDRBackupsComputeInstanceBackupPropertiesGuestFlush(original["guestFlush"], d, config) + return []interface{}{transformed} +} + +func flattenDataSourceBackupDRBackupsComputeInstanceBackupPropertiesGuestFlush(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDataSourceBackupDRBackupsDiskBackupProperties(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original, ok := v.(map[string]interface{}) + if !ok || len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["guest_flush"] = flattenDataSourceBackupDRBackupsDiskBackupPropertiesGuestFlush(original["guestFlush"], d, config) + return []interface{}{transformed} +} + +func flattenDataSourceBackupDRBackupsDiskBackupPropertiesGuestFlush(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + + func init() { registry.Schema{ Name: "google_backup_dr_backup", diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_association_test.go b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_association_test.go index 9d5b90d192c5..19d06a1d9bee 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_association_test.go +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_association_test.go @@ -9,6 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceGoogleBackupDRBackupPlanAssociation_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_test.go b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_test.go index 46dda3a3af98..84ffb2e932ab 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_test.go +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_plan_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" ) func TestAccDataSourceGoogleBackupDRBackupPlan_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_vault_test.go b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_vault_test.go index 0aaf73d63ca9..602f6611b313 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_vault_test.go +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_backup_vault_test.go @@ -3,6 +3,7 @@ package backupdr_test import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" "testing" ) diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_data_source_reference_test.go b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_data_source_reference_test.go index 9990c60e9c41..4dc8a61746a8 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_data_source_reference_test.go +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_data_source_reference_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceGoogleBackupDRDataSourceReferences_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server.go b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server.go index 5aefe3063923..d096762954c9 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server.go +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server.go @@ -75,7 +75,7 @@ func dataSourceGoogleCloudBackupDRServiceRead(d *schema.ResourceData, meta inter return err } billingProject := project - url, err := tpgresource.ReplaceVars(d, config, `{{BackupDRBasePath}}projects/{{project}}/locations/{{location}}/managementServers`) + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+`projects/{{project}}/locations/{{location}}/managementServers`) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server_test.go b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server_test.go index 3953b1a85fc7..c8365823c6ae 100644 --- a/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server_test.go +++ b/mmv1/third_party/terraform/services/backupdr/data_source_backup_dr_management_server_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -16,7 +18,7 @@ func TestAccDataSourceGoogleBackupDRManagementServer_basic(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "backupdr-managementserver-basic"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "backupdr-managementserver-basic"), "random_suffix": acctest.RandString(t, 10), } @@ -48,7 +50,7 @@ func testAccCheckBackupDRManagementServerDestroyProducer(t *testing.T) func(s *t config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, `{{BackupDRBasePath}}projects/{{project}}/locations/{{location}}/managementServers/{{name}}`) + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(backupdr.Product, config)+`projects/{{project}}/locations/{{location}}/managementServers/{{name}}`) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_association_test.go b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_association_test.go index 492dcce0fc91..9134aff74d0a 100644 --- a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_association_test.go +++ b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_association_test.go @@ -4,6 +4,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "testing" "time" ) diff --git a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_test.go b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_test.go index d77e10f19456..c18022d4c060 100644 --- a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_test.go +++ b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_plan_test.go @@ -4,6 +4,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "testing" ) @@ -185,7 +188,9 @@ resource "google_backup_dr_backup_plan" "bp" { resource_type = "compute.googleapis.com/Instance" backup_vault = google_backup_dr_backup_vault.my-backup-vault.name max_custom_on_demand_retention_days = 45 - + compute_instance_backup_plan_properties { + guest_flush = true + } backup_rules { rule_id = "rule-1" backup_retention_days = 366 @@ -219,3 +224,92 @@ resource "google_backup_dr_backup_plan" "bp" { } `, context) } + +func TestAccBackupDRBackupPlan_diskUpdate(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "project": envvar.GetTestProjectFromEnv(), + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: testAccBackupDRBackupPlan_diskCreate(context), + }, + { + Config: testAccBackupDRBackupPlan_diskUpdate(context), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_backup_dr_backup_plan.bp", "disk_backup_plan_properties.0.guest_flush", "true"), + ), + }, + }, + }) +} + +func testAccBackupDRBackupPlan_diskCreate(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_backup_dr_backup_vault" "vault" { + location = "us-central1" + backup_vault_id = "tf-test-bv-%{random_suffix}" + backup_minimum_enforced_retention_duration = "100000s" +} + +resource "google_backup_dr_backup_plan" "bp" { + location = "us-central1" + backup_plan_id = "tf-test-bp-%{random_suffix}" + resource_type = "compute.googleapis.com/Disk" + backup_vault = google_backup_dr_backup_vault.vault.id + + backup_rules { + rule_id = "rule-1" + backup_retention_days = 7 + standard_schedule { + recurrence_type = "DAILY" + time_zone = "UTC" + backup_window { + start_hour_of_day = 0 + end_hour_of_day = 24 + } + } + } +} +`, context) +} + +func testAccBackupDRBackupPlan_diskUpdate(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_backup_dr_backup_vault" "vault" { + location = "us-central1" + backup_vault_id = "tf-test-bv-%{random_suffix}" + backup_minimum_enforced_retention_duration = "100000s" +} + +resource "google_backup_dr_backup_plan" "bp" { + location = "us-central1" + backup_plan_id = "tf-test-bp-%{random_suffix}" + resource_type = "compute.googleapis.com/Disk" + backup_vault = google_backup_dr_backup_vault.vault.id + + backup_rules { + rule_id = "rule-1" + backup_retention_days = 7 + standard_schedule { + recurrence_type = "DAILY" + time_zone = "UTC" + backup_window { + start_hour_of_day = 0 + end_hour_of_day = 24 + } + } + } + + disk_backup_plan_properties { + guest_flush = true + } +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_vault_test.go b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_vault_test.go index 33d24d8ba32a..e1e3c3273819 100644 --- a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_vault_test.go +++ b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_backup_vault_test.go @@ -4,6 +4,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" "testing" "time" ) diff --git a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_restore_workload_test.go b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_restore_workload_test.go index caca0fe9fbff..719fcd708131 100644 --- a/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_restore_workload_test.go +++ b/mmv1/third_party/terraform/services/backupdr/resource_backup_dr_restore_workload_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/backupdr" ) // This test cannot be run locally without seeding your environment with a backup vault and scheduling diff --git a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connection_test.go b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connection_test.go index 49c4057c5b3d..1fcae4943086 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connection_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connection_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleBeyondcorpAppConnection_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connector_test.go b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connector_test.go index 1b59f280ddad..56e8f76dcb86 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connector_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_connector_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleBeyondcorpAppConnector_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_gateway_test.go b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_gateway_test.go index 5aebf887c5f0..9dec90d30fb7 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_gateway_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_app_gateway_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" ) func TestAccDataSourceGoogleBeyondcorpAppGateway_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_security_gateway_test.go b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_security_gateway_test.go index 8ce0c344addb..b9f90f2c4465 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_security_gateway_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/data_source_google_beyondcorp_security_gateway_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" ) func TestAccDataSourceGoogleBeyondcorpSecurityGateway_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connection_test.go b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connection_test.go index f94f1dd1260f..1d7a422b5d4d 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connection_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connection_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccBeyondcorpAppConnection_beyondcorpAppConnectionUpdateExample(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connector_test.go b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connector_test.go index 433e7798aa33..0423f5706163 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connector_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_app_connector_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccBeyondcorpAppConnector_beyondcorpAppConnectorUpdateExample(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_application_test.go b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_application_test.go index af5d58d0e6e6..77bbb07c2f1a 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_application_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_application_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" ) func TestAccBeyondcorpSecurityGatewayApplication_beyondcorpSecurityGatewayApplicationBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_test.go b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_test.go index 1501a793dec5..8907778d2895 100644 --- a/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_test.go +++ b/mmv1/third_party/terraform/services/beyondcorp/resource_beyondcorp_security_gateway_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" ) func TestAccBeyondcorpSecurityGateway_beyondcorpSecurityGatewayBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/biglake/resource_biglake_database_test.go b/mmv1/third_party/terraform/services/biglake/resource_biglake_database_test.go index 8485f0512eb9..fe68d8c05023 100644 --- a/mmv1/third_party/terraform/services/biglake/resource_biglake_database_test.go +++ b/mmv1/third_party/terraform/services/biglake/resource_biglake_database_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/biglake" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccBiglakeDatabase_biglakeDatabase_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/biglake/resource_biglake_table_test.go b/mmv1/third_party/terraform/services/biglake/resource_biglake_table_test.go index 86eb82dbab8c..c5dfa6397a84 100644 --- a/mmv1/third_party/terraform/services/biglake/resource_biglake_table_test.go +++ b/mmv1/third_party/terraform/services/biglake/resource_biglake_table_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/biglake" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccBiglakeTable_biglakeTable_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_catalog_test.go b/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_catalog_test.go index 6e7964c50bef..da4f3e52c282 100644 --- a/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_catalog_test.go +++ b/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_catalog_test.go @@ -28,6 +28,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/biglakeiceberg" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_namespace_test.go b/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_namespace_test.go index be7ca6fad1fc..fcb8817fa0c4 100644 --- a/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_namespace_test.go +++ b/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_namespace_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/biglakeiceberg" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccBiglakeIcebergIcebergNamespace_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_table_test.go b/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_table_test.go index deac2eb4b9ea..5e308a3f4720 100644 --- a/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_table_test.go +++ b/mmv1/third_party/terraform/services/biglakeiceberg/resource_biglake_iceberg_table_test.go @@ -1,6 +1,3 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - package biglakeiceberg_test import ( @@ -10,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/biglakeiceberg" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccBiglakeIcebergIcebergTable_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_dataset_test.go b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_dataset_test.go index f61ebc500c86..77908dc7413f 100644 --- a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_dataset_test.go +++ b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_dataset_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" ) func TestAccDataSourceGoogleBigqueryDataset_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets.go b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets.go index 660e5c2be1fe..d3557d84544c 100644 --- a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets.go +++ b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets.go @@ -72,7 +72,7 @@ func DataSourceGoogleBigQueryDatasetsRead(d *schema.ResourceData, meta interface datasets := make([]map[string]interface{}, 0) for { - url, err := tpgresource.ReplaceVars(d, config, "{{BigQueryBasePath}}projects/{{project}}/datasets") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/datasets") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets_test.go b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets_test.go index 74146ee7a310..f2f33309b8aa 100644 --- a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets_test.go +++ b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_datasets_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleBigqueryDatasets_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_table_test.go b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_table_test.go index 906978facf6b..77fd3b992745 100644 --- a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_table_test.go +++ b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_table_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/datacatalog" ) func TestAccDataSourceGoogleBigqueryTable_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables.go b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables.go index 2825b9edce68..b03e27aad584 100644 --- a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables.go +++ b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables.go @@ -70,7 +70,7 @@ func DataSourceGoogleBigQueryTablesRead(d *schema.ResourceData, meta interface{} for { - url, err := tpgresource.ReplaceVars(d, config, "{{BigQueryBasePath}}projects/{{project}}/datasets/{{dataset_id}}/tables") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/datasets/{{dataset_id}}/tables") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables_test.go b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables_test.go index cd21b8ad6b7b..5604b0ee8cf1 100644 --- a/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables_test.go +++ b/mmv1/third_party/terraform/services/bigquery/data_source_google_bigquery_tables_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" ) func TestAccDataSourceGoogleBigqueryTables_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_access_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_access_test.go index 92fbc6d90570..7b7499f586f1 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_access_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_access_test.go @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -358,7 +361,7 @@ func testAccCheckBigQueryDatasetAccess(t *testing.T, n string, expected map[stri } config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{BigQueryBasePath}}projects/{{project}}/datasets/{{dataset_id}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(bigquery.Product, config)+"projects/{{project}}/datasets/{{dataset_id}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_member_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_member_test.go index 419379a14e4a..8ad65603c526 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_member_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_member_test.go @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -235,7 +238,7 @@ func testAccCheckBigQueryDatasetIamMember(t *testing.T, n string, expected map[s } config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{BigQueryBasePath}}projects/{{project}}/datasets/{{dataset_id}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(bigquery.Product, config)+"projects/{{project}}/datasets/{{dataset_id}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_test.go index 5d80a9037730..5834eb94b6a1 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_iam_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccBigqueryDatasetIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_test.go index b6254e9d2b32..30e93766fcd1 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_dataset_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" bigquery_tpg "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "google.golang.org/api/bigquery/v2" "regexp" "strings" @@ -389,7 +391,7 @@ func TestAccBigQueryDataset_regionalLocation(t *testing.T) { func TestAccBigQueryDataset_cmek(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKeyInLocation(t, "us") + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us") pid := envvar.GetTestProjectFromEnv() datasetID1 := fmt.Sprintf("tf_test_%s", acctest.RandString(t, 10)) @@ -398,7 +400,7 @@ func TestAccBigQueryDataset_cmek(t *testing.T) { ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ { - Config: testAccBigQueryDataset_cmek(pid, datasetID1, kms.CryptoKey.Name), + Config: testAccBigQueryDataset_cmek(pid, datasetID1, bootstrapped.CryptoKey.Name), }, { ResourceName: "google_bigquery_dataset.test", diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_job_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_job_test.go index 419c879490a2..d3f8b68a7dd6 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_job_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_job_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" ) func TestAccBigQueryJob_withLocation(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_routine_test.go.tmpl b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_routine_test.go.tmpl index 2d2438eeb43a..479131cfa213 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_routine_test.go.tmpl +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_routine_test.go.tmpl @@ -9,6 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" {{- end }} "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryconnection" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions2" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" ) func TestAccBigQueryRoutine_bigQueryRoutine_Update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_row_access_policy_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_row_access_policy_test.go index e64cc01563e3..fab61a195cef 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_row_access_policy_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_row_access_policy_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" ) func TestAccBigQueryRowAccessPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table.go.tmpl b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table.go.tmpl index 1ec563438a98..666163f54bc4 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table.go.tmpl +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table.go.tmpl @@ -686,6 +686,7 @@ func ResourceBigQueryTable() *schema.Resource { State: resourceBigQueryTableImport, }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, resourceBigQueryTableSchemaCustomizeDiff, tpgresource.SetLabelsDiff, @@ -1837,6 +1838,9 @@ func ResourceBigQueryTable() *schema.Resource { }, }, }, +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -2382,6 +2386,11 @@ func resourceBigQueryTableRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error setting external_catalog_table_options: %s", err) } } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } @@ -2413,7 +2422,7 @@ func addAutoGenSchemaFields(d *schema.ResourceData, table *bigquery.Table) error func resourceBigQueryTableUpdate(d *schema.ResourceData, meta interface{}) error { // If only client-side fields were modified, short-circuit the Update function to avoid sending an update API request. - clientSideFields := map[string]bool{"deletion_protection": true, "ignore_schema_changes": true, "ignore_auto_generated_schema": true, "table_metadata_view": true} + clientSideFields := map[string]bool{"deletion_protection": true, "ignore_schema_changes": true, "ignore_auto_generated_schema": true, "table_metadata_view": true, "deletion_policy": true} clientSideOnly := true for field := range ResourceBigQueryTable().Schema { if d.HasChange(field) && !clientSideFields[field] { @@ -2553,6 +2562,13 @@ func resourceBigQueryTableColumnDrop(config *transport_tpg.Config, userAgent str } func resourceBigQueryTableDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + if d.Get("deletion_protection").(bool) { return fmt.Errorf("cannot destroy table %v without setting deletion_protection=false and running `terraform apply`", d.Id()) } diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_meta.yaml b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_meta.yaml index 768050c65bcf..95bd7082d5a5 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_meta.yaml +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_meta.yaml @@ -134,3 +134,5 @@ fields: - api_field: 'type' - api_field: 'view.query' - api_field: 'view.useLegacySql' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_test.go b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_test.go index 785e05091dcb..234c93b2c915 100644 --- a/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_test.go +++ b/mmv1/third_party/terraform/services/bigquery/resource_bigquery_table_test.go @@ -11,6 +11,14 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryconnection" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquerydatapolicy" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" + _ "github.com/hashicorp/terraform-provider-google/google/services/datacatalog" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccBigQueryTable_Basic(t *testing.T) { @@ -262,8 +270,8 @@ func TestAccBigQueryTable_Kms(t *testing.T) { resourceName := "google_bigquery_table.test" datasetID := fmt.Sprintf("tf_test_%s", acctest.RandString(t, 10)) tableID := fmt.Sprintf("tf_test_%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKey(t) - cryptoKeyName := kms.CryptoKey.Name + boostrapped := kms.BootstrapKMSKey(t) + cryptoKeyName := boostrapped.CryptoKey.Name acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchange_test.go b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchange_test.go index 13345226e328..ae2b91a06489 100644 --- a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchange_test.go +++ b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchange_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryanalyticshub" ) func TestAccBigqueryAnalyticsHubDataExchange_bigqueryAnalyticshubPublicDataExchangeUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchangesubscription_test.go.tmpl b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchangesubscription_test.go.tmpl index 878cccb7c96e..fcb5df3cdd00 100644 --- a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchangesubscription_test.go.tmpl +++ b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_dataexchangesubscription_test.go.tmpl @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryanalyticshub" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" ) func TestAccBigqueryAnalyticsHubDataExchangeSubscription_bigqueryAnalyticshubDataexchangeSubscriptionUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_subscription_test.go b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_subscription_test.go index 33e443947502..87629b3cb999 100644 --- a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_subscription_test.go +++ b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_subscription_test.go @@ -16,6 +16,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryanalyticshub" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_test.go b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_test.go index db463fd14d98..63d8eaad6565 100644 --- a/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_test.go +++ b/mmv1/third_party/terraform/services/bigqueryanalyticshub/resource_bigquery_analytics_hub_listing_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryanalyticshub" ) // Dummy usages to ensure imports are satisfied in both versions diff --git a/mmv1/third_party/terraform/services/bigqueryconnection/resource_bigquery_connection_test.go b/mmv1/third_party/terraform/services/bigqueryconnection/resource_bigquery_connection_test.go index 07d67bee341f..ae50a62d30fd 100644 --- a/mmv1/third_party/terraform/services/bigqueryconnection/resource_bigquery_connection_test.go +++ b/mmv1/third_party/terraform/services/bigqueryconnection/resource_bigquery_connection_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryconnection" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccBigqueryConnectionConnection_bigqueryConnectionBasic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquerydatapolicy/resource_bigquery_datapolicy_data_policy_test.go b/mmv1/third_party/terraform/services/bigquerydatapolicy/resource_bigquery_datapolicy_data_policy_test.go index 00ab3c15499e..7c94711fe084 100644 --- a/mmv1/third_party/terraform/services/bigquerydatapolicy/resource_bigquery_datapolicy_data_policy_test.go +++ b/mmv1/third_party/terraform/services/bigquerydatapolicy/resource_bigquery_datapolicy_data_policy_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquerydatapolicy" + _ "github.com/hashicorp/terraform-provider-google/google/services/datacatalog" ) func TestAccBigqueryDatapolicyDataPolicy_bigqueryDatapolicyDataPolicyUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquerydatapolicyv2/resource_bigquery_datapolicyv2_data_policy_test.go b/mmv1/third_party/terraform/services/bigquerydatapolicyv2/resource_bigquery_datapolicyv2_data_policy_test.go index 9354f98dda1c..5a060999f6f5 100644 --- a/mmv1/third_party/terraform/services/bigquerydatapolicyv2/resource_bigquery_datapolicyv2_data_policy_test.go +++ b/mmv1/third_party/terraform/services/bigquerydatapolicyv2/resource_bigquery_datapolicyv2_data_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquerydatapolicyv2" ) func TestAccBigqueryDatapolicyv2DataPolicy_bigqueryDatapolicyv2DatapolicyBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigquerydatatransfer/resource_bigquery_data_transfer_config_test.go b/mmv1/third_party/terraform/services/bigquerydatatransfer/resource_bigquery_data_transfer_config_test.go index b586865c1384..e5e7cb48b752 100644 --- a/mmv1/third_party/terraform/services/bigquerydatatransfer/resource_bigquery_data_transfer_config_test.go +++ b/mmv1/third_party/terraform/services/bigquerydatatransfer/resource_bigquery_data_transfer_config_test.go @@ -5,7 +5,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" "github.com/hashicorp/terraform-provider-google/google/services/bigquerydatatransfer" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "strings" @@ -525,7 +529,7 @@ func testAccCheckBigqueryDataTransferConfigDestroyProducer(t *testing.T) func(s config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{BigqueryDataTransferBasePath}}{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(bigquerydatatransfer.Product, config)+"{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_bi_reservation_test.go b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_bi_reservation_test.go index 9e40e56a3783..8298990ff889 100644 --- a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_bi_reservation_test.go +++ b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_bi_reservation_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryreservation" ) func TestAccBigqueryReservationBiReservation_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_assignment_test.go b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_assignment_test.go new file mode 100644 index 000000000000..860ea46f7fd8 --- /dev/null +++ b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_assignment_test.go @@ -0,0 +1,46 @@ +package bigqueryreservation_test + +import ( + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryreservation" +) + +func TestAccBigqueryReservationReservationAssignment_bareNameWithoutLocation(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: testAccBigqueryReservationReservationAssignment_bareNameWithoutLocation(context), + ExpectError: regexp.MustCompile("`location` is required"), + }, + }, + }) +} + +func testAccBigqueryReservationReservationAssignment_bareNameWithoutLocation(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_bigquery_reservation" "test" { + name = "tf-test-reservation-%{random_suffix}" + location = "us-central1" + slot_capacity = 0 + edition = "ENTERPRISE" +} + +resource "google_bigquery_reservation_assignment" "test" { + reservation = google_bigquery_reservation.test.name + assignee = "projects/${google_bigquery_reservation.test.project}" + job_type = "QUERY" +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_group_test.go b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_group_test.go index b103976e2371..241b8d7cebc4 100644 --- a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_group_test.go +++ b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_group_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryreservation" ) func TestAccBigqueryReservationGroup_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_test.go.tmpl b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_test.go.tmpl index 19a56a2a9a79..91d55360245c 100644 --- a/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_test.go.tmpl +++ b/mmv1/third_party/terraform/services/bigqueryreservation/resource_bigquery_reservation_test.go.tmpl @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigqueryreservation" ) func TestAccBigqueryReservation_withDisasterRecovery_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_app_profile_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_app_profile_test.go index f28ecdacf24f..483f73bf2a54 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_app_profile_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_app_profile_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" ) func TestAccBigtableAppProfile_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view.go index 3638d7dcddfa..9aa3981ec5d8 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view.go @@ -56,6 +56,7 @@ func ResourceBigtableAuthorizedView() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -122,6 +123,9 @@ If not provided, currently deletion protection will be set to UNPROTECTED as it }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -253,10 +257,19 @@ func resourceBigtableAuthorizedViewRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error parsing server returned subset_view since it's empty") } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceBigtableAuthorizedViewUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceBigtableAuthorizedView) { + return ResourceBigtableAuthorizedView().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -320,6 +333,13 @@ func resourceBigtableAuthorizedViewUpdate(d *schema.ResourceData, meta interface } func resourceBigtableAuthorizedViewDestroy(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view_meta.yaml b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view_meta.yaml index bea00f8ed23f..6bcc6d8b446f 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view_meta.yaml +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_authorized_view_meta.yaml @@ -13,3 +13,5 @@ fields: - field: 'subset_view.family_subsets.qualifiers' - api_field: 'subsetView.rowPrefixes' - field: 'table_name' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy.go index 3f1198cf7308..a0ae9eb231b3 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy.go @@ -10,6 +10,7 @@ import ( "time" "cloud.google.com/go/bigtable" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -95,12 +96,14 @@ func resourceBigtableGCPolicyCustomizeDiff(_ context.Context, d *schema.Resource func ResourceBigtableGCPolicy() *schema.Resource { return &schema.Resource{ - Create: resourceBigtableGCPolicyUpsert, - Read: resourceBigtableGCPolicyRead, - Delete: resourceBigtableGCPolicyDestroy, - Update: resourceBigtableGCPolicyUpsert, - CustomizeDiff: resourceBigtableGCPolicyCustomizeDiff, - + Create: resourceBigtableGCPolicyUpsert, + Read: resourceBigtableGCPolicyRead, + Delete: resourceBigtableGCPolicyDestroy, + Update: resourceBigtableGCPolicyUpsert, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + resourceBigtableGCPolicyCustomizeDiff, + ), Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(20 * time.Minute), Delete: schema.DefaultTimeout(20 * time.Minute), @@ -209,14 +212,9 @@ func ResourceBigtableGCPolicy() *schema.Resource { Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, - "deletion_policy": { - Type: schema.TypeString, - Optional: true, - Description: `The deletion policy for the GC policy. Setting ABANDON allows the resource - to be abandoned rather than deleted. This is useful for GC policy as it cannot be deleted - in a replicated instance. Possible values are: "ABANDON".`, - ValidateFunc: validation.StringInSlice([]string{"ABANDON", ""}, false), - }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end "ignore_warnings": { Type: schema.TypeBool, @@ -233,6 +231,11 @@ func ResourceBigtableGCPolicy() *schema.Resource { } func resourceBigtableGCPolicyUpsert(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceBigtableGCPolicy) { + return ResourceBigtableGCPolicy().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -370,6 +373,10 @@ func resourceBigtableGCPolicyRead(d *schema.ResourceData, meta interface{}) erro return fmt.Errorf("Error setting project: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -437,15 +444,15 @@ func GcPolicyToGCRuleString(gc bigtable.GCPolicy, topLevel bool) (map[string]int } func resourceBigtableGCPolicyDestroy(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) - if deletionPolicy := d.Get("deletion_policy"); deletionPolicy == "ABANDON" { - // Allows for the GC policy to be abandoned without deletion to avoid possible - // deletion failure in a replicated instance. - log.Printf("[WARN] The GC policy is abandoned") + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { return nil } + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy_meta.yaml b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy_meta.yaml index e2f3144c6ae5..553cdf72a6a5 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy_meta.yaml +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_gc_policy_meta.yaml @@ -6,6 +6,7 @@ api_resource_type_kind: 'Table' fields: - field: 'column_family' - field: 'deletion_policy' + provider_only: true - field: 'gc_rules' - field: 'ignore_warnings' - field: 'instance_name' diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance.go index b04950754daa..422dc84c1f17 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance.go @@ -54,6 +54,7 @@ func ResourceBigtableInstance() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, resourceBigtableInstanceClusterReorderTypeList, resourceBigtableInstanceUniqueClusterID, @@ -224,7 +225,9 @@ func ResourceBigtableInstance() *schema.Resource { ForceNew: true, Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, - + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end "tags": { Type: schema.TypeMap, Optional: true, @@ -232,6 +235,13 @@ func ResourceBigtableInstance() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, Description: `A map of Resource Manager Tags. Keys can be either the numeric tag key ID (tagKeys/123) or the namespaced name (project/tag-key). Values can be the numeric tag value ID (tagValues/456) or the namespaced value (project/tag-key/tag-value). The field is ignored when empty.`, }, + "edition": { + Type: schema.TypeString, + Optional: true, + Default: "ENTERPRISE", + ValidateFunc: validation.StringInSlice([]string{"ENTERPRISE", "ENTERPRISE_PLUS"}, false), + Description: `The edition of the instance. One of "ENTERPRISE" or "ENTERPRISE_PLUS". Defaults to "ENTERPRISE".`, + }, }, UseJSONNumber: true, } @@ -276,6 +286,15 @@ func resourceBigtableInstanceCreate(d *schema.ResourceData, meta interface{}) er conf.InstanceType = bigtable.PRODUCTION } + if v, ok := d.GetOk("edition"); ok { + switch v.(string) { + case "ENTERPRISE": + conf.Edition = bigtable.Enterprise + case "ENTERPRISE_PLUS": + conf.Edition = bigtable.EnterprisePlus + } + } + conf.Clusters, err = expandBigtableClusters(d.Get("cluster").([]interface{}), conf.InstanceID, config) if err != nil { return err @@ -386,6 +405,19 @@ func resourceBigtableInstanceRead(d *schema.ResourceData, meta interface{}) erro // Don't set instance_type: we don't want to detect drift on it because it can // change under-the-hood. + var edition string + switch instance.Edition { + case bigtable.Enterprise: + edition = "ENTERPRISE" + case bigtable.EnterprisePlus: + edition = "ENTERPRISE_PLUS" + default: + edition = "ENTERPRISE" + } + if err := d.Set("edition", edition); err != nil { + return fmt.Errorf("Error setting edition: %s", err) + } + // Explicitly set virtual fields to default values if unset if _, ok := d.GetOkExists("force_destroy"); !ok { if err := d.Set("force_destroy", false); err != nil { @@ -393,10 +425,19 @@ func resourceBigtableInstanceRead(d *schema.ResourceData, meta interface{}) erro } } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceBigtableInstanceUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceBigtableInstance) { + return ResourceBigtableInstance().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -436,6 +477,15 @@ func resourceBigtableInstanceUpdate(d *schema.ResourceData, meta interface{}) er conf.InstanceType = bigtable.PRODUCTION } + if d.HasChange("edition") { + switch d.Get("edition").(string) { + case "ENTERPRISE": + conf.Edition = bigtable.Enterprise + case "ENTERPRISE_PLUS": + conf.Edition = bigtable.EnterprisePlus + } + } + conf.Clusters, err = expandBigtableClusters(d.Get("cluster").([]interface{}), conf.InstanceID, config) if err != nil { return err @@ -464,6 +514,13 @@ func resourceBigtableInstanceUpdate(d *schema.ResourceData, meta interface{}) er func resourceBigtableInstanceDestroy(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Deleting BigTable instance %q", d.Id()) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + if d.Get("deletion_protection").(bool) { return fmt.Errorf("cannot destroy instance without setting deletion_protection=false and running `terraform apply`") } diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_iam_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_iam_test.go index 0d8ec23e5b9f..cb991ff92dec 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_iam_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_iam_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccBigtableInstanceIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_meta.yaml b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_meta.yaml index 64a6a50b96b8..1329e856f40b 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_meta.yaml +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_meta.yaml @@ -22,6 +22,7 @@ fields: - field: 'effective_labels' provider_only: true - field: 'force_destroy' + - field: 'edition' - field: 'instance_type' - api_field: 'labels' - api_field: 'name' @@ -29,3 +30,5 @@ fields: - api_field: 'tags' - field: 'terraform_labels' provider_only: true + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_test.go index 0d9462327cf7..375b051dcc8c 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_instance_test.go @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/bigtable" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -178,8 +181,8 @@ func TestAccBigtableInstance_kms(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - kms1 := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - kms2 := acctest.BootstrapKMSKeyInLocation(t, "us-east1") + kms1 := kms.BootstrapKMSKeyInLocation(t, "us-central1") + kms2 := kms.BootstrapKMSKeyInLocation(t, "us-east1") pid := envvar.GetTestProjectFromEnv() instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -1323,3 +1326,91 @@ resource "google_bigtable_instance" "instance" { } `, pid, instanceName, instanceName, instanceName, instanceName) } + +func TestAccBigtableInstance_edition(t *testing.T) { + // bigtable instance does not use the shared HTTP client, this test creates an instance + acctest.SkipIfVcr(t) + t.Parallel() + + instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckBigtableInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + // Create as ENTERPRISE + { + Config: testAccBigtableInstance_edition(instanceName, "ENTERPRISE"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_bigtable_instance.instance", "edition", "ENTERPRISE"), + ), + }, + { + ResourceName: "google_bigtable_instance.instance", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection", "instance_type", "labels", "terraform_labels"}, + }, + // Upgrade to ENTERPRISE_PLUS + { + Config: testAccBigtableInstance_edition(instanceName, "ENTERPRISE_PLUS"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_bigtable_instance.instance", "edition", "ENTERPRISE_PLUS"), + ), + }, + { + ResourceName: "google_bigtable_instance.instance", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection", "instance_type", "labels", "terraform_labels"}, + }, + }, + }) +} + +func TestAccBigtableInstance_editionEnterprisePlus(t *testing.T) { + // bigtable instance does not use the shared HTTP client, this test creates an instance + acctest.SkipIfVcr(t) + t.Parallel() + + instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckBigtableInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + // Create directly as ENTERPRISE_PLUS + { + Config: testAccBigtableInstance_edition(instanceName, "ENTERPRISE_PLUS"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_bigtable_instance.instance", "edition", "ENTERPRISE_PLUS"), + ), + }, + { + ResourceName: "google_bigtable_instance.instance", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection", "instance_type", "labels", "terraform_labels"}, + }, + }, + }) +} + +func testAccBigtableInstance_edition(instanceName, edition string) string { + return fmt.Sprintf(` +resource "google_bigtable_instance" "instance" { + name = "%s" + instance_type = "PRODUCTION" + edition = "%s" + cluster { + cluster_id = "%s" + zone = "us-central1-b" + num_nodes = 1 + storage_type = "SSD" + } + deletion_protection = false +} +`, instanceName, edition, instanceName) +} diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_logical_view_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_logical_view_test.go index a6e3c39c6301..a98bb377bd6e 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_logical_view_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_logical_view_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_materialized_view_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_materialized_view_test.go index 945b3da64c0d..5b25583fe6d8 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_materialized_view_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_materialized_view_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_schema_bundle_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_schema_bundle_test.go index 73293bf94f10..c05550825c37 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_schema_bundle_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_schema_bundle_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table.go index 17de347888a0..96b6135fe6b9 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table.go @@ -54,6 +54,7 @@ func ResourceBigtableTable() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, abpDiffFunc, ), @@ -168,6 +169,9 @@ func ResourceBigtableTable() *schema.Resource { The schema must be a valid JSON encoded string representing a Type's struct protobuf message. Note that for bytes sequence (like delimited_bytes.delimiter) the delimiter must be base64 encoded. For example, if you want to set a delimiter to a single byte character "#", it should be set to "Iw==", which is the base64 encoding of the byte sequence "#".`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -441,6 +445,10 @@ func resourceBigtableTableRead(d *schema.ResourceData, meta interface{}) error { d.Set("row_key_schema", nil) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -487,6 +495,11 @@ func familyMapDiffValueTypes(a, b map[string]bigtable.Family) map[string]bigtabl } func resourceBigtableTableUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceBigtableTable) { + return ResourceBigtableTable().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -632,6 +645,13 @@ func resourceBigtableTableUpdate(d *schema.ResourceData, meta interface{}) error } func resourceBigtableTableDestroy(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_iam_test.go b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_iam_test.go index dd31e17eb757..6246ae5774be 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_iam_test.go +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_iam_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigtable" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccBigtableTableIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_meta.yaml b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_meta.yaml index 0e42b54d1066..ae71259d2170 100644 --- a/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_meta.yaml +++ b/mmv1/third_party/terraform/services/bigtable/resource_bigtable_table_meta.yaml @@ -18,3 +18,5 @@ fields: - api_field: 'rowKeySchema' json: true - field: 'split_keys' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/billingbudgets/resource_billing_budget_test.go b/mmv1/third_party/terraform/services/billingbudgets/resource_billing_budget_test.go index f1daffb1067c..e52b13ab175e 100644 --- a/mmv1/third_party/terraform/services/billingbudgets/resource_billing_budget_test.go +++ b/mmv1/third_party/terraform/services/billingbudgets/resource_billing_budget_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/billingbudgets" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_attestor_test.go.tmpl b/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_attestor_test.go.tmpl index 929c02619b92..3226f2c55bd9 100644 --- a/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_attestor_test.go.tmpl +++ b/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_attestor_test.go.tmpl @@ -4,7 +4,9 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/containeranalysis" "github.com/hashicorp/terraform-provider-google/google/services/binaryauthorization" + "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) @@ -97,7 +99,7 @@ func TestAccBinaryAuthorizationAttestor_full(t *testing.T) { func TestAccBinaryAuthorizationAttestor_kms(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") + bootstrapped := kms.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") attestorName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -106,7 +108,7 @@ func TestAccBinaryAuthorizationAttestor_kms(t *testing.T) { CheckDestroy: testAccCheckBinaryAuthorizationAttestorDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccBinaryAuthorizationAttestorKms(attestorName, kms.CryptoKey.Name), + Config: testAccBinaryAuthorizationAttestorKms(attestorName, bootstrapped.CryptoKey.Name), }, { ResourceName: "google_binary_authorization_attestor.attestor", diff --git a/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_policy_test.go b/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_policy_test.go index 8e2f9f14361b..44ce8934989f 100644 --- a/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_policy_test.go +++ b/mmv1/third_party/terraform/services/binaryauthorization/resource_binary_authorization_policy_test.go @@ -11,6 +11,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/binaryauthorization" + _ "github.com/hashicorp/terraform-provider-google/google/services/containeranalysis" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificate_map_test.go b/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificate_map_test.go index a40e7b577139..bee1f8e10796 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificate_map_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificate_map_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" ) func TestAccDataSourceGoogleCertificateManagerCertificateMap_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificates_test.go b/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificates_test.go index 075a65b1dffd..8a5cae8a2026 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificates_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_certificates_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" ) func TestAccDataSourceGoogleCertificateManagerCertificates_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_dns_authorization_test.go b/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_dns_authorization_test.go index 56f2c3293b14..6e73410f1062 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_dns_authorization_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/data_source_google_certificate_manager_dns_authorization_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" ) func TestAccCertificateManagerDnsAuthorizationDatasource(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_certificate_upgrade_test.go b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_certificate_upgrade_test.go index 5fb626aa3123..6cc376d3f364 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_certificate_upgrade_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_certificate_upgrade_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" ) // Tests schema version migration by creating a certificate with an old version of the provider (4.59.0) diff --git a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_test.go b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_test.go index a50e4e6d66a7..83426ddf26aa 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" ) func TestAccCertificateManagerDnsAuthorization_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_upgrade_test.go b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_upgrade_test.go index 90f48d4c04d8..53f0eb2d7ac6 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_upgrade_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_dns_authorization_upgrade_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" ) // Tests schema version migration by creating a dns authorization with an old version of the provider (5.15.0) diff --git a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_trust_config_test.go b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_trust_config_test.go index 70a64eb55b9c..0b13018fd093 100644 --- a/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_trust_config_test.go +++ b/mmv1/third_party/terraform/services/certificatemanager/resource_certificate_manager_trust_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" ) func TestAccCertificateManagerTrustConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/ces/ces_agent_test.go b/mmv1/third_party/terraform/services/ces/ces_agent_test.go index 171562455ab0..0cbcd5c9d5ca 100644 --- a/mmv1/third_party/terraform/services/ces/ces_agent_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_agent_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" ) func TestAccCESAgent_cesAgentBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/ces/ces_app_root_agent_association_test.go b/mmv1/third_party/terraform/services/ces/ces_app_root_agent_association_test.go index 110816686080..1c54ef8fec94 100644 --- a/mmv1/third_party/terraform/services/ces/ces_app_root_agent_association_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_app_root_agent_association_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/ces" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -76,7 +77,7 @@ func testAccCheckCesAppRootAgentCleared(t *testing.T, appResourceName string) re config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{CESBasePath}}projects/{{project}}/locations/{{location}}/apps/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(ces.Product, config)+"projects/{{project}}/locations/{{location}}/apps/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/ces/ces_app_test.go b/mmv1/third_party/terraform/services/ces/ces_app_test.go index bdb2d0203001..6ab024692dbc 100644 --- a/mmv1/third_party/terraform/services/ces/ces_app_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_app_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccCESApp_update(t *testing.T) { @@ -76,6 +78,7 @@ resource "google_ces_app" "ces_app_basic" { description = "Basic CES App example" display_name = "tf-test-my-app-%{random_suffix}" pinned = false + tool_execution_mode = "SEQUENTIAL" language_settings { default_language_code = "en-US" @@ -267,6 +270,7 @@ resource "google_ces_app" "ces_app_basic" { description = "Updated CES App example" display_name = "tf-test-my-app%{random_suffix}" pinned = true + tool_execution_mode = "PARALLEL" language_settings { default_language_code = "en-ES" diff --git a/mmv1/third_party/terraform/services/ces/ces_deployment_test.go b/mmv1/third_party/terraform/services/ces/ces_deployment_test.go index 742561091b06..e9d9d23c2d71 100644 --- a/mmv1/third_party/terraform/services/ces/ces_deployment_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_deployment_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" // Add this import "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" ) func TestAccCESDeployment_update(t *testing.T) { @@ -74,6 +75,12 @@ resource "google_ces_deployment" "my-deployment" { modality = "CHAT_AND_VOICE" theme = "DARK" web_widget_title = "temp_webwidget_title" + security_settings { + enable_public_access = true + enable_origin_check = true + allowed_origins = ["https://example.com", "https://test.com"] + enable_recaptcha = true + } } } } @@ -107,6 +114,12 @@ resource "google_ces_deployment" "my-deployment" { modality = "CHAT_ONLY" theme = "LIGHT" web_widget_title = "temp_webwidget_title" + security_settings { + enable_public_access = false + enable_origin_check = false + allowed_origins = ["https://updated.com"] + enable_recaptcha = false + } } } } diff --git a/mmv1/third_party/terraform/services/ces/ces_example_test.go b/mmv1/third_party/terraform/services/ces/ces_example_test.go index 1256a539cecb..d112e0c9a4be 100644 --- a/mmv1/third_party/terraform/services/ces/ces_example_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_example_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" ) func TestAccCESExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/ces/ces_guardrail_test.go b/mmv1/third_party/terraform/services/ces/ces_guardrail_test.go index c5de54a0e601..66ceba5c54c2 100644 --- a/mmv1/third_party/terraform/services/ces/ces_guardrail_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_guardrail_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" ) func TestAccCESGuardrail_cesGuardrailBasicExample_update(t *testing.T) { @@ -676,3 +677,115 @@ resource "google_ces_guardrail" "ces_guardrail_llm_policy" { } `, context) } + +func TestAccCESGuardrail_cesGuardrailLlmPromptSecurityFailOpenExample_update(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckCESGuardrailDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccCESGuardrail_cesGuardrailLlmPromptSecurityFailOpenExample_full(context), + }, + { + ResourceName: "google_ces_guardrail.ces_guardrail_llm_prompt_security_fail_open", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"app_id", "guardrail_id"}, + }, + { + Config: testAccCESGuardrail_cesGuardrailLlmPromptSecurityFailOpenExample_update(context), + ConfigPlanChecks: resource.ConfigPlanChecks{ + PreApply: []plancheck.PlanCheck{ + plancheck.ExpectResourceAction("google_ces_guardrail.ces_guardrail_llm_prompt_security_fail_open", plancheck.ResourceActionUpdate), + }, + }, + }, + { + ResourceName: "google_ces_guardrail.ces_guardrail_llm_prompt_security_fail_open", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"app_id", "guardrail_id"}, + }, + }, + }) +} + +func testAccCESGuardrail_cesGuardrailLlmPromptSecurityFailOpenExample_full(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_ces_app" "ces_app_for_guardrail" { + app_id = "tf-test-app-id%{random_suffix}" + location = "us" + description = "App used as parent for CES Guardrail example" + display_name = "tf-test-my-app%{random_suffix}" + + language_settings { + default_language_code = "en-US" + supported_language_codes = ["es-ES", "fr-FR"] + enable_multilingual_support = true + fallback_action = "escalate" + } + time_zone_settings { + time_zone = "America/Los_Angeles" + } +} + +resource "google_ces_guardrail" "ces_guardrail_llm_prompt_security_fail_open" { + guardrail_id = "tf-test-guardrail-id%{random_suffix}" + location = google_ces_app.ces_app_for_guardrail.location + app = google_ces_app.ces_app_for_guardrail.app_id + display_name = "tf-test-my-guardrail%{random_suffix}" + description = "Guardrail description" + action { + generative_answer { + prompt = "example_prompt" + } + } + enabled = true +} +`, context) +} + +func testAccCESGuardrail_cesGuardrailLlmPromptSecurityFailOpenExample_update(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_ces_app" "ces_app_for_guardrail" { + app_id = "tf-test-app-id%{random_suffix}" + location = "us" + description = "App used as parent for CES Guardrail example" + display_name = "tf-test-my-app%{random_suffix}" + + language_settings { + default_language_code = "en-US" + supported_language_codes = ["es-ES", "fr-FR"] + enable_multilingual_support = true + fallback_action = "escalate" + } + time_zone_settings { + time_zone = "America/Los_Angeles" + } +} + +resource "google_ces_guardrail" "ces_guardrail_llm_prompt_security_fail_open" { + guardrail_id = "tf-test-guardrail-id%{random_suffix}" + location = google_ces_app.ces_app_for_guardrail.location + app = google_ces_app.ces_app_for_guardrail.app_id + display_name = "tf-test-my-guardrail%{random_suffix}" + description = "Guardrail description" + action { + generative_answer { + prompt = "example_prompt" + } + } + enabled = true + llm_prompt_security { + fail_open = true + } +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/ces/ces_tool_test.go b/mmv1/third_party/terraform/services/ces/ces_tool_test.go index a07ee2eb8281..57cf5d9ef62b 100644 --- a/mmv1/third_party/terraform/services/ces/ces_tool_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_tool_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" // Add this import "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccCESTool_cesToolClientFunctionBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/ces/ces_toolset_test.go b/mmv1/third_party/terraform/services/ces/ces_toolset_test.go index 08da36383ebb..efaff37b8a01 100644 --- a/mmv1/third_party/terraform/services/ces/ces_toolset_test.go +++ b/mmv1/third_party/terraform/services/ces/ces_toolset_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccCESToolset_cesToolsetOpenapiServiceAccountAuthConfigExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/ces/resource_ces_evaluation_test.go.tmpl b/mmv1/third_party/terraform/services/ces/resource_ces_evaluation_test.go.tmpl index 6e54e67bbb2b..c883f1e45160 100644 --- a/mmv1/third_party/terraform/services/ces/resource_ces_evaluation_test.go.tmpl +++ b/mmv1/third_party/terraform/services/ces/resource_ces_evaluation_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/ces" ) func TestAccCESEvaluation_update(t *testing.T) { t.Parallel() diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_dashboard_chart_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_dashboard_chart_test.go index 31fa0099fd4f..1ba26f3169de 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_dashboard_chart_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_dashboard_chart_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleDashboardChart_chronicleDashboardchartFullExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_label_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_label_test.go index aaaf9ff30ecb..cef00c08177c 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_label_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_label_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_scope_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_scope_test.go index 0684aedc188d..fe432a65ec83 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_scope_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_access_scope_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleDataAccessScope_chronicleDataaccessscopeBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_deletion_policy_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_deletion_policy_test.go index fb49ca498c94..7eac9252e435 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_deletion_policy_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_deletion_policy_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleDataTable_DeletionPolicy_DefaultFail(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_row_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_row_test.go index 3375c3ef92be..858aeb972987 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_row_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_row_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleDataTableRow_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_test.go index 8f684123a846..6c91a04b70c0 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_data_table_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleDataTable_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_feed_test.go.tmpl b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_feed_test.go.tmpl index bf3759a7ddfc..90d01076e290 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_feed_test.go.tmpl +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_feed_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_native_dashboard_test.go.tmpl b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_native_dashboard_test.go similarity index 98% rename from mmv1/third_party/terraform/services/chronicle/resource_chronicle_native_dashboard_test.go.tmpl rename to mmv1/third_party/terraform/services/chronicle/resource_chronicle_native_dashboard_test.go index 9ae608eaff51..3f7cbe650d65 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_native_dashboard_test.go.tmpl +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_native_dashboard_test.go @@ -1,7 +1,5 @@ package chronicle_test -{{- if ne $.TargetVersionName "ga" }} - import ( "testing" @@ -10,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) // TestAccChronicleNativeDashboard_chronicleNativedashboardUpdateExample tests updating a Native Dashboard and the layout/filter association of an existing Chart within it. @@ -121,5 +120,3 @@ resource "google_chronicle_native_dashboard" "my_dashboard" { } `, context) } - -{{- end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_reference_list_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_reference_list_test.go index 5d8e0ff11380..05ca9eb535d8 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_reference_list_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_reference_list_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleReferenceList_chronicleReferencelistBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_deployment_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_deployment_test.go index d3d458d4f4ba..30c2e5bf358b 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_deployment_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_deployment_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleRuleDeployment_chronicleRuledeploymentBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_test.go index 3776451efc42..19ba93609a38 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_rule_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleRule_chronicleRuleBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_watchlist_test.go b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_watchlist_test.go index 3f705da79e77..6ca3b88bd577 100644 --- a/mmv1/third_party/terraform/services/chronicle/resource_chronicle_watchlist_test.go +++ b/mmv1/third_party/terraform/services/chronicle/resource_chronicle_watchlist_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/chronicle" ) func TestAccChronicleWatchlist_chronicleWatchlistBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudbilling/iam_billing_account_test.go b/mmv1/third_party/terraform/services/cloudbilling/iam_billing_account_test.go index 84ac833e02b8..084275fbc8d5 100644 --- a/mmv1/third_party/terraform/services/cloudbilling/iam_billing_account_test.go +++ b/mmv1/third_party/terraform/services/cloudbilling/iam_billing_account_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/cloudbilling/resource_google_billing_project_info_test.go b/mmv1/third_party/terraform/services/cloudbilling/resource_google_billing_project_info_test.go index 17638d20f3a9..85e01586a6f1 100644 --- a/mmv1/third_party/terraform/services/cloudbilling/resource_google_billing_project_info_test.go +++ b/mmv1/third_party/terraform/services/cloudbilling/resource_google_billing_project_info_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccBillingProjectInfo_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudbuild/data_source_google_cloudbuild_trigger_test.go b/mmv1/third_party/terraform/services/cloudbuild/data_source_google_cloudbuild_trigger_test.go index fd4bac3ed768..845efda90e5a 100644 --- a/mmv1/third_party/terraform/services/cloudbuild/data_source_google_cloudbuild_trigger_test.go +++ b/mmv1/third_party/terraform/services/cloudbuild/data_source_google_cloudbuild_trigger_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuild" ) func TestAccDataSourceGoogleCloudBuildTrigger_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_test.go b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_test.go index 3bcfa0d657ca..4da7a23dafa7 100644 --- a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_test.go +++ b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_test.go @@ -6,6 +6,9 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuild" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_upgrade_test.go b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_upgrade_test.go index e0614a4af60e..ca4b77bcb0de 100644 --- a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_upgrade_test.go +++ b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_trigger_upgrade_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuild" ) // Tests schema version migration by creating a trigger with an old version of the provider (4.30.0) diff --git a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool.go b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool.go index 23e81af94bce..f52c0e67d4b2 100644 --- a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool.go +++ b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool.go @@ -36,6 +36,7 @@ func ResourceCloudbuildWorkerPool() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -139,6 +140,9 @@ func ResourceCloudbuildWorkerPool() *schema.Resource { Computed: true, Description: "Output only. Time at which the request to update the `WorkerPool` was received.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -354,9 +358,18 @@ func resourceCloudbuildWorkerPoolRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error setting update_time in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceCloudbuildWorkerPoolUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceCloudbuildWorkerPool) { + return ResourceCloudbuildWorkerPool().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -407,6 +420,13 @@ func resourceCloudbuildWorkerPoolUpdate(d *schema.ResourceData, meta interface{} } func resourceCloudbuildWorkerPoolDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_meta.yaml b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_meta.yaml index dca7d6eaad31..32c9b11d3a9e 100644 --- a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_meta.yaml +++ b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_meta.yaml @@ -32,3 +32,5 @@ fields: field: 'worker_config.machine_type' - api_field: 'privatePoolV1Config.networkConfig.egressOption' field: 'worker_config.no_external_ip' + - field: 'deletion_policy' + provider_only: true \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_test.go.tmpl b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_test.go.tmpl index aa6399bb3de0..8926f07b25e9 100644 --- a/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudbuild/resource_cloudbuild_worker_pool_test.go.tmpl @@ -8,7 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuild" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -58,9 +61,9 @@ func TestAccCloudbuildWorkerPool_basic(t *testing.T) { t.Parallel() - testNetworkName := acctest.BootstrapSharedTestNetwork(t, "attachment-network") - subnetName := acctest.BootstrapSubnet(t, "tf-test-subnet", testNetworkName) - networkAttachmentName := acctest.BootstrapNetworkAttachment(t, "tf-test-attachment", subnetName) + testNetworkName := tpgcompute.BootstrapSharedTestNetwork(t, "attachment-network") + subnetName := tpgcompute.BootstrapSubnet(t, "tf-test-subnet", testNetworkName) + networkAttachmentName := tpgcompute.BootstrapNetworkAttachment(t, "tf-test-attachment", subnetName) // Need to have the full network attachment name in the format project/{project_id}/regions/{region_id}/networkAttachments/{networkAttachmentName} fullFormNetworkAttachmentName := fmt.Sprintf("projects/%s/regions/%s/networkAttachments/%s", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), networkAttachmentName) @@ -182,7 +185,7 @@ func TestAccCloudbuildWorkerPool_withNetwork(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "project": envvar.GetTestProjectFromEnv(), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "cloudbuild-workerpool-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "cloudbuild-workerpool-1"), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/cloudbuildv2/resource_cloudbuildv2_connection_test.go b/mmv1/third_party/terraform/services/cloudbuildv2/resource_cloudbuildv2_connection_test.go index e0426e6d4292..df0b5e6ee68e 100644 --- a/mmv1/third_party/terraform/services/cloudbuildv2/resource_cloudbuildv2_connection_test.go +++ b/mmv1/third_party/terraform/services/cloudbuildv2/resource_cloudbuildv2_connection_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuildv2" ) func TestAccCloudbuildv2Connection_GheCompleteConnection(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_automation_test.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_automation_test.go index 2b6d9930c08b..3f71c3f17e90 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_automation_test.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_automation_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/clouddeploy" ) func TestAccClouddeployAutomation_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_custom_target_type_test.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_custom_target_type_test.go index abcca4a69516..023e77ac4a8c 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_custom_target_type_test.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_custom_target_type_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/clouddeploy" ) func TestAccClouddeployCustomTargetType_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline.go index e2250feb5697..98c8e24b20ca 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline.go @@ -37,6 +37,7 @@ func ResourceClouddeployDeliveryPipeline() *schema.Resource { tpgresource.DefaultProviderProject, tpgresource.SetLabelsDiff, tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -145,6 +146,9 @@ func ResourceClouddeployDeliveryPipeline() *schema.Resource { Computed: true, Description: "Output only. Most recent time at which the pipeline was updated.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -1089,9 +1093,18 @@ func resourceClouddeployDeliveryPipelineRead(d *schema.ResourceData, meta interf return fmt.Errorf("error setting update_time in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceClouddeployDeliveryPipelineUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceClouddeployDeliveryPipeline) { + return ResourceClouddeployDeliveryPipeline().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -1142,6 +1155,13 @@ func resourceClouddeployDeliveryPipelineUpdate(d *schema.ResourceData, meta inte } func resourceClouddeployDeliveryPipelineDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_meta.yaml b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_meta.yaml index a2402b90dc47..0a024e2cdf40 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_meta.yaml +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_meta.yaml @@ -111,3 +111,5 @@ fields: provider_only: true - api_field: 'uid' - api_field: 'updateTime' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_test.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_test.go index ffb98bb043a6..a74a1afe2918 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_test.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_delivery_pipeline_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/clouddeploy" ) func TestAccClouddeployDeliveryPipeline_withAnalysis(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_deploy_policy_test.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_deploy_policy_test.go index 8cca70af4a88..8e9262da408b 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_deploy_policy_test.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_deploy_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/clouddeploy" ) func TestAccClouddeployDeployPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target.go index d14fcee69f28..ab74f67e278d 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target.go @@ -37,6 +37,7 @@ func ResourceClouddeployTarget() *schema.Resource { tpgresource.DefaultProviderProject, tpgresource.SetLabelsDiff, tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -204,6 +205,9 @@ func ResourceClouddeployTarget() *schema.Resource { Computed: true, Description: "Output only. Most recent time at which the `Target` was updated.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -645,9 +649,18 @@ func resourceClouddeployTargetRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("error setting update_time in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceClouddeployTargetUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceClouddeployTarget) { + return ResourceClouddeployTarget().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -705,6 +718,13 @@ func resourceClouddeployTargetUpdate(d *schema.ResourceData, meta interface{}) e } func resourceClouddeployTargetDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_meta.yaml b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_meta.yaml index 036814635ff4..da9bc1a3cb1a 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_meta.yaml +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_meta.yaml @@ -47,3 +47,5 @@ fields: provider_only: true - api_field: 'uid' - api_field: 'updateTime' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_test.go b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_test.go index d70410ef074f..b23a8e6f5c6b 100644 --- a/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_test.go +++ b/mmv1/third_party/terraform/services/clouddeploy/resource_clouddeploy_target_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/clouddeploy" ) func TestAccClouddeployTarget_withProviderDefaultLabels(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudfunctions/data_source_google_cloudfunctions_function_test.go b/mmv1/third_party/terraform/services/cloudfunctions/data_source_google_cloudfunctions_function_test.go index 47657bbdeb89..78b4e2529446 100644 --- a/mmv1/third_party/terraform/services/cloudfunctions/data_source_google_cloudfunctions_function_test.go +++ b/mmv1/third_party/terraform/services/cloudfunctions/data_source_google_cloudfunctions_function_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function.go b/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function.go index 00ddd116c0ab..7c24a20d72bc 100644 --- a/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function.go +++ b/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function.go @@ -144,6 +144,7 @@ func ResourceCloudFunctionsFunction() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, tpgresource.SetLabelsDiff, @@ -534,6 +535,9 @@ func ResourceCloudFunctionsFunction() *schema.Resource { Computed: true, Description: `The version identifier of the Cloud Function. Each deployment attempt results in a new version of a function being created.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -868,11 +872,20 @@ func resourceCloudFunctionsRead(d *schema.ResourceData, meta interface{}) error d.Set("automatic_update_policy", nil) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceCloudFunctionsUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG]: Updating google_cloudfunctions_function") + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceCloudFunctionsFunction) { + return ResourceCloudFunctionsFunction().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1065,6 +1078,13 @@ func resourceCloudFunctionsUpdate(d *schema.ResourceData, meta interface{}) erro } func resourceCloudFunctionsDestroy(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_meta.yaml b/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_meta.yaml index 7e815ad9e358..66cc41aa17b8 100644 --- a/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_meta.yaml +++ b/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_meta.yaml @@ -53,3 +53,5 @@ fields: - api_field: 'vpcConnectorEgressSettings' - field: 'automatic_update_policy' - api_field: 'onDeployUpdatePolicy.runtimeVersion' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_test.go.tmpl b/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_test.go.tmpl index 9bcc17f9eff0..4b4b4caa8575 100644 --- a/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudfunctions/resource_cloudfunctions_function_test.go.tmpl @@ -8,8 +8,19 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuild" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/vpcaccess" + _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" "github.com/hashicorp/terraform-provider-google/google/envvar" tpgcloudfunctions "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions" +{{ if ne $.TargetVersionName `ga` -}} + "github.com/hashicorp/terraform-provider-google/google/services/kms" +{{- end }} + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "google.golang.org/api/cloudfunctions/v1" ) @@ -26,7 +37,7 @@ const testSecretEnvVarFunctionPath = "./test-fixtures/secret_environment_variabl const testSecretVolumesMountFunctionPath = "./test-fixtures/secret_volumes_mount.js" func bootstrapGcfAdminAgents(t *testing.T) { - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com", Role: "roles/vpcaccess.admin", @@ -312,7 +323,7 @@ func TestAccCloudFunctionsFunction_cmek(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") funcResourceName := "google_cloudfunctions_function.function" arRepoName := fmt.Sprintf("tf-cmek-test-docker-repository-%s", acctest.RandString(t, 10)) functionName := fmt.Sprintf("tf-cmek-test-%s", acctest.RandString(t, 10)) diff --git a/mmv1/third_party/terraform/services/cloudfunctions2/data_source_google_cloudfunctions2_function_test.go b/mmv1/third_party/terraform/services/cloudfunctions2/data_source_google_cloudfunctions2_function_test.go index 27abc9ecf150..87873917e90b 100644 --- a/mmv1/third_party/terraform/services/cloudfunctions2/data_source_google_cloudfunctions2_function_test.go +++ b/mmv1/third_party/terraform/services/cloudfunctions2/data_source_google_cloudfunctions2_function_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions2" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceGoogleCloudFunctions2Function_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudfunctions2/resource_cloudfunctions2_function_test.go b/mmv1/third_party/terraform/services/cloudfunctions2/resource_cloudfunctions2_function_test.go index 96e7c7f8273a..b1ca1875ec8a 100644 --- a/mmv1/third_party/terraform/services/cloudfunctions2/resource_cloudfunctions2_function_test.go +++ b/mmv1/third_party/terraform/services/cloudfunctions2/resource_cloudfunctions2_function_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/binaryauthorization" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions2" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccCloudFunctions2Function_update(t *testing.T) { @@ -198,7 +202,7 @@ func TestAccCloudFunctions2Function_fullUpdate(t *testing.T) { "random_suffix": randomSuffix, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", diff --git a/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_lookup_test.go b/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_lookup_test.go index 0409c182ec67..4781beb0586e 100644 --- a/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_lookup_test.go +++ b/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_lookup_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" ) func testAccDataSourceCloudIdentityGroupLookup_basicTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_transitive_memberships_test.go b/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_transitive_memberships_test.go index 31f3896a74f4..9c2c1feaca9d 100644 --- a/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_transitive_memberships_test.go +++ b/mmv1/third_party/terraform/services/cloudidentity/data_source_cloud_identity_group_transitive_memberships_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" ) func testAccDataSourceCloudIdentityGroupTransitiveMemberships_basicTest(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_membership_test.go.tmpl b/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_membership_test.go.tmpl index 3bc92e86400f..777341311cc4 100644 --- a/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_membership_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_membership_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_test.go.tmpl b/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_test.go.tmpl index 390ba0b1cf8a..a1c8ddc72c2f 100644 --- a/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_group_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_policy_test.go.tmpl b/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_policy_test.go.tmpl index ccd2031a4ca0..e7c26edfa6b5 100644 --- a/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudidentity/resource_cloud_identity_policy_test.go.tmpl @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/cloudids/resource_cloudids_endpoint_test.go b/mmv1/third_party/terraform/services/cloudids/resource_cloudids_endpoint_test.go index 6d0d2df72704..bab23ada20e9 100644 --- a/mmv1/third_party/terraform/services/cloudids/resource_cloudids_endpoint_test.go +++ b/mmv1/third_party/terraform/services/cloudids/resource_cloudids_endpoint_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/cloudids" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -18,7 +20,7 @@ func TestAccCloudIdsEndpoint_basic(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "cloud-ids-endpoint-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "cloud-ids-endpoint-1"), } acctest.VcrTest(t, resource.TestCase{ @@ -90,7 +92,7 @@ func testAccCheckCloudIdsEndpointDestroyProducer(t *testing.T) func(s *terraform config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{CloudIdsBasePath}}projects/{{project}}/locations/{{location}}/endpoints/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(cloudids.Product, config)+"projects/{{project}}/locations/{{location}}/endpoints/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_info.go b/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_info.go index b3c68a833431..cb236dca1d59 100644 --- a/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_info.go +++ b/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_info.go @@ -133,7 +133,7 @@ func dataSourceGoogleCloudQuotasQuotaInfoRead(d *schema.ResourceData, meta inter return err } - url, err := tpgresource.ReplaceVars(d, config, "{{CloudQuotasBasePath}}{{parent}}/locations/global/services/{{service}}/quotaInfos/{{quota_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/locations/global/services/{{service}}/quotaInfos/{{quota_id}}") if err != nil { return fmt.Errorf("error setting api endpoint") } diff --git a/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_infos.go b/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_infos.go index efe25cdc6b7e..7069b84d59b6 100644 --- a/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_infos.go +++ b/mmv1/third_party/terraform/services/cloudquotas/data_source_google_cloud_quotas_quota_infos.go @@ -145,7 +145,7 @@ func dataSourceGoogleCloudQuotasQuotaInfosRead(d *schema.ResourceData, meta inte return err } - url, err := tpgresource.ReplaceVars(d, config, "{{CloudQuotasBasePath}}{{parent}}/locations/global/services/{{service}}/quotaInfos") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/locations/global/services/{{service}}/quotaInfos") if err != nil { return fmt.Errorf("error setting api endpoint") } @@ -170,7 +170,7 @@ func dataSourceGoogleCloudQuotasQuotaInfosRead(d *schema.ResourceData, meta inte if res["nextPageToken"] == nil || res["nextPageToken"].(string) == "" { break } - url, err = tpgresource.ReplaceVars(d, config, "{{CloudQuotasBasePath}}{{parent}}/locations/global/services/{{service}}/quotaInfos?pageToken="+res["nextPageToken"].(string)) + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/locations/global/services/{{service}}/quotaInfos?pageToken="+res["nextPageToken"].(string)) if err != nil { return fmt.Errorf("error setting api endpoint") } diff --git a/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_adjuster_settings_test.go.tmpl b/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_adjuster_settings_test.go.tmpl index 4fe98efd9643..a0c75b7b208f 100644 --- a/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_adjuster_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_adjuster_settings_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudquotas" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_preference_test.go b/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_preference_test.go index 55baf9185086..f61dd06fe42f 100644 --- a/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_preference_test.go +++ b/mmv1/third_party/terraform/services/cloudquotas/resource_cloud_quotas_quota_preference_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudquotas" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccCloudQuotasQuotaPreference_cloudquotasQuotaPreferenceBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudrun/data_source_cloud_run_service_test.go b/mmv1/third_party/terraform/services/cloudrun/data_source_cloud_run_service_test.go index 12c2876b7261..470acdcb690a 100644 --- a/mmv1/third_party/terraform/services/cloudrun/data_source_cloud_run_service_test.go +++ b/mmv1/third_party/terraform/services/cloudrun/data_source_cloud_run_service_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" ) func TestAccDataSourceGoogleCloudRunService_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_domain_mapping_test.go b/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_domain_mapping_test.go index e0147440263a..52fb3b281c38 100644 --- a/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_domain_mapping_test.go +++ b/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_domain_mapping_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" ) // Destroy and recreate the mapping, testing that Terraform doesn't return a 409 diff --git a/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_service_test.go.tmpl b/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_service_test.go.tmpl index 0982e5effaa8..8dd3335d4fa6 100644 --- a/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_service_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudrun/resource_cloud_run_service_test.go.tmpl @@ -4,6 +4,8 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_job_test.go b/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_job_test.go index e59989e2e0f5..bef71b3f584e 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_job_test.go +++ b/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_job_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleCloudRunV2Job_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_service_test.go b/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_service_test.go index 770d90993ad5..409ffa4c7332 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_service_test.go +++ b/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_service_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleCloudRunV2Service_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_worker_pool_test.go b/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_worker_pool_test.go index 8ff9cffa3b2e..0ec74340fe83 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_worker_pool_test.go +++ b/mmv1/third_party/terraform/services/cloudrunv2/data_source_google_cloud_run_v2_worker_pool_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" ) func TestAccDataSourceGoogleCloudRunV2WorkerPool_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_job_test.go.tmpl b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_job_test.go.tmpl index 80f80884c807..870c991043ef 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_job_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_job_test.go.tmpl @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/vpcaccess" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_test.go.tmpl b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_test.go.tmpl index a118f189046c..4e28914f4238 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_test.go.tmpl @@ -9,6 +9,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/vpcaccess" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" ) diff --git a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_zip_deploy_test.go.tmpl b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_zip_deploy_test.go.tmpl index 0bb8d3c8ab66..87b9a3a55e4a 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_zip_deploy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_service_zip_deploy_test.go.tmpl @@ -14,6 +14,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_worker_pool_test.go b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_worker_pool_test.go index 1a206fe0889d..fc1b924d058e 100644 --- a/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_worker_pool_test.go +++ b/mmv1/third_party/terraform/services/cloudrunv2/resource_cloud_run_v2_worker_pool_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccCloudRunV2WorkerPool_cloudrunv2WorkerPoolFullUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_cloud_control_test.go b/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_cloud_control_test.go index b6f64b12e2db..90e91219aab2 100644 --- a/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_cloud_control_test.go +++ b/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_cloud_control_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudsecuritycompliance" ) func testAccCloudSecurityComplianceCloudControl_basic(context map[string]interface{}) string { diff --git a/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_framework_test.go b/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_framework_test.go index 6ebe45882fe8..641ade64e93d 100644 --- a/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_framework_test.go +++ b/mmv1/third_party/terraform/services/cloudsecuritycompliance/resource_cloud_security_compliance_framework_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudsecuritycompliance" ) func testAccCloudSecurityComplianceFramework_basic(context map[string]interface{}) string { diff --git a/mmv1/third_party/terraform/services/cloudtasks/resource_cloud_tasks_queue_test.go b/mmv1/third_party/terraform/services/cloudtasks/resource_cloud_tasks_queue_test.go index eb7d61fe65ec..1c53e484a452 100644 --- a/mmv1/third_party/terraform/services/cloudtasks/resource_cloud_tasks_queue_test.go +++ b/mmv1/third_party/terraform/services/cloudtasks/resource_cloud_tasks_queue_test.go @@ -5,6 +5,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudtasks" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/colab/resource_colab_runtime_template_test.go b/mmv1/third_party/terraform/services/colab/resource_colab_runtime_template_test.go index 2101184f51ba..d910f8138833 100644 --- a/mmv1/third_party/terraform/services/colab/resource_colab_runtime_template_test.go +++ b/mmv1/third_party/terraform/services/colab/resource_colab_runtime_template_test.go @@ -14,6 +14,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/colab" + "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -38,7 +40,7 @@ func TestAccColabRuntimeTemplate_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "key_name": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "key_name": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/colab/resource_colab_runtime_test.go b/mmv1/third_party/terraform/services/colab/resource_colab_runtime_test.go index 50a2c0a2c7fc..04a98ba432f7 100644 --- a/mmv1/third_party/terraform/services/colab/resource_colab_runtime_test.go +++ b/mmv1/third_party/terraform/services/colab/resource_colab_runtime_test.go @@ -7,13 +7,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/colab" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccColabRuntime_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "key_name": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "key_name": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/colab/resource_colab_schedule_test.go b/mmv1/third_party/terraform/services/colab/resource_colab_schedule_test.go index a4eab875fe7d..5c41f2ee5368 100644 --- a/mmv1/third_party/terraform/services/colab/resource_colab_schedule_test.go +++ b/mmv1/third_party/terraform/services/colab/resource_colab_schedule_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/colab" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccColabSchedule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/composer/data_source_google_composer_environment_test.go b/mmv1/third_party/terraform/services/composer/data_source_google_composer_environment_test.go index e8bf78d776c6..4e4828d85a30 100644 --- a/mmv1/third_party/terraform/services/composer/data_source_google_composer_environment_test.go +++ b/mmv1/third_party/terraform/services/composer/data_source_google_composer_environment_test.go @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/composer" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceComposerEnvironment_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/composer/data_source_google_composer_image_versions.go b/mmv1/third_party/terraform/services/composer/data_source_google_composer_image_versions.go index 575efa7cc2e2..3cb91b9e4bab 100644 --- a/mmv1/third_party/terraform/services/composer/data_source_google_composer_image_versions.go +++ b/mmv1/third_party/terraform/services/composer/data_source_google_composer_image_versions.go @@ -62,7 +62,7 @@ func dataSourceGoogleComposerImageVersionsRead(d *schema.ResourceData, meta inte return err } - url, err := tpgresource.ReplaceVars(d, config, "{{ComposerBasePath}}projects/{{project}}/locations/{{region}}/imageVersions") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{region}}/imageVersions") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_config_map_test.go b/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_config_map_test.go index d2c6b856a2aa..99824e96d7fe 100644 --- a/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_config_map_test.go +++ b/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_config_map_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/composer" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceComposerUserWorkloadsConfigMap_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_secret_test.go b/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_secret_test.go index 3e7b477cada6..8cbe4dd0f37c 100644 --- a/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_secret_test.go +++ b/mmv1/third_party/terraform/services/composer/data_source_google_composer_user_workloads_secret_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/composer" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceComposerUserWorkloadsSecret_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_environment.go.tmpl b/mmv1/third_party/terraform/services/composer/resource_composer_environment.go.tmpl index 924e300565b6..f5064b4b6815 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_environment.go.tmpl +++ b/mmv1/third_party/terraform/services/composer/resource_composer_environment.go.tmpl @@ -160,6 +160,7 @@ func ResourceComposerEnvironment() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, tpgresource.SetLabelsDiff, @@ -1079,6 +1080,9 @@ func ResourceComposerEnvironment() *schema.Resource { }, }, }, +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -1199,10 +1203,20 @@ func resourceComposerEnvironmentRead(d *schema.ResourceData, meta interface{}) e if err := d.Set("storage_config", flattenComposerStorageConfig(res.StorageConfig)); err != nil { return fmt.Errorf("Error setting Storage: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComposerEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComposerEnvironment) { + return ResourceComposerEnvironment().Read(d, meta) + } + tfConfig := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, tfConfig.UserAgent) if err != nil { @@ -1629,6 +1643,13 @@ func resourceComposerEnvironmentPatchField(updateMask, userAgent string, env *co } func resourceComposerEnvironmentDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_environment_meta.yaml.tmpl b/mmv1/third_party/terraform/services/composer/resource_composer_environment_meta.yaml.tmpl index ffc9885d4088..152011dac829 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_environment_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/composer/resource_composer_environment_meta.yaml.tmpl @@ -98,3 +98,5 @@ fields: - api_field: 'storageConfig.bucket' - field: 'terraform_labels' provider_only: true + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_environment_test.go b/mmv1/third_party/terraform/services/composer/resource_composer_environment_test.go index 95e9a0e6a2ec..401786a122bd 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_environment_test.go +++ b/mmv1/third_party/terraform/services/composer/resource_composer_environment_test.go @@ -12,6 +12,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/composer" tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -23,7 +26,7 @@ const testComposerBucketPrefix = "tf-test-composer-bucket" const testComposerNetworkAttachmentPrefix = "tf-test-composer-nta" func bootstrapComposerServiceAgents(t *testing.T) { - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@cloudcomposer-accounts.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -93,7 +96,7 @@ func TestAccComposerEnvironment_withEncryptionConfigComposer2(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - kms := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-composer2-key1") + bootstrapped := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-composer2-key1") pid := envvar.GetTestProjectFromEnv() bootstrapComposerServiceAgents(t) envName := fmt.Sprintf("%s-%d", testComposerEnvironmentPrefix, acctest.RandInt(t)) @@ -107,7 +110,7 @@ func TestAccComposerEnvironment_withEncryptionConfigComposer2(t *testing.T) { CheckDestroy: testAccComposerEnvironmentDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccComposerEnvironment_encryptionCfg(pid, "2", "2", envName, kms.CryptoKey.Name, network, subnetwork, serviceAccount), + Config: testAccComposerEnvironment_encryptionCfg(pid, "2", "2", envName, bootstrapped.CryptoKey.Name, network, subnetwork, serviceAccount), }, { ResourceName: "google_composer_environment.test", @@ -120,7 +123,7 @@ func TestAccComposerEnvironment_withEncryptionConfigComposer2(t *testing.T) { { PlanOnly: true, ExpectNonEmptyPlan: false, - Config: testAccComposerEnvironment_encryptionCfg(pid, "2", "2", envName, kms.CryptoKey.Name, network, subnetwork, serviceAccount), + Config: testAccComposerEnvironment_encryptionCfg(pid, "2", "2", envName, bootstrapped.CryptoKey.Name, network, subnetwork, serviceAccount), Check: testAccCheckClearComposerEnvironmentFirewalls(t, network), }, }, diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_config_map_test.go b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_config_map_test.go index 03e3142a1b95..f2c0027f61c2 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_config_map_test.go +++ b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_config_map_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/services/composer" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComposerUserWorkloadsConfigMap_composerUserWorkloadsConfigMapBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret.go.tmpl b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret.go.tmpl index bccd08fff93a..c2b2f75c4ca6 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret.go.tmpl +++ b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret.go.tmpl @@ -36,6 +36,7 @@ func ResourceComposerUserWorkloadsSecret() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, ), @@ -76,7 +77,10 @@ func ResourceComposerUserWorkloadsSecret() *schema.Resource { Sensitive: true, Description: `A map of the secret data.`, }, - }, +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end + }, } } @@ -144,10 +148,20 @@ func resourceComposerUserWorkloadsSecretRead(d *schema.ResourceData, meta interf if err := d.Set("name", tpgresource.GetResourceNameFromSelfLink(res.Name)); err != nil { return fmt.Errorf("Error setting UserWorkloadsSecret Name: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComposerUserWorkloadsSecretUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComposerUserWorkloadsSecret) { + return ResourceComposerUserWorkloadsSecret().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -181,6 +195,13 @@ func resourceComposerUserWorkloadsSecretUpdate(d *schema.ResourceData, meta inte } func resourceComposerUserWorkloadsSecretDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_meta.yaml.tmpl b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_meta.yaml.tmpl index ed3331a6c445..0eefaf0f0ae5 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_meta.yaml.tmpl @@ -13,3 +13,5 @@ fields: - api_field: 'name' - field: 'project' - field: 'region' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_test.go b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_test.go index 9eaa21575cb6..4a0b1b36b437 100644 --- a/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_test.go +++ b/mmv1/third_party/terraform/services/composer/resource_composer_user_workloads_secret_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/composer" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/compute/bootstrap_test_utils.go b/mmv1/third_party/terraform/services/compute/bootstrap_test_utils.go new file mode 100644 index 000000000000..565d263ca95b --- /dev/null +++ b/mmv1/third_party/terraform/services/compute/bootstrap_test_utils.go @@ -0,0 +1,378 @@ +package compute + +import ( + "fmt" + "log" + "maps" + "testing" + "time" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +const SharedTestNetworkPrefix = "tf-bootstrap-net-" + +// BootstrapSharedTestNetwork will return a persistent compute network for a +// test or set of tests. +// +// Usage 1 +// Resources like service_networking_connection use a consumer network and +// create a complementing tenant network which we don't control. These tenant +// networks never get cleaned up and they can accumulate to the point where a +// limit is reached for the organization. By reusing a consumer network across +// test runs, we can reduce the number of tenant networks that are needed. +// See b/146351146 for more context. +// +// Usage 2 +// Bootstrap networks used in tests (gke clusters, dataproc clusters...) +// to avoid traffic to the default network +// +// testId specifies the test for which a shared network is used/initialized. +// Note that if the network is being used for a service_networking_connection, +// the same testId should generally not be used across tests, to avoid race +// conditions where multiple tests attempt to modify the connection at once. +// +// Returns the name of a network, creating it if it hasn't been created in the +// test project. +func BootstrapSharedTestNetwork(t *testing.T, testId string) string { + project := envvar.GetTestProjectFromEnv() + networkName := SharedTestNetworkPrefix + testId + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + log.Printf("[DEBUG] Getting shared test network %q", networkName) + _, err := NewClient(config, config.UserAgent).Networks.Get(project, networkName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] Network %q not found, bootstrapping", networkName) + url := fmt.Sprintf("%sprojects/%s/global/networks", transport_tpg.BaseUrl(Product, config), project) + netObj := map[string]interface{}{ + "name": networkName, + "autoCreateSubnetworks": false, + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + Body: netObj, + Timeout: 4 * time.Minute, + }) + if err != nil { + t.Fatalf("Error bootstrapping shared test network %q: %s", networkName, err) + } + + log.Printf("[DEBUG] Waiting for network creation to finish") + err = ComputeOperationWaitTime(config, res, project, "Error bootstrapping shared test network", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error bootstrapping shared test network %q: %s", networkName, err) + } + } + + network, err := NewClient(config, config.UserAgent).Networks.Get(project, networkName).Do() + if err != nil { + t.Errorf("Error getting shared test network %q: %s", networkName, err) + } + if network == nil { + t.Fatalf("Error getting shared test network %q: is nil", networkName) + } + return network.Name +} + +type AddressSettings struct { + PrefixLength int +} + +func AddressWithPrefixLength(prefixLength int) func(*AddressSettings) { + return func(settings *AddressSettings) { + settings.PrefixLength = prefixLength + } +} + +func NewAddressSettings(options ...func(*AddressSettings)) *AddressSettings { + settings := &AddressSettings{ + PrefixLength: 16, // default prefix length + } + + for _, o := range options { + o(settings) + } + return settings +} + +const SharedTestGlobalAddressPrefix = "tf-bootstrap-addr-" + +// params are the functions to set compute global address +func BootstrapSharedTestGlobalAddress(t *testing.T, testId string, params ...func(*AddressSettings)) string { + project := envvar.GetTestProjectFromEnv() + addressName := SharedTestGlobalAddressPrefix + testId + networkName := BootstrapSharedTestNetwork(t, testId) + networkId := fmt.Sprintf("projects/%v/global/networks/%v", project, networkName) + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + log.Printf("[DEBUG] Getting shared test global address %q", addressName) + _, err := NewClient(config, config.UserAgent).GlobalAddresses.Get(project, addressName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] Global address %q not found, bootstrapping", addressName) + url := fmt.Sprintf("%sprojects/%s/global/addresses", transport_tpg.BaseUrl(Product, config), project) + + settings := NewAddressSettings(params...) + + netObj := map[string]interface{}{ + "name": addressName, + "address_type": "INTERNAL", + "purpose": "VPC_PEERING", + "prefix_length": settings.PrefixLength, + "network": networkId, + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + Body: netObj, + Timeout: 4 * time.Minute, + }) + if err != nil { + t.Fatalf("Error bootstrapping shared test global address %q: %s", addressName, err) + } + + log.Printf("[DEBUG] Waiting for global address creation to finish") + err = ComputeOperationWaitTime(config, res, project, "Error bootstrapping shared test global address", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error bootstrapping shared test global address %q: %s", addressName, err) + } + } + + address, err := NewClient(config, config.UserAgent).GlobalAddresses.Get(project, addressName).Do() + if err != nil { + t.Errorf("Error getting shared test global address %q: %s", addressName, err) + } + if address == nil { + t.Fatalf("Error getting shared test global address %q: is nil", addressName) + } + return address.Name +} + +func BootstrapSubnet(t *testing.T, subnetName string, networkName string) string { + return BootstrapSubnetWithOverrides(t, subnetName, networkName, make(map[string]interface{})) +} + +func BootstrapSubnetWithOverrides(t *testing.T, subnetName string, networkName string, subnetOptions map[string]interface{}) string { + projectID := envvar.GetTestProjectFromEnv() + region := envvar.GetTestRegionFromEnv() + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + t.Fatal("Could not bootstrap config.") + } + + computeService := NewClient(config, config.UserAgent) + if computeService == nil { + t.Fatal("Could not create compute client.") + } + + // In order to create a networkAttachment we need to bootstrap a subnet. + _, err := computeService.Subnetworks.Get(projectID, region, subnetName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] Subnet %q not found, bootstrapping", subnetName) + + networkUrl := fmt.Sprintf("%sprojects/%s/global/networks/%s", transport_tpg.BaseUrl(Product, config), projectID, networkName) + url := fmt.Sprintf("%sprojects/%s/regions/%s/subnetworks", transport_tpg.BaseUrl(Product, config), projectID, region) + + defaultSubnetObj := map[string]interface{}{ + "name": subnetName, + "region ": region, + "network": networkUrl, + "ipCidrRange": "10.77.0.0/20", + } + + if len(subnetOptions) != 0 { + maps.Copy(defaultSubnetObj, subnetOptions) + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: projectID, + RawURL: url, + UserAgent: config.UserAgent, + Body: defaultSubnetObj, + Timeout: 4 * time.Minute, + }) + + log.Printf("Response is, %s", res) + if err != nil { + t.Fatalf("Error bootstrapping test subnet %s: %s", subnetName, err) + } + + log.Printf("[DEBUG] Waiting for network creation to finish") + err = ComputeOperationWaitTime(config, res, projectID, "Error bootstrapping test subnet", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error bootstrapping test subnet %s: %s", subnetName, err) + } + } + + subnet, err := computeService.Subnetworks.Get(projectID, region, subnetName).Do() + + if subnet == nil { + t.Fatalf("Error getting test subnet %s: is nil", subnetName) + } + + if err != nil { + t.Fatalf("Error getting test subnet %s: %s", subnetName, err) + } + return subnet.Name +} + +func BootstrapNetworkAttachment(t *testing.T, networkAttachmentName string, subnetName string) string { + projectID := envvar.GetTestProjectFromEnv() + region := envvar.GetTestRegionFromEnv() + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + computeService := NewClient(config, config.UserAgent) + if computeService == nil { + return "" + } + + networkAttachment, err := computeService.NetworkAttachments.Get(projectID, region, networkAttachmentName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + // Create Network Attachment Here. + log.Printf("[DEBUG] Network Attachment %s not found, bootstrapping", networkAttachmentName) + url := fmt.Sprintf("%sprojects/%s/regions/%s/networkAttachments", transport_tpg.BaseUrl(Product, config), projectID, region) + + subnetURL := fmt.Sprintf("%sprojects/%s/regions/%s/subnetworks/%s", transport_tpg.BaseUrl(Product, config), projectID, region, subnetName) + networkAttachmentObj := map[string]interface{}{ + "name": networkAttachmentName, + "region": region, + "subnetworks": []string{subnetURL}, + "connectionPreference": "ACCEPT_AUTOMATIC", + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: projectID, + RawURL: url, + UserAgent: config.UserAgent, + Body: networkAttachmentObj, + Timeout: 4 * time.Minute, + }) + if err != nil { + t.Fatalf("Error bootstrapping test Network Attachment %s: %s", networkAttachmentName, err) + } + + log.Printf("[DEBUG] Waiting for network creation to finish") + err = ComputeOperationWaitTime(config, res, projectID, "Error bootstrapping shared test subnet", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error bootstrapping test Network Attachment %s: %s", networkAttachmentName, err) + } + } + + networkAttachment, err = computeService.NetworkAttachments.Get(projectID, region, networkAttachmentName).Do() + + if networkAttachment == nil { + t.Fatalf("Error getting test network attachment %s: is nil", networkAttachmentName) + } + + if err != nil { + t.Fatalf("Error getting test Network Attachment %s: %s", networkAttachmentName, err) + } + + return networkAttachment.Name +} + +const SharedStoragePoolPrefix = "tf-bootstrap-storage-pool-" + +func BootstrapComputeStoragePool(t *testing.T, storagePoolName, storagePoolType string) string { + projectID := envvar.GetTestProjectFromEnv() + zone := envvar.GetTestZoneFromEnv() + + storagePoolName = SharedStoragePoolPrefix + storagePoolType + "-" + storagePoolName + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + t.Fatal("Could not bootstrap config.") + } + + computeService := NewClient(config, config.UserAgent) + if computeService == nil { + t.Fatal("Could not create compute client.") + } + + _, err := computeService.StoragePools.Get(projectID, zone, storagePoolName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] Storage pool %q not found, bootstrapping", storagePoolName) + + url := fmt.Sprintf("%sprojects/%s/zones/%s/storagePools", transport_tpg.BaseUrl(Product, config), projectID, zone) + storagePoolTypeUrl := fmt.Sprintf("/projects/%s/zones/%s/storagePoolTypes/%s", projectID, zone, storagePoolType) + + storagePoolObj := map[string]interface{}{ + "name": storagePoolName, + "poolProvisionedCapacityGb": 10240, + "poolProvisionedThroughput": 180, + "storagePoolType": storagePoolTypeUrl, + "capacityProvisioningType": "ADVANCED", + } + + if storagePoolType == "hyperdisk-balanced" { + storagePoolObj["poolProvisionedIops"] = 10000 + storagePoolObj["poolProvisionedThroughput"] = 1024 + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: projectID, + RawURL: url, + UserAgent: config.UserAgent, + Body: storagePoolObj, + Timeout: 20 * time.Minute, + }) + + log.Printf("Response is, %s", res) + if err != nil { + t.Fatalf("Error bootstrapping storage pool %s: %s", storagePoolName, err) + } + + log.Printf("[DEBUG] Waiting for storage pool creation to finish") + err = ComputeOperationWaitTime(config, res, projectID, "Error bootstrapping storage pool", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error bootstrapping test storage pool %s: %s", storagePoolName, err) + } + } + + storagePool, err := computeService.StoragePools.Get(projectID, zone, storagePoolName).Do() + + if storagePool == nil { + t.Fatalf("Error getting storage pool %s: is nil", storagePoolName) + } + + if err != nil { + t.Fatalf("Error getting storage pool %s: %s", storagePoolName, err) + } + + storagePoolResourceName, err := tpgresource.GetRelativePath(storagePool.SelfLink) + + if err != nil { + t.Fatal("Failed to extract Storage Pool resource name from URL.") + } + + return storagePoolResourceName +} diff --git a/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl b/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl index 3863236b923a..2b33b7cce6b6 100644 --- a/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/compute_instance_helpers.go.tmpl @@ -77,6 +77,32 @@ func flattenAliasIpRange(d *schema.ResourceData, ranges []*compute.AliasIpRange, return sorted } +{{ if ne $.TargetVersionName `ga` -}} +func flattenIpv6AliasRange(d *schema.ResourceData, ranges []*compute.AliasIpRange, i int) []map[string]interface{} { + prefix := fmt.Sprintf("network_interface.%d", i) + + configData := []map[string]interface{}{} + for _, item := range d.Get(prefix + ".alias_ipv6_range").([]interface{}) { + configData = append(configData, item.(map[string]interface{})) + } + + apiData := make([]map[string]interface{}, 0, len(ranges)) + for _, ipRange := range ranges { + apiData = append(apiData, map[string]interface{}{ + "ip_cidr_range": ipRange.IpCidrRange, + "subnetwork_range_name": ipRange.SubnetworkRangeName, + }) + } + + //permadiff fix + sorted, err := tpgresource.SortMapsByConfigOrder(configData, apiData, "ip_cidr_range") + if err != nil { + return apiData + } + return sorted +} +{{- end }} + func expandScheduling(v interface{}) (*compute.Scheduling, error) { if v == nil { // We can't set default values for lists. @@ -559,6 +585,9 @@ func flattenNetworkInterfaces(d *schema.ResourceData, config *transport_tpg.Conf "subnetwork_project": subnet.Project, "access_config": ac, "alias_ip_range": flattenAliasIpRange(d, iface.AliasIpRanges, i), + {{ if ne $.TargetVersionName `ga` -}} + "alias_ipv6_range": flattenIpv6AliasRange(d, iface.AliasIpv6Ranges, i), + {{- end }} "nic_type": iface.NicType, "stack_type": iface.StackType, "ipv6_access_config": flattenIpv6AccessConfigs(iface.Ipv6AccessConfigs), @@ -693,6 +722,9 @@ func expandNetworkInterfaces(d tpgresource.TerraformResourceData, config *transp Subnetwork: sf.RelativeLink(), AccessConfigs: expandAccessConfigs(data["access_config"].([]interface{})), AliasIpRanges: expandAliasIpRanges(data["alias_ip_range"].([]interface{})), + {{ if ne $.TargetVersionName `ga` -}} + AliasIpv6Ranges: expandAliasIpRanges(data["alias_ipv6_range"].([]interface{})), + {{- end }} NicType: data["nic_type"].(string), StackType: data["stack_type"].(string), QueueCount: int64(data["queue_count"].(int)), diff --git a/mmv1/third_party/terraform/services/compute/data_source_compute_health_check_test.go b/mmv1/third_party/terraform/services/compute/data_source_compute_health_check_test.go index 03bc06893a1b..5f98aa5d609d 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_compute_health_check_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_compute_health_check_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeHealthCheckDatasource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_group_test.go b/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_group_test.go index bd4fd55f0b58..7ee64b0ac1f9 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_group_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_group_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeNetworkEndpointGroup(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_groups_test.go b/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_groups_test.go index bacacc58301a..a56038b7f07c 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_groups_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_compute_network_endpoint_groups_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeNetworkEndpointGroups(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_compute_network_peering_test.go b/mmv1/third_party/terraform/services/compute/data_source_compute_network_peering_test.go index e458765b5b4e..137bf8aa471f 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_compute_network_peering_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_compute_network_peering_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeNetworkPeering_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_compute_security_policy_test.go b/mmv1/third_party/terraform/services/compute/data_source_compute_security_policy_test.go index 4617c7b482df..86d584c31876 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_compute_security_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_compute_security_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeSecurityPolicy_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_addresses_test.go.tmpl b/mmv1/third_party/terraform/services/compute/data_source_google_compute_addresses_test.go.tmpl index 687524b0c83f..72b2c1d69ec6 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_addresses_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_addresses_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_bucket_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_bucket_test.go index 88d99235e8af..c4e15cf77a45 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_bucket_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_bucket_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceComputeBackendBucket_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_service_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_service_test.go index d72b71999994..c260f5d80fc5 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_service_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_backend_service_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeBackendService_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_disk_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_disk_test.go index 7de5bf838180..64dbbf8fd1d0 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_disk_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_disk_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleComputeDisk_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rule_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rule_test.go index c4f26af900b1..62d10d504f39 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rule_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rule_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleForwardingRule(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rules_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rules_test.go index afc8704abc4a..3e063d09561f 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rules_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_forwarding_rules_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleForwardingRules(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_global_address_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_global_address_test.go index 05d1bb971532..f06715852ef3 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_global_address_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_global_address_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_ha_vpn_gateway_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_ha_vpn_gateway_test.go index fec6d128be81..cd3bfe5adf9c 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_ha_vpn_gateway_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_ha_vpn_gateway_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeHaVpnGateway(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_image_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_image_test.go index 8ddaba7bf035..3e1dbeafbecd 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_image_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_image_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_images_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_images_test.go index 2a0918143147..011790009f54 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_images_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_images_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeImages_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group.go index b95eccbcb0dd..9b137d65c902 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group.go @@ -79,6 +79,11 @@ func DataSourceGoogleComputeInstanceGroup() *schema.Resource { Type: schema.TypeInt, Computed: true, }, + + "deletion_policy": { + Type: schema.TypeString, + Computed: true, + }, }, } } diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_manager_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_manager_test.go index 9497d8b16641..6732232c60eb 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_manager_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_manager_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleComputeInstanceGroupManager(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_test.go index 2603417e79f5..ee2f5785cf83 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_group_test.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_guest_attributes_test.go.tmpl b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_guest_attributes_test.go similarity index 97% rename from mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_guest_attributes_test.go.tmpl rename to mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_guest_attributes_test.go index 499da60003dc..9683204f4e2b 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_guest_attributes_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_guest_attributes_test.go @@ -6,17 +6,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" - {{- if ne $.TargetVersionName "ga" }} - compute "google.golang.org/api/compute/v0.beta" -{{- else }} - compute "google.golang.org/api/compute/v1" -{{- end }} + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeInstanceGuestAttributes_basic(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_serial_port_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_serial_port_test.go index 1a8768e457fd..c2c547a49240 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_serial_port_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_serial_port_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_template_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_template_test.go index e18ddae3b9e7..f1b4d0f88ff2 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_template_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_template_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccInstanceTemplateDatasource_name(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_test.go index 5b7c9cd9b767..421fe06f364f 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_instance_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeInstance_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network.go index ce843b9eae77..ccbac0a2968e 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network.go @@ -3,6 +3,7 @@ package compute import ( "fmt" "strconv" + "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" @@ -17,7 +18,8 @@ func DataSourceGoogleComputeNetwork() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, - Required: true, + Optional: true, + Computed: true, }, "description": { @@ -54,12 +56,14 @@ func DataSourceGoogleComputeNetwork() *schema.Resource { "self_link": { Type: schema.TypeString, + Optional: true, Computed: true, }, "project": { Type: schema.TypeString, Optional: true, + Computed: true, }, "subnetworks_self_links": { @@ -78,11 +82,44 @@ func dataSourceGoogleComputeNetworkRead(d *schema.ResourceData, meta interface{} return err } - project, err := tpgresource.GetProject(d, config) - if err != nil { - return err + var project, name string + + if v, ok := d.GetOk("self_link"); ok { + // Parse project and name from the self_link. + // Network self_links have the form: + // https://www.googleapis.com/compute/v1/projects/{project}/global/networks/{name} + // or a partial path like projects/{project}/global/networks/{name} + selfLink := v.(string) + nameFromLink := tpgresource.GetResourceNameFromSelfLink(selfLink) + if nameFromLink == "" { + return fmt.Errorf("invalid self_link %q: could not extract network name", selfLink) + } + name = nameFromLink + + // Extract project from self_link + parts := strings.Split(selfLink, "/") + for i, part := range parts { + if part == "projects" && i+1 < len(parts) { + project = parts[i+1] + break + } + } + if project == "" { + // Fall back to provider project + project, err = tpgresource.GetProject(d, config) + if err != nil { + return err + } + } + } else if v, ok := d.GetOk("name"); ok { + name = v.(string) + project, err = tpgresource.GetProject(d, config) + if err != nil { + return err + } + } else { + return fmt.Errorf("must provide either `self_link` or `name`") } - name := d.Get("name").(string) id := fmt.Sprintf("projects/%s/global/networks/%s", project, name) @@ -90,6 +127,12 @@ func dataSourceGoogleComputeNetworkRead(d *schema.ResourceData, meta interface{} if err != nil { return transport_tpg.HandleDataSourceNotFoundError(err, d, fmt.Sprintf("Network Not Found : %s", name), id) } + if err := d.Set("name", network.Name); err != nil { + return fmt.Errorf("Error setting name: %s", err) + } + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error setting project: %s", err) + } if err := d.Set("gateway_ipv4", network.GatewayIPv4); err != nil { return fmt.Errorf("Error setting gateway_ipv4: %s", err) } diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_attachment_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_attachment_test.go index e05cdd09ae89..478c1b43e69d 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_attachment_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_attachment_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceComputeNetworkAttachment_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_internal_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_internal_test.go new file mode 100644 index 000000000000..107d2e1933c8 --- /dev/null +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_internal_test.go @@ -0,0 +1,58 @@ +package compute + +import ( + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" +) + +func TestDataSourceGoogleComputeNetwork_selfLinkParsing(t *testing.T) { + tests := []struct { + name string + selfLink string + wantProject string + wantName string + }{ + { + name: "full self_link", + selfLink: "https://www.googleapis.com/compute/v1/projects/my-project/global/networks/my-network", + wantProject: "my-project", + wantName: "my-network", + }, + { + name: "partial path", + selfLink: "projects/my-project/global/networks/my-network", + wantProject: "my-project", + wantName: "my-network", + }, + { + name: "beta API version", + selfLink: "https://www.googleapis.com/compute/beta/projects/test-proj/global/networks/test-net", + wantProject: "test-proj", + wantName: "test-net", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + gotName := tpgresource.GetResourceNameFromSelfLink(tc.selfLink) + if gotName != tc.wantName { + t.Errorf("GetResourceNameFromSelfLink(%q) = %q, want %q", tc.selfLink, gotName, tc.wantName) + } + + // Verify project extraction logic matches what's in the data source + parts := strings.Split(tc.selfLink, "/") + var gotProject string + for i, part := range parts { + if part == "projects" && i+1 < len(parts) { + gotProject = parts[i+1] + break + } + } + if gotProject != tc.wantProject { + t.Errorf("project from %q = %q, want %q", tc.selfLink, gotProject, tc.wantProject) + } + }) + } +} diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_test.go index 71e6d4f0caa5..3e788c8189d9 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_network_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_networks_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_networks_test.go index 9e6ec8ef291d..8396900ceba3 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_networks_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_networks_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleNetworks(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_backend_service_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_backend_service_test.go index 31423be89c9f..5f1db29452e7 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_backend_service_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_backend_service_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeRegionBackendService_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_disk_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_disk_test.go index e5ce4338f4d3..962f7c319e20 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_disk_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_disk_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleComputeRegionDisk_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_manager_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_manager_test.go index 8b5652bf6589..4d507d0f1deb 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_manager_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_manager_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleComputeRegionInstanceGroupManager(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_test.go index 24bbde48d011..c9382405ce3b 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_group_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_template_test.go.tmpl b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_template_test.go.tmpl index ec38d1af5c1e..58824153dfa4 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_template_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_instance_template_test.go.tmpl @@ -7,6 +7,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_network_endpoint_group_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_network_endpoint_group_test.go index eefccac0dd74..2befec06e0d5 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_network_endpoint_group_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_network_endpoint_group_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceRegionNetworkEndpointGroup_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_security_policy_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_security_policy_test.go index 52c0e400b84b..619123572f69 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_security_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_security_policy_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionSecurityPolicyDatasource(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_certificate_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_certificate_test.go index ad0cb802e70d..002f1070cd12 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_certificate_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_certificate_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeRegionSslCertificate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_policy_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_policy_test.go index f37c6f2a4403..c3555e556d4c 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_region_ssl_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeRegionSslPolicy(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_regions.go.tmpl b/mmv1/third_party/terraform/services/compute/data_source_google_compute_regions.go similarity index 58% rename from mmv1/third_party/terraform/services/compute/data_source_google_compute_regions.go.tmpl rename to mmv1/third_party/terraform/services/compute/data_source_google_compute_regions.go index 6cb1c359b603..1de23888133d 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_regions.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_regions.go @@ -11,11 +11,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -{{- if eq $.TargetVersionName "ga" }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} ) func DataSourceGoogleComputeRegions() *schema.Resource { @@ -43,7 +38,7 @@ func DataSourceGoogleComputeRegions() *schema.Resource { func dataSourceGoogleComputeRegionsRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -54,17 +49,41 @@ func dataSourceGoogleComputeRegionsRead(d *schema.ResourceData, meta interface{} } filter := "" if s, ok := d.GetOk("status"); ok { - filter = fmt.Sprintf(" (status eq %s)", s) + filter = fmt.Sprintf("(status eq %s)", s.(string)) } - call := NewClient(config, userAgent).Regions.List(project).Filter(filter) + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/regions") + if err != nil { + return err + } - resp, err := call.Do() + queryParams := map[string]string{ + "filter": filter, + "prettyPrint": "false", + } + url, err = transport_tpg.AddQueryParams(url, queryParams) if err != nil { return err } - regions := flattenRegions(resp.Items) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) + if err != nil { + return err + } + + var regions []string + rawItems, ok := res["items"].([]interface{}) + if !ok { + log.Printf("[DEBUG] no regions found in response") + } else { + regions = flattenRegions(rawItems) + } log.Printf("[DEBUG] Received Google Compute Regions: %q", regions) if err := d.Set("names", regions); err != nil { @@ -78,10 +97,18 @@ func dataSourceGoogleComputeRegionsRead(d *schema.ResourceData, meta interface{} return nil } -func flattenRegions(regions []*compute.Region) []string { - result := make([]string, len(regions)) - for i, region := range regions { - result[i] = region.Name +func flattenRegions(regions []interface{}) []string { + var result []string + for _, region := range regions { + regionMap, ok := region.(map[string]interface{}) + if !ok { + continue + } + name, ok := regionMap["name"].(string) + if !ok { + continue + } + result = append(result, name) } sort.Strings(result) return result @@ -89,9 +116,9 @@ func flattenRegions(regions []*compute.Region) []string { func init() { registry.Schema{ - Name: "google_compute_regions", + Name: "google_compute_regions", ProductName: "compute", - Type: registry.SchemaTypeDataSource, - Schema: DataSourceGoogleComputeRegions(), + Type: registry.SchemaTypeDataSource, + Schema: DataSourceGoogleComputeRegions(), }.Register() } diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_reservation_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_reservation_test.go index 42e74a90b7de..307211a1b4e8 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_reservation_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_reservation_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeReservation(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_nat_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_nat_test.go index f5d4ced5527f..a5b54cc9294d 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_nat_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_nat_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleComputeRouterNat_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status.go.tmpl b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status.go similarity index 53% rename from mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status.go.tmpl rename to mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status.go index 910c91ed57ed..7217d79e796d 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status.go @@ -3,15 +3,10 @@ package compute import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -{{- if eq $.TargetVersionName "ga" }} - "google.golang.org/api/compute/v1" -{{- else }} - "google.golang.org/api/compute/v0.beta" -{{- end }} ) func DataSourceGoogleComputeRouterStatus() *schema.Resource { @@ -65,7 +60,7 @@ func DataSourceGoogleComputeRouterStatus() *schema.Resource { func dataSourceComputeRouterStatusRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -79,32 +74,44 @@ func dataSourceComputeRouterStatusRead(d *schema.ResourceData, meta interface{}) if err != nil { return err } + if err := d.Set("region", region); err != nil { + return fmt.Errorf("Error setting region: %s", err) + } - var name string - if n, ok := d.GetOk("name"); ok { - name = n.(string) + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/regions/{{region}}/routers/{{name}}/getRouterStatus") + if err != nil { + return err } - resp, err := NewClient(config, userAgent).Routers.GetRouterStatus(project, region, name).Do() + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return err } - status := resp.Result + status, ok := res["result"].(map[string]interface{}) + if !ok { + return fmt.Errorf("Error parsing router status response: 'result' field not found or invalid") + } - if err := d.Set("network", status.Network); err != nil { + if err := d.Set("network", status["network"]); err != nil { return fmt.Errorf("Error setting network: %s", err) } - if err := d.Set("best_routes", flattenRoutes(status.BestRoutes)); err != nil { + if err := d.Set("best_routes", flattenRoutes(status["bestRoutes"])); err != nil { return fmt.Errorf("Error setting best_routes: %s", err) } - if err := d.Set("best_routes_for_router", flattenRoutes(status.BestRoutesForRouter)); err != nil { + if err := d.Set("best_routes_for_router", flattenRoutes(status["bestRoutesForRouter"])); err != nil { return fmt.Errorf("Error setting best_routes_for_router: %s", err) } - id, err := tpgresource.ReplaceVars(d, config, "projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/routers/{{"{{"}}name{{"}}"}}") + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/regions/{{region}}/routers/{{name}}") if err != nil { return fmt.Errorf("Error constructing id: %s", err) } @@ -113,22 +120,32 @@ func dataSourceComputeRouterStatusRead(d *schema.ResourceData, meta interface{}) return nil } -func flattenRoutes(routes []*compute.Route) []map[string]interface{} { - results := make([]map[string]interface{}, len(routes)) +func flattenRoutes(routes interface{}) []map[string]interface{} { + routeList, ok := routes.([]interface{}) + if !ok { + return nil + } + + results := make([]map[string]interface{}, len(routeList)) + + for i, route := range routeList { + routeMap, ok := route.(map[string]interface{}) + if !ok { + continue + } - for i, route := range routes { results[i] = map[string]interface{}{ - "dest_range": route.DestRange, - "name": route.Name, - "network": route.Network, - "description": route.Description, - "next_hop_gateway": route.NextHopGateway, - "next_hop_ilb": route.NextHopIlb, - "next_hop_ip": route.NextHopIp, - "next_hop_vpn_tunnel": route.NextHopVpnTunnel, - "priority": route.Priority, - "tags": route.Tags, - "next_hop_network": route.NextHopNetwork, + "dest_range": routeMap["destRange"], + "name": routeMap["name"], + "network": routeMap["network"], + "description": routeMap["description"], + "next_hop_gateway": routeMap["nextHopGateway"], + "next_hop_ilb": routeMap["nextHopIlb"], + "next_hop_ip": routeMap["nextHopIp"], + "next_hop_vpn_tunnel": routeMap["nextHopVpnTunnel"], + "priority": routeMap["priority"], + "tags": routeMap["tags"], + "next_hop_network": routeMap["nextHopNetwork"], } } @@ -137,9 +154,9 @@ func flattenRoutes(routes []*compute.Route) []map[string]interface{} { func init() { registry.Schema{ - Name: "google_compute_router_status", + Name: "google_compute_router_status", ProductName: "compute", - Type: registry.SchemaTypeDataSource, - Schema: DataSourceGoogleComputeRouterStatus(), + Type: registry.SchemaTypeDataSource, + Schema: DataSourceGoogleComputeRouterStatus(), }.Register() } diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status_test.go index 8e9df1a6214b..fa60ca7efb1e 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_status_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeRouterStatus(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_test.go index cefabe64d202..9076c7adb009 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_router_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeRouter(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_routers_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_routers_test.go index 197885c64955..3f1b8ae0cf1e 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_routers_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_routers_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleComputeRouters_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_service_attachment.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_service_attachment.go new file mode 100644 index 000000000000..bdb0ae950663 --- /dev/null +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_service_attachment.go @@ -0,0 +1,61 @@ +package compute + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-google/google/registry" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func DataSourceGoogleComputeServiceAttachment() *schema.Resource { + dsSchema := tpgresource.DatasourceSchemaFromResourceSchema(ResourceComputeServiceAttachment().Schema) + + tpgresource.AddRequiredFieldsToSchema(dsSchema, "name") + tpgresource.AddOptionalFieldsToSchema(dsSchema, "project", "region") + + return &schema.Resource{ + Read: dataSourceGoogleComputeServiceAttachmentRead, + Schema: dsSchema, + } +} + +func dataSourceGoogleComputeServiceAttachmentRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + + name := d.Get("name").(string) + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return err + } + + region, err := tpgresource.GetRegion(d, config) + if err != nil { + return err + } + + id := fmt.Sprintf("projects/%s/regions/%s/serviceAttachments/%s", project, region, name) + d.SetId(id) + + err = resourceComputeServiceAttachmentRead(d, meta) + if err != nil { + return err + } + + if d.Id() == "" { + return fmt.Errorf("%s not found", id) + } + + return nil +} + +func init() { + registry.Schema{ + Name: "google_compute_service_attachment", + ProductName: "compute", + Type: registry.SchemaTypeDataSource, + Schema: DataSourceGoogleComputeServiceAttachment(), + }.Register() +} diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_service_attachment_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_service_attachment_test.go new file mode 100644 index 000000000000..02407f4f26f5 --- /dev/null +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_service_attachment_test.go @@ -0,0 +1,104 @@ +package compute_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" +) + +func TestAccDataSourceGoogleComputeServiceAttachment_basic(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: testAccDataSourceGoogleComputeServiceAttachment_basic(context), + Check: acctest.CheckDataSourceStateMatchesResourceState( + "data.google_compute_service_attachment.default", + "google_compute_service_attachment.psc_ilb_service_attachment", + ), + }, + }, + }) +} + +func testAccDataSourceGoogleComputeServiceAttachment_basic(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_compute_network" "psc_ilb_network" { + name = "tf-test-psc-ilb-network%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "psc_ilb_producer_subnetwork" { + name = "tf-test-psc-ilb-producer-subnetwork%{random_suffix}" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + ip_cidr_range = "10.0.0.0/16" +} + +resource "google_compute_subnetwork" "psc_ilb_nat" { + name = "tf-test-psc-ilb-nat%{random_suffix}" + region = "us-west2" + + network = google_compute_network.psc_ilb_network.id + purpose = "PRIVATE_SERVICE_CONNECT" + ip_cidr_range = "10.1.0.0/16" +} + +resource "google_compute_health_check" "producer_service_health_check" { + name = "tf-test-producer-service-health-check%{random_suffix}" + + check_interval_sec = 1 + timeout_sec = 1 + tcp_health_check { + port = "80" + } +} + +resource "google_compute_region_backend_service" "producer_service_backend" { + name = "tf-test-producer-service%{random_suffix}" + region = "us-west2" + + health_checks = [google_compute_health_check.producer_service_health_check.id] +} + +resource "google_compute_forwarding_rule" "psc_ilb_target_service" { + name = "tf-test-producer-forwarding-rule%{random_suffix}" + region = "us-west2" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.psc_ilb_network.name + subnetwork = google_compute_subnetwork.psc_ilb_producer_subnetwork.name +} + +resource "google_compute_service_attachment" "psc_ilb_service_attachment" { + name = "tf-test-psc-ilb-sa%{random_suffix}" + region = "us-west2" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = false + connection_preference = "ACCEPT_AUTOMATIC" + nat_subnets = [google_compute_subnetwork.psc_ilb_nat.id] + target_service = google_compute_forwarding_rule.psc_ilb_target_service.id +} + +data "google_compute_service_attachment" "default" { + name = google_compute_service_attachment.psc_ilb_service_attachment.name + region = google_compute_service_attachment.psc_ilb_service_attachment.region + project = google_compute_service_attachment.psc_ilb_service_attachment.project + depends_on = [ + google_compute_service_attachment.psc_ilb_service_attachment, + ] +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_snapshot_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_snapshot_test.go index 5c82860e2e19..7e974d456159 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_snapshot_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_snapshot_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccSnapshotDatasource_name(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_certificate_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_certificate_test.go index 83a2f46a7c2c..1d2afeaf72de 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_certificate_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_certificate_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeSslCertificate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_policy_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_policy_test.go index 8d0e59fec7d3..528c9b850d4d 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_ssl_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleSslPolicy(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_storage_pool_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_storage_pool_test.go index 53f7f70eff69..675b0c8686de 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_storage_pool_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_storage_pool_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceComputeStoragePool_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetwork_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetwork_test.go index f166c835ca31..d239d86cd2a5 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetwork_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetwork_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetworks_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetworks_test.go index 0a6310493dc9..5c70b2cbf5f0 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetworks_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_subnetworks_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleSubnetworks_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_vpn_gateway_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_vpn_gateway_test.go index af0354e743f6..a9c88fbd7c6e 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_vpn_gateway_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_vpn_gateway_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_compute_zones.go b/mmv1/third_party/terraform/services/compute/data_source_google_compute_zones.go index c29d66f57fd2..bd3dd3a012ac 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_compute_zones.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_compute_zones.go @@ -73,7 +73,7 @@ func dataSourceGoogleComputeZonesRead(d *schema.ResourceData, meta interface{}) if pageToken != "" { params.Set("pageToken", pageToken) } - listURL := fmt.Sprintf("%sprojects/%s/zones", config.ComputeBasePath, project) + listURL := fmt.Sprintf("%sprojects/%s/zones", transport_tpg.BaseUrl(Product, config), project) listURL = fmt.Sprintf("%s?%s", listURL, params.Encode()) resp, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, diff --git a/mmv1/third_party/terraform/services/compute/data_source_google_global_compute_forwarding_rule_test.go b/mmv1/third_party/terraform/services/compute/data_source_google_global_compute_forwarding_rule_test.go index c1dbe878e351..87c3d6ebf243 100644 --- a/mmv1/third_party/terraform/services/compute/data_source_google_global_compute_forwarding_rule_test.go +++ b/mmv1/third_party/terraform/services/compute/data_source_google_global_compute_forwarding_rule_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccDataSourceGoogleGlobalForwardingRule(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/fw_data_source_google_compute_network.go.tmpl b/mmv1/third_party/terraform/services/compute/fw_data_source_google_compute_network.go.tmpl deleted file mode 100644 index e265b1e4dfbe..000000000000 --- a/mmv1/third_party/terraform/services/compute/fw_data_source_google_compute_network.go.tmpl +++ /dev/null @@ -1,187 +0,0 @@ -package compute - -import ( - "context" - "fmt" - "strconv" - - "github.com/hashicorp/terraform-plugin-framework/datasource" - "github.com/hashicorp/terraform-plugin-framework/datasource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-log/tflog" - {{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" - {{- else }} - compute "google.golang.org/api/compute/v0.beta" - {{- end }} - - "github.com/hashicorp/terraform-provider-google/google/fwmodels" - "github.com/hashicorp/terraform-provider-google/google/fwresource" - "github.com/hashicorp/terraform-provider-google/google/fwtransport" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -// Ensure the implementation satisfies the expected interfaces. -var ( - _ datasource.DataSource = &ComputeNetworkFWDataSource{} - _ datasource.DataSourceWithConfigure = &ComputeNetworkFWDataSource{} -) - -// NewComputeNetworkFWDataSource is a helper function to simplify the provider implementation. -func NewComputeNetworkFWDataSource() datasource.DataSource { - return &ComputeNetworkFWDataSource{} -} - -// ComputeNetworkFWDataSource is the data source implementation. -type ComputeNetworkFWDataSource struct { - client *compute.Service - providerConfig *transport_tpg.Config -} - -type ComputeNetworkModel struct { - Id types.String `tfsdk:"id"` - Project types.String `tfsdk:"project"` - Name types.String `tfsdk:"name"` - Description types.String `tfsdk:"description"` - NetworkId types.Int64 `tfsdk:"network_id"` - NumericId types.String `tfsdk:"numeric_id"` - GatewayIpv4 types.String `tfsdk:"gateway_ipv4"` - InternalIpv6Range types.String `tfsdk:"internal_ipv6_range"` - SelfLink types.String `tfsdk:"self_link"` - // NetworkProfile types.String `tfsdk:"network_profile"` - // SubnetworksSelfLinks types.List `tfsdk:"subnetworks_self_links"` -} - -// Metadata returns the data source type name. -func (d *ComputeNetworkFWDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_fw_compute_network" -} - -func (d *ComputeNetworkFWDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - config, ok := req.ProviderData.(*transport_tpg.Config) - if !ok { - resp.Diagnostics.AddError( - "Unexpected Data Source Configure Type", - fmt.Sprintf("Expected *transport_tpg.Config, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - return - } - - d.client = NewClient(config, config.UserAgent) - if resp.Diagnostics.HasError() { - return - } - d.providerConfig = config -} - -// Schema defines the schema for the data source. -func (d *ComputeNetworkFWDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "A data source to get network details.", - - Attributes: map[string]schema.Attribute{ - "project": schema.StringAttribute{ - Description: `The project name.`, - MarkdownDescription: `The project name.`, - Optional: true, - }, - "name": schema.StringAttribute{ - Description: `The name of the Compute network.`, - MarkdownDescription: `The name of the Compute network.`, - Required: true, - }, - "description": schema.StringAttribute{ - Description: `The description of the network.`, - MarkdownDescription: `The description of the network.`, - Computed: true, - }, - "network_id": schema.Int64Attribute{ - Description: `The network ID.`, - MarkdownDescription: `The network ID.`, - Computed: true, - }, - "numeric_id": schema.StringAttribute{ - Description: `The numeric ID of the network. Deprecated in favor of network_id.`, - MarkdownDescription: `The numeric ID of the network. Deprecated in favor of network_id.`, - Computed: true, - DeprecationMessage: "`numeric_id` is deprecated and will be removed in a future major release. Use `network_id` instead.", - }, - "gateway_ipv4": schema.StringAttribute{ - Description: `The gateway address for default routing out of the network.`, - MarkdownDescription: `The gateway address for default routing out of the network.`, - Computed: true, - }, - "internal_ipv6_range": schema.StringAttribute{ - Description: `The internal ipv6 address range of the network.`, - MarkdownDescription: `The internal ipv6 address range of the network.`, - Computed: true, - }, - "self_link": schema.StringAttribute{ - Description: `The network self link.`, - MarkdownDescription: `The network self link.`, - Computed: true, - }, - // This is included for backwards compatibility with the original, SDK-implemented data source. - "id": schema.StringAttribute{ - Description: "Project identifier", - MarkdownDescription: "Project identifier", - Computed: true, - }, - }, - } -} - -// Read refreshes the Terraform state with the latest data. -func (d *ComputeNetworkFWDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var data ComputeNetworkModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.Config.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - - // Use provider_meta to set User-Agent - d.client.UserAgent = fwtransport.GenerateFrameworkUserAgentString(metaData, d.client.UserAgent) - - project := fwresource.GetProjectFramework(data.Project, types.StringValue(d.providerConfig.Project), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - // GET Request - clientResp, err := d.client.Networks.Get(project.ValueString(), data.Name.ValueString()).Do() - if err != nil { - fwtransport.HandleNotFoundError(ctx, err, &resp.State, fmt.Sprintf("dataSourceComputeNetwork %q", data.Name.ValueString()), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - } - - tflog.Trace(ctx, "read compute network data source") - - // Put data in model - id := fmt.Sprintf("projects/%s/global/networks/%s", project.ValueString(), clientResp.Name) - data.Id = types.StringValue(id) - data.Description = types.StringValue(clientResp.Description) - data.NetworkId = types.Int64Value(int64(clientResp.Id)) - data.NumericId = types.StringValue(strconv.Itoa(int(clientResp.Id))) - data.GatewayIpv4 = types.StringValue(clientResp.GatewayIPv4) - data.InternalIpv6Range = types.StringValue(clientResp.InternalIpv6Range) - data.SelfLink = types.StringValue(clientResp.SelfLink) - - // Save data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} diff --git a/mmv1/third_party/terraform/services/compute/fw_data_source_google_compute_network_test.go b/mmv1/third_party/terraform/services/compute/fw_data_source_google_compute_network_test.go deleted file mode 100644 index ae82326c793d..000000000000 --- a/mmv1/third_party/terraform/services/compute/fw_data_source_google_compute_network_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package compute_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/terraform" - "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" -) - -func TestAccDataSourceGoogleFWNetwork(t *testing.T) { - t.Parallel() - - networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - Steps: []resource.TestStep{ - { - Config: testAccDataSourceGoogleNetworkFWConfig(networkName), - Check: resource.ComposeTestCheckFunc( - testAccDataSourceGoogleFWNetworkCheck("data.google_fw_compute_network.my_network", "google_compute_network.foobar"), - ), - }, - }, - }) -} - -func testAccDataSourceGoogleFWNetworkCheck(data_source_name string, resource_name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - ds, ok := s.RootModule().Resources[data_source_name] - if !ok { - return fmt.Errorf("root module has no resource called %s", data_source_name) - } - - rs, ok := s.RootModule().Resources[resource_name] - if !ok { - return fmt.Errorf("can't find %s in state", resource_name) - } - - ds_attr := ds.Primary.Attributes - rs_attr := rs.Primary.Attributes - network_attrs_to_test := []string{ - "id", - "name", - "network_id", - "numeric_id", - "description", - "internal_ipv6_range", - } - - for _, attr_to_check := range network_attrs_to_test { - if ds_attr[attr_to_check] != rs_attr[attr_to_check] { - return fmt.Errorf( - "%s is %s; want %s", - attr_to_check, - ds_attr[attr_to_check], - rs_attr[attr_to_check], - ) - } - } - - if !tpgresource.CompareSelfLinkOrResourceName("", ds_attr["self_link"], rs_attr["self_link"], nil) && ds_attr["self_link"] != rs_attr["self_link"] { - return fmt.Errorf("self link does not match: %s vs %s", ds_attr["self_link"], rs_attr["self_link"]) - } - - return nil - } -} - -func testAccDataSourceGoogleNetworkFWConfig(name string) string { - return fmt.Sprintf(` -resource "google_compute_network" "foobar" { - name = "%s" - description = "my-description" - enable_ula_internal_ipv6 = true - auto_create_subnetworks = false -} - -data "google_fw_compute_network" "my_network" { - name = google_compute_network.foobar.name -} -`, name) -} diff --git a/mmv1/third_party/terraform/services/compute/iam_compute_instance_test.go b/mmv1/third_party/terraform/services/compute/iam_compute_instance_test.go index 6a8ec4585c33..7d2fd2ece962 100644 --- a/mmv1/third_party/terraform/services/compute/iam_compute_instance_test.go +++ b/mmv1/third_party/terraform/services/compute/iam_compute_instance_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) // Even though the resource has generated tests, keep this one around until we are able to generate diff --git a/mmv1/third_party/terraform/services/compute/iam_compute_storage_pool_test.go b/mmv1/third_party/terraform/services/compute/iam_compute_storage_pool_test.go index 004596c1cb50..877f4647bc49 100644 --- a/mmv1/third_party/terraform/services/compute/iam_compute_storage_pool_test.go +++ b/mmv1/third_party/terraform/services/compute/iam_compute_storage_pool_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/iam_compute_subnetwork_test.go b/mmv1/third_party/terraform/services/compute/iam_compute_subnetwork_test.go index 376c7a5c7cb2..ee5e23109342 100644 --- a/mmv1/third_party/terraform/services/compute/iam_compute_subnetwork_test.go +++ b/mmv1/third_party/terraform/services/compute/iam_compute_subnetwork_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // Even though the resource has generated tests, keep this one around until we are able to generate diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_address_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_address_test.go index b6590eb9ebac..b6eb29d8aecd 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_address_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_address_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeAddress_networkTier(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk.go.tmpl index a59374f59ddb..d31260ed6a01 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk.go.tmpl @@ -21,6 +21,7 @@ func ResourceComputeAttachedDisk() *schema.Resource { return &schema.Resource{ Create: resourceAttachedDiskCreate, Read: resourceAttachedDiskRead, + Update: resourceAttachedDiskUpdate, Delete: resourceAttachedDiskDelete, Importer: &schema.ResourceImporter{ @@ -33,6 +34,7 @@ func ResourceComputeAttachedDisk() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, computeAttachedDiskDefaultProviderZone, ), @@ -88,7 +90,9 @@ func ResourceComputeAttachedDisk() *schema.Resource { Description: `The disk interface used for attaching this disk. One of SCSI or NVME. (This field is only used for specific cases, please don't specify this field without advice from Google.)`, ValidateFunc: validation.StringInSlice([]string{"SCSI", "NVME"}, false), }, - +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -219,11 +223,30 @@ func resourceAttachedDiskRead(d *schema.ResourceData, meta interface{}) error { if err := d.Set("disk", diskPath); err != nil { return fmt.Errorf("Error setting disk: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } +//UDP update start +func resourceAttachedDiskUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceAttachedDiskRead(d, meta) +} +//UDP update end + func resourceAttachedDiskDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk_meta.yaml.tmpl index a884a93bc311..d1bf506b370a 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_attached_disk_meta.yaml.tmpl @@ -19,3 +19,5 @@ fields: field: 'mode' - field: 'project' - api_field: 'zone' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_autoscaler_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_autoscaler_test.go.tmpl index 941995a1fa19..987d80639417 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_autoscaler_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_autoscaler_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_signed_url_key_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_signed_url_key_test.go index 5bf280b8d75a..90c9adf9f889 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_signed_url_key_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_signed_url_key_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -93,7 +95,7 @@ func checkComputeBackendBucketSignedUrlKeyExists(t *testing.T, s *terraform.Stat config := acctest.GoogleProviderConfig(t) keyName := rs.Primary.Attributes["name"] - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/global/backendBuckets/{{backend_bucket}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(compute.Product, config)+"projects/{{project}}/global/backendBuckets/{{backend_bucket}}") if err != nil { return false, err } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_test.go index fba388d035cd..0879f1766025 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_backend_bucket_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_signed_url_key_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_signed_url_key_test.go index c41d1bf95d5a..ccb1883877a4 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_signed_url_key_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_signed_url_key_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -93,7 +94,7 @@ func checkComputeBackendServiceSignedUrlKeyExists(t *testing.T, s *terraform.Sta config := acctest.GoogleProviderConfig(t) keyName := rs.Primary.Attributes["name"] - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/global/backendServices/{{backend_service}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(compute.Product, config)+"projects/{{project}}/global/backendServices/{{backend_service}}") if err != nil { return false, err } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_test.go.tmpl index 9a0cbb01c34a..5139a3d91b0d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_backend_service_test.go.tmpl @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_cross_site_network_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_cross_site_network_test.go index fa09228f23fb..461a74493917 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_cross_site_network_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_cross_site_network_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeCrossSiteNetwork_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication.go b/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication.go index 533a6cff96f4..f7cd007b5e80 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -18,12 +19,17 @@ func ResourceComputeDiskAsyncReplication() *schema.Resource { return &schema.Resource{ Create: resourceDiskAsyncReplicationCreate, Read: resourceDiskAsyncReplicationRead, + Update: resourceDiskAsyncReplicationUpdate, Delete: resourceDiskAsyncReplicationDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(5 * time.Minute), Delete: schema.DefaultTimeout(5 * time.Minute), @@ -60,6 +66,9 @@ func ResourceComputeDiskAsyncReplication() *schema.Resource { }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -272,10 +281,30 @@ func resourceDiskAsyncReplicationRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error setting secondary_disk: %s", err) } d.SetId(resourceId) + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceDiskAsyncReplicationUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceDiskAsyncReplicationRead(d, meta) +} + +//UDP update end + func resourceDiskAsyncReplicationDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config, userAgent, err := asyncReplicationGetConfigAndUserAgent(d, meta) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_meta.yaml.tmpl index 69d33886b644..23e13e99e07f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_meta.yaml.tmpl @@ -13,3 +13,5 @@ fields: field: 'secondary_disk.disk' - api_field: 'resourceStatus.asyncSecondaryDisks' field: 'secondary_disk.state' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_test.go.tmpl index 7cea74a407cf..dd2f2e52724d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_disk_async_replication_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_disk_resource_policy_attachment_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_disk_resource_policy_attachment_test.go index 5e1dd7fd129a..5e9f8c082b01 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_disk_resource_policy_attachment_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_disk_resource_policy_attachment_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeDiskResourcePolicyAttachment_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_disk_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_disk_test.go.tmpl index b9164942f736..8d3194a26ddd 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_disk_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_disk_test.go.tmpl @@ -10,8 +10,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/envvar" tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -654,13 +658,13 @@ func TestAccComputeDisk_encryption(t *testing.T) { func TestAccComputeDisk_encryptionKMS(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) pid := envvar.GetTestProjectFromEnv() diskName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) importID := fmt.Sprintf("%s/%s/%s", pid, "us-central1-a", diskName) var disk map[string]interface{} - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -673,7 +677,7 @@ func TestAccComputeDisk_encryptionKMS(t *testing.T) { CheckDestroy: testAccCheckComputeDiskDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccComputeDisk_encryptionKMS(diskName, kms.CryptoKey.Name), + Config: testAccComputeDisk_encryptionKMS(diskName, bootstrapped.CryptoKey.Name), Check: resource.ComposeTestCheckFunc( testAccCheckComputeDiskExists( t, "google_compute_disk.foobar", pid, &disk), @@ -696,7 +700,7 @@ func TestAccComputeDisk_pdHyperDiskEnableConfidentialCompute(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms": acctest.BootstrapKMSKeyWithPurposeInLocationAndName( + "kms": kms.BootstrapKMSKeyWithPurposeInLocationAndName( t, "ENCRYPT_DECRYPT", "us-central1", @@ -1208,7 +1212,7 @@ func TestAccComputeDisk_createSnapshotBeforeDestroy(t *testing.T) { "disk_name2": fmt.Sprintf("test-%s", acctest.RandString(t, 44)), //this is over the snapshot character creation limit of 48 "disk_name3": fmt.Sprintf("tf-test-disk-%s", acctest.RandString(t, 10)), "snapshot_prefix": fmt.Sprintf("tf-test-snapshot-%s", acctest.RandString(t, 10)), - "kms_key_self_link": acctest.BootstrapKMSKey(t).CryptoKey.Name, + "kms_key_self_link": kms.BootstrapKMSKey(t).CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "ieCx/NcW06PcT7Ep1X6LUTc/hLvUDYyzSZPPVCVPTVEohpeHASqC8uw5TzyO9U+Fka9JFHz0mBibXUInrC/jEk014kCK/NPjYgEMOyssZ4ZINPKxlUh2zn1bV+MCaTICrdmuSBTWlUUiFoDD6PYznLwh8ZNdaheCeZ8ewEXgFQ8V+sDroLaN3Xs3MDTXQEMMoNUXMCZEIpg9Vtp9x2oeQ5lAbtt7bYAAHf5l+gJWw3sUfs0/Glw5fpdjT8Uggrr+RMZezGrltJEF293rvTIjWOEB3z5OHyHwQkvdrPDFcTqsLfh+8Hr8g+mf+7zVPEC8nEbqpdl3GPv3A7AwpFp7MA==", } @@ -1960,7 +1964,7 @@ resource "google_compute_disk" "foobar" { func TestAccComputeDisk_storagePoolSpecified(t *testing.T) { t.Parallel() - storagePoolNameLong := acctest.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-throughput") + storagePoolNameLong := tpgcompute.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-throughput") diskName := fmt.Sprintf("tf-test-disk-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1982,7 +1986,7 @@ func TestAccComputeDisk_storagePoolSpecified(t *testing.T) { func TestAccComputeDisk_storagePoolSpecified_nameOnly(t *testing.T) { t.Parallel() - acctest.BootstrapComputeStoragePool(t, "basic-2", "hyperdisk-throughput") + tpgcompute.BootstrapComputeStoragePool(t, "basic-2", "hyperdisk-throughput") diskName := fmt.Sprintf("tf-test-disk-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_external_vpn_gateway_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_external_vpn_gateway_test.go index c1a0d36cb6cd..6923e5907e66 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_external_vpn_gateway_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_external_vpn_gateway_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_association_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_association_test.go index a3f6a3b6df87..8dd249689756 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_association_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_association_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeFirewallPolicyAssociation_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_rule_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_rule_test.go index baf97eb84e78..c4bab979a321 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_rule_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_rule_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeFirewallPolicyRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_test.go index 76ccb0720cbf..f56a139798d7 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_test.go @@ -4,6 +4,8 @@ import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_with_rules_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_with_rules_test.go index 7423fee3b20f..05211d5d8b35 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_with_rules_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_policy_with_rules_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeFirewallPolicyWithRules_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_test.go index 1ba316dc5250..bdebde8ac0f5 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_firewall_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_firewall_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_forwarding_rule_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_forwarding_rule_test.go.tmpl index eda66bda4bc9..767c67596e39 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_forwarding_rule_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_forwarding_rule_test.go.tmpl @@ -4,8 +4,11 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicedirectory" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/plancheck" ) func TestAccComputeForwardingRule_update(t *testing.T) { @@ -230,6 +233,38 @@ func TestAccComputeForwardingRule_forwardingRuleVpcPscExampleUpdate(t *testing.T }) } +func TestAccComputeForwardingRule_forwardingRulePscTargetUpdateRecreate(t *testing.T) { + t.Parallel() + +context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeForwardingRuleDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeForwardingRule_forwardingRulePscTargetUpdateRecreate(context, false), + }, + { + ResourceName: "google_compute_forwarding_rule.default", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeForwardingRule_forwardingRulePscTargetUpdateRecreate(context, true), + ConfigPlanChecks: resource.ConfigPlanChecks{ + PreApply: []plancheck.PlanCheck{ + plancheck.ExpectResourceAction("google_compute_forwarding_rule.default", plancheck.ResourceActionReplace), + }, + }, + }, + }, + }) +} + func TestAccComputeForwardingRule_forwardingRulePscRecreate(t *testing.T) { t.Parallel() @@ -876,6 +911,142 @@ resource "google_compute_health_check" "producer_service_health_check" { `, context) } +func testAccComputeForwardingRule_forwardingRulePscTargetUpdateRecreate(context map[string]interface{}, useSecondTarget bool) string { + var targetService string + if useSecondTarget { + targetService = "google_compute_service_attachment.producer_service_attachment_two.self_link" + } else { + targetService = "google_compute_service_attachment.producer_service_attachment_one.self_link" + } + context["target_service"] = targetService + + return acctest.Nprintf(` +// Consumer side +resource "google_compute_forwarding_rule" "default" { + name = "tf-test-psc-endpoint%{random_suffix}" + region = "us-central1" + load_balancing_scheme = "" + target = %{target_service} + network = google_compute_network.consumer_net.name + ip_address = google_compute_address.consumer_address.id + allow_psc_global_access = true +} + +resource "google_compute_network" "consumer_net" { + name = "tf-test-consumer-net%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "consumer_subnet" { + name = "tf-test-consumer-net%{random_suffix}" + ip_cidr_range = "10.0.0.0/16" + region = "us-central1" + network = google_compute_network.consumer_net.id +} + +resource "google_compute_address" "consumer_address" { + name = "tf-test-website-ip%{random_suffix}-1" + region = "us-central1" + subnetwork = google_compute_subnetwork.consumer_subnet.id + address_type = "INTERNAL" +} + + +// Producer service attachment + +resource "google_compute_network" "producer_net" { + name = "tf-test-producer-net%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "producer_subnet" { + name = "tf-test-producer-net%{random_suffix}" + ip_cidr_range = "10.0.0.0/16" + region = "us-central1" + network = google_compute_network.producer_net.id +} + +resource "google_compute_subnetwork" "psc_producer_nat_subnet_one" { + name = "tf-test-producer-psc-net-one%{random_suffix}" + ip_cidr_range = "10.1.0.0/16" + region = "us-central1" + + purpose = "PRIVATE_SERVICE_CONNECT" + network = google_compute_network.producer_net.id +} + +resource "google_compute_subnetwork" "psc_producer_nat_subnet_two" { + name = "tf-test-producer-psc-net-two%{random_suffix}" + ip_cidr_range = "10.2.0.0/16" + region = "us-central1" + + purpose = "PRIVATE_SERVICE_CONNECT" + network = google_compute_network.producer_net.id +} + +resource "google_compute_service_attachment" "producer_service_attachment_one" { + name = "tf-test-producer-service-one%{random_suffix}" + region = "us-central1" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = true + connection_preference = "ACCEPT_AUTOMATIC" + nat_subnets = [google_compute_subnetwork.psc_producer_nat_subnet_one.name] + target_service = google_compute_forwarding_rule.producer_target_service_one.id +} + +resource "google_compute_service_attachment" "producer_service_attachment_two" { + name = "tf-test-producer-service-two%{random_suffix}" + region = "us-central1" + description = "A service attachment configured with Terraform" + + enable_proxy_protocol = true + connection_preference = "ACCEPT_AUTOMATIC" + nat_subnets = [google_compute_subnetwork.psc_producer_nat_subnet_two.name] + target_service = google_compute_forwarding_rule.producer_target_service_two.id +} + +resource "google_compute_forwarding_rule" "producer_target_service_one" { + name = "tf-test-producer-forwarding-rule-one%{random_suffix}" + region = "us-central1" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.producer_net.name + subnetwork = google_compute_subnetwork.producer_subnet.name +} + +resource "google_compute_forwarding_rule" "producer_target_service_two" { + name = "tf-test-producer-forwarding-rule-two%{random_suffix}" + region = "us-central1" + + load_balancing_scheme = "INTERNAL" + backend_service = google_compute_region_backend_service.producer_service_backend.id + all_ports = true + network = google_compute_network.producer_net.name + subnetwork = google_compute_subnetwork.producer_subnet.name +} + +resource "google_compute_region_backend_service" "producer_service_backend" { + name = "tf-test-producer-service-backend%{random_suffix}" + region = "us-central1" + + health_checks = [google_compute_health_check.producer_service_health_check.id] +} + +resource "google_compute_health_check" "producer_service_health_check" { + name = "tf-test-producer-service-health-check%{random_suffix}" + + check_interval_sec = 1 + timeout_sec = 1 + tcp_health_check { + port = "80" + } +} +`, context) +} + func testAccComputeForwardingRule_forwardingRuleRegionalSteeringExampleUpdate(context map[string]interface{}) string { return acctest.Nprintf(` resource "google_compute_forwarding_rule" "steering" { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_future_reservation_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_future_reservation_test.go.tmpl index 0bbd33c9b89e..3d4674b70ccd 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_future_reservation_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_future_reservation_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/plancheck" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_global_address_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_global_address_test.go index 4748818ec51a..ea79a34a4321 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_global_address_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_global_address_test.go @@ -3,6 +3,7 @@ package compute_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_global_network_endpoint_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_global_network_endpoint_test.go index 73a249356d51..b58efca99c4e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_global_network_endpoint_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_global_network_endpoint_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeGlobalNetworkEndpoint_networkEndpointsBasic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_ha_vpn_gateway_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_ha_vpn_gateway_test.go index 2621722213ee..1271b0610164 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_ha_vpn_gateway_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_ha_vpn_gateway_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_health_check_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_health_check_test.go.tmpl index 8047a869332c..14fd666c2cd6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_health_check_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_health_check_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeHealthCheck_tcp_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_https_health_check_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_https_health_check_test.go index e217395fd1cc..841117283049 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_https_health_check_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_https_health_check_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeHttpsHealthCheck_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_image_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_image_test.go.tmpl index d9d256f65f23..ef3a47de9d04 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_image_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_image_test.go.tmpl @@ -6,9 +6,13 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/envvar" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/tpgresource" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -315,7 +319,7 @@ func TestAccComputeImage_resolveImage(t *testing.T) { func TestAccComputeImage_imageEncryptionKey(t *testing.T) { t.Parallel() - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") kmsKeyName := tpgresource.GetResourceNameFromSelfLink(kmsKey.CryptoKey.Name) kmsRingName := tpgresource.GetResourceNameFromSelfLink(kmsKey.KeyRing.Name) @@ -341,7 +345,7 @@ func TestAccComputeImage_sourceImageEncryptionKey(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_self_link": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "kms_key_self_link": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "fB6BS8tJGhGVDZDjGt1pwUo2wyNbkzNxgH1avfOtiwB9X6oPG94gWgenygitnsYJyKjdOJ7DyXLmxwQOSmnCYCUBWdKCSssyLV5907HL2mb5TfqmgHk5JcArI/t6QADZWiuGtR+XVXqiLa5B9usxFT2BTmbHvSKfkpJ7McCNc/3U0PQR8euFRZ9i75o/w+pLHFMJ05IX3JB0zHbXMV173PjObiV3ItSJm2j3mp5XKabRGSA5rmfMnHIAMz6stGhcuom6+bMri2u/axmPsdxmC6MeWkCkCmPjaKsVz1+uQUNCJkAnzesluhoD+R6VjFDm4WI7yYabu4MOOAOTaQXdEg==", } @@ -363,7 +367,7 @@ func TestAccComputeImage_sourceSnapshotEncryptionKey(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_self_link": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "kms_key_self_link": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "fB6BS8tJGhGVDZDjGt1pwUo2wyNbkzNxgH1avfOtiwB9X6oPG94gWgenygitnsYJyKjdOJ7DyXLmxwQOSmnCYCUBWdKCSssyLV5907HL2mb5TfqmgHk5JcArI/t6QADZWiuGtR+XVXqiLa5B9usxFT2BTmbHvSKfkpJ7McCNc/3U0PQR8euFRZ9i75o/w+pLHFMJ05IX3JB0zHbXMV173PjObiV3ItSJm2j3mp5XKabRGSA5rmfMnHIAMz6stGhcuom6+bMri2u/axmPsdxmC6MeWkCkCmPjaKsVz1+uQUNCJkAnzesluhoD+R6VjFDm4WI7yYabu4MOOAOTaQXdEg==", } @@ -385,7 +389,7 @@ func TestAccComputeImage_sourceDiskEncryptionKey(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_self_link": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "kms_key_self_link": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "fB6BS8tJGhGVDZDjGt1pwUo2wyNbkzNxgH1avfOtiwB9X6oPG94gWgenygitnsYJyKjdOJ7DyXLmxwQOSmnCYCUBWdKCSssyLV5907HL2mb5TfqmgHk5JcArI/t6QADZWiuGtR+XVXqiLa5B9usxFT2BTmbHvSKfkpJ7McCNc/3U0PQR8euFRZ9i75o/w+pLHFMJ05IX3JB0zHbXMV173PjObiV3ItSJm2j3mp5XKabRGSA5rmfMnHIAMz6stGhcuom6+bMri2u/axmPsdxmC6MeWkCkCmPjaKsVz1+uQUNCJkAnzesluhoD+R6VjFDm4WI7yYabu4MOOAOTaQXdEg==", } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl index 9905532a2944..cacba3a76d83 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance.go.tmpl @@ -747,6 +747,29 @@ func ResourceComputeInstance() *schema.Resource { }, }, + {{ if ne $.TargetVersionName `ga` -}} + "alias_ipv6_range": { + Type: schema.TypeList, + Optional: true, + Description: `An array of IPv6 alias IP ranges for this network interface.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ip_cidr_range": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: IpCidrRangeDiffSuppress, + Description: `The IPv6 CIDR range represented by this alias IP range.`, + }, + "subnetwork_range_name": { + Type: schema.TypeString, + Optional: true, + Description: `The subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IP range.`, + }, + }, + }, + }, + {{- end }} + "stack_type": { Type: schema.TypeString, Optional: true, @@ -1693,8 +1716,12 @@ be from 0 to 999,999,999 inclusive.`, Description: `Specifies whether the disks restored from source snapshots or source machine image should erase Windows specific VSS signature.`, }, {{- end }} +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderZone, customdiff.If( @@ -1919,18 +1946,40 @@ func getAllStatusBut(status string) []string { } func changeInstanceStatusOnCreation(config *transport_tpg.Config, d *schema.ResourceData, project, zone, status, userAgent string) error { - var op *compute.Operation + var res map[string]interface{} var err error if status == "TERMINATED" { - op, err = NewClient(config, userAgent).Instances.Stop(project, zone, d.Get("name").(string)).Do() + var url string + url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/stop") + if err != nil { + return fmt.Errorf("Error changing instance status after creation: %s", err) + } + res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) } else if status == "SUSPENDED" { - op, err = NewClient(config, userAgent).Instances.Suspend(project, zone, d.Get("name").(string)).Do() + var url string + url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/suspend") + if err != nil { + return fmt.Errorf("Error changing instance status after creation: %s", err) + } + res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) } if err != nil { return fmt.Errorf("Error changing instance status after creation: %s", err) } - waitErr := ComputeOperationWaitTime(config, op, project, "changing instance status", userAgent, d.Timeout(schema.TimeoutCreate)) + waitErr := ComputeOperationWaitTime(config, res, project, "changing instance status", userAgent, d.Timeout(schema.TimeoutCreate)) if waitErr != nil { d.SetId("") return waitErr @@ -2010,7 +2059,22 @@ func resourceComputeInstanceCreate(d *schema.ResourceData, meta interface{}) err {{- end }} log.Printf("[INFO] Requesting instance creation") - op, err := NewClient(config, userAgent).Instances.Insert(project, zone.Name, instance).Do() + instanceBody, err := tpgresource.ConvertToMap(instance) + if err != nil { + return fmt.Errorf("Error converting instance: %s", err) + } + insertUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: insertUrl, + UserAgent: userAgent, + Body: instanceBody, + }) if err != nil { return fmt.Errorf("Error creating instance: %s", err) } @@ -2019,7 +2083,7 @@ func resourceComputeInstanceCreate(d *schema.ResourceData, meta interface{}) err d.SetId(fmt.Sprintf("projects/%s/zones/%s/instances/%s", project, z, instance.Name)) // Wait for the operation to complete - waitErr := ComputeOperationWaitTime(config, op, project, "instance to create", userAgent, d.Timeout(schema.TimeoutCreate)) + waitErr := ComputeOperationWaitTime(config, res, project, "instance to create", userAgent, d.Timeout(schema.TimeoutCreate)) if waitErr != nil { // The resource didn't actually create d.SetId("") @@ -2376,10 +2440,20 @@ func resourceComputeInstanceRead(d *schema.ResourceData, meta interface{}) error d.SetId(fmt.Sprintf("projects/%s/zones/%s/instances/%s", project, zone, instance.Name)) + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeInstance) { + return ResourceComputeInstance().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -2519,13 +2593,27 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if err := tpgresource.Convert(tags, tagsV1); err != nil { return err } - op, err := NewClient(config, userAgent).Instances.SetTags( - project, zone, d.Get("name").(string), tagsV1).Do() + tagsBody, err := tpgresource.ConvertToMap(tagsV1) + if err != nil { + return fmt.Errorf("Error converting tags: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setTags") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: tagsBody, + }) if err != nil { return fmt.Errorf("Error updating tags: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "tags to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "tags to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2536,12 +2624,27 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err labelFingerprint := d.Get("label_fingerprint").(string) req := compute.InstancesSetLabelsRequest{Labels: labels, LabelFingerprint: labelFingerprint} - op, err := NewClient(config, userAgent).Instances.SetLabels(project, zone, instance.Name, &req).Do() + labelsBody, err := tpgresource.ConvertToMap(&req) + if err != nil { + return fmt.Errorf("Error converting labels: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setLabels") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: labelsBody, + }) if err != nil { return fmt.Errorf("Error updating labels: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "labels to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "labels to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2585,12 +2688,27 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if len(instance.ResourcePolicies) > 0 { req := compute.InstancesRemoveResourcePoliciesRequest{ResourcePolicies: instance.ResourcePolicies} - op, err := NewClient(config, userAgent).Instances.RemoveResourcePolicies(project, zone, instance.Name, &req).Do() + body, err := tpgresource.ConvertToMap(&req) + if err != nil { + return fmt.Errorf("Error converting remove resource policies request: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/removeResourcePolicies") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return fmt.Errorf("Error removing existing resource policies: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "resource policies to remove", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "resource policies to remove", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2600,12 +2718,27 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if len(resourcePolicies) > 0 { req := compute.InstancesAddResourcePoliciesRequest{ResourcePolicies: resourcePolicies} - op, err := NewClient(config, userAgent).Instances.AddResourcePolicies(project, zone, instance.Name, &req).Do() + body, err := tpgresource.ConvertToMap(&req) + if err != nil { + return fmt.Errorf("Error converting add resource policies request: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/addResourcePolicies") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return fmt.Errorf("Error adding resource policies: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "resource policies to add", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "resource policies to add", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2620,14 +2753,28 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error creating request data to update scheduling: %s", err) } - op, err := NewClient(config, userAgent).Instances.SetScheduling( - project, zone, instance.Name, scheduling).Do() + schedulingBody, err := tpgresource.ConvertToMap(scheduling) + if err != nil { + return fmt.Errorf("Error converting scheduling: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setScheduling") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: schedulingBody, + }) if err != nil { return fmt.Errorf("Error updating scheduling policy: %s", err) } opErr := ComputeOperationWaitTime( - config, op, project, "scheduling policy update", userAgent, + config, res, project, "scheduling policy update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr @@ -2759,11 +2906,30 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if commonAliasIpRanges := CheckForCommonAliasIp(instNetworkInterface, networkInterface); len(commonAliasIpRanges) > 0 { ni.AliasIpRanges = commonAliasIpRanges } - op, err := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, ni).Do() + niBody, err := tpgresource.ConvertToMap(ni) + if err != nil { + return errwrap.Wrapf("Error converting network interface: {{"{{"}}err{{"}}"}}", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateNetworkInterface") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"networkInterface": networkName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: niBody, + }) if err != nil { return errwrap.Wrapf("Error removing alias_ip_range: {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "updating alias ip ranges", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "updating alias ip ranges", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2779,16 +2945,84 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err AliasIpRanges: networkInterface.AliasIpRanges, Fingerprint: instNetworkInterface.Fingerprint, } + niBody, err := tpgresource.ConvertToMap(networkInterfacePatchObj) + if err != nil { + return errwrap.Wrapf("Error converting network interface: {{"{{"}}err{{"}}"}}", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateNetworkInterface") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"networkInterface": networkName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: niBody, + }) + if err != nil { + return errwrap.Wrapf("Error updating network interface: {{"{{"}}err{{"}}"}}", err) + } + opErr := ComputeOperationWaitTime(config, res, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + if opErr != nil { + return opErr + } + } + +{{ if ne $.TargetVersionName `ga` -}} + if !updateDuringStop && d.HasChange(prefix+".alias_ipv6_range") { + // Alias IPv6 ranges cannot be updated; they must be removed and then added + // unless you are changing subnetwork/network + if len(instNetworkInterface.AliasIpv6Ranges) > 0 { + ni := &compute.NetworkInterface{ + Fingerprint: instNetworkInterface.Fingerprint, + ForceSendFields: []string{"AliasIpv6Ranges"}, + } + if commonAliasIpv6Ranges := CheckForCommonAliasIpv6(instNetworkInterface, networkInterface); len(commonAliasIpv6Ranges) > 0 { + ni.AliasIpv6Ranges = commonAliasIpv6Ranges + } + op, err := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, ni).Do() + if err != nil { + return errwrap.Wrapf("Error removing alias_ipv6_range: {{"{{"}}err{{"}}"}}", err) + } + opErr := ComputeOperationWaitTime(config, op, project, "updating alias ipv6 ranges", userAgent, d.Timeout(schema.TimeoutUpdate)) + if opErr != nil { + return opErr + } + // re-read fingerprint + instance, err = NewClient(config, userAgent).Instances.Get(project, zone, instance.Name).Do() + if err != nil { + return err + } + instNetworkInterface = instance.NetworkInterfaces[i] + } + + networkInterfacePatchObj := &compute.NetworkInterface{ + AliasIpv6Ranges: networkInterface.AliasIpv6Ranges, + Fingerprint: instNetworkInterface.Fingerprint, + } updateCall := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, networkInterfacePatchObj).Do op, err := updateCall() if err != nil { - return errwrap.Wrapf("Error updating network interface: {{"{{"}}err{{"}}"}}", err) + return errwrap.Wrapf("Error updating network interface: {{`{{`}}err{{`}}`}}", err) } opErr := ComputeOperationWaitTime(config, op, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } + // re-read fingerprint + instance, err = NewClient(config, userAgent).Instances.Get(project, zone, instance.Name).Do() + if err != nil { + return err + } + instNetworkInterface = instance.NetworkInterfaces[i] } +{{- end }} if !updateDuringStop && d.HasChange(prefix+".stack_type") { @@ -2796,12 +3030,30 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err StackType: d.Get(prefix+".stack_type").(string), Fingerprint: instNetworkInterface.Fingerprint, } - updateCall := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, networkInterfacePatchObj).Do - op, err := updateCall() + niBody, err := tpgresource.ConvertToMap(networkInterfacePatchObj) + if err != nil { + return errwrap.Wrapf("Error converting network interface: {{"{{"}}err{{"}}"}}", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateNetworkInterface") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"networkInterface": networkName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: niBody, + }) if err != nil { return errwrap.Wrapf("Error updating network interface: {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2813,12 +3065,30 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err IgmpQuery: d.Get(prefix+".igmp_query").(string), Fingerprint: instNetworkInterface.Fingerprint, } - updateCall := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, networkInterfacePatchObj).Do - op, err := updateCall() + niBody, err := tpgresource.ConvertToMap(networkInterfacePatchObj) + if err != nil { + return errwrap.Wrapf("Error converting network interface: {{"{{"}}err{{"}}"}}", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateNetworkInterface") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"networkInterface": networkName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: niBody, + }) if err != nil { return errwrap.Wrapf("Error updating network interface: {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2830,12 +3100,30 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err Ipv6Address: d.Get(prefix+".ipv6_address").(string), Fingerprint: instNetworkInterface.Fingerprint, } - updateCall := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, networkInterfacePatchObj).Do - op, err := updateCall() + niBody, err := tpgresource.ConvertToMap(networkInterfacePatchObj) + if err != nil { + return errwrap.Wrapf("Error converting network interface: {{"{{"}}err{{"}}"}}", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateNetworkInterface") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"networkInterface": networkName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: niBody, + }) if err != nil { return errwrap.Wrapf("Error updating network interface: {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2847,12 +3135,30 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err InternalIpv6PrefixLength: d.Get(prefix+".internal_ipv6_prefix_length").(int64), Fingerprint: instNetworkInterface.Fingerprint, } - updateCall := NewClient(config, userAgent).Instances.UpdateNetworkInterface(project, zone, instance.Name, networkName, networkInterfacePatchObj).Do - op, err := updateCall() + niBody, err := tpgresource.ConvertToMap(networkInterfacePatchObj) + if err != nil { + return errwrap.Wrapf("Error converting network interface: {{"{{"}}err{{"}}"}}", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateNetworkInterface") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"networkInterface": networkName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: niBody, + }) if err != nil { return errwrap.Wrapf("Error updating network interface: {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "network interface to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -2864,6 +3170,9 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err Network: networkInterface.Network, Subnetwork: networkInterface.Subnetwork, AliasIpRanges: networkInterface.AliasIpRanges, +{{ if ne $.TargetVersionName `ga` -}} + AliasIpv6Ranges: networkInterface.AliasIpv6Ranges, +{{- end }} } // network_ip can be inferred if not declared. Let's only patch if it's being changed by user @@ -3008,12 +3317,26 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err // Detach the old disks. for hash, deviceName := range oDisks { if _, ok := nDisks[hash]; !ok { - op, err := NewClient(config, userAgent).Instances.DetachDisk(project, zone, instance.Name, deviceName).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/detachDisk") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"deviceName": deviceName}) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return errwrap.Wrapf("Error detaching disk: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "detaching disk", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "detaching disk", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3023,12 +3346,27 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err // Attach the new disks for _, disk := range attach { - op, err := NewClient(config, userAgent).Instances.AttachDisk(project, zone, instance.Name, disk).Do() + diskBody, err := tpgresource.ConvertToMap(disk) + if err != nil { + return fmt.Errorf("Error converting attached disk: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/attachDisk") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: diskBody, + }) if err != nil { return errwrap.Wrapf("Error attaching disk : {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "attaching disk", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "attaching disk", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3038,11 +3376,28 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err // if any other boot_disk fields will be added here this should be wrapped in if d.HasChange("boot_disk") if d.HasChange("boot_disk.0.auto_delete") { - op, err := NewClient(config, userAgent).Instances.SetDiskAutoDelete(project, zone, instance.Name, d.Get("boot_disk.0.auto_delete").(bool), d.Get("boot_disk.0.device_name").(string)).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setDiskAutoDelete") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{ + "autoDelete": strconv.FormatBool(d.Get("boot_disk.0.auto_delete").(bool)), + "deviceName": d.Get("boot_disk.0.device_name").(string), + }) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return fmt.Errorf("Error changing auto_delete: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "changing auto_delete", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "changing auto_delete", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3067,12 +3422,28 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if d.HasChange("deletion_protection") { nDeletionProtection := d.Get("deletion_protection").(bool) - op, err := NewClient(config, userAgent).Instances.SetDeletionProtection(project, zone, d.Get("name").(string)).DeletionProtection(nDeletionProtection).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setDeletionProtection") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{ + "deletionProtection": strconv.FormatBool(nDeletionProtection), + }) + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return fmt.Errorf("Error updating deletion protection flag: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "deletion protection to update", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "deletion protection to update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3165,12 +3536,22 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err } if statusBeforeUpdate != "TERMINATED" { - op, err := NewClient(config, userAgent).Instances.Stop(project, zone, instance.Name).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/stop") + if err != nil { + return errwrap.Wrapf("Error generating URL: {{"{{"}}err{{"}}"}}", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return errwrap.Wrapf("Error stopping instance: {{"{{"}}err{{"}}"}}", err) } - opErr := ComputeOperationWaitTime(config, op, project, "stopping instance", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "stopping instance", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3181,11 +3562,26 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err req := &compute.InstancesSetMinCpuPlatformRequest{ MinCpuPlatform: minCpuPlatform.(string), } - op, err := NewClient(config, userAgent).Instances.SetMinCpuPlatform(project, zone, instance.Name, req).Do() + body, err := tpgresource.ConvertToMap(req) + if err != nil { + return fmt.Errorf("Error converting min cpu platform request: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setMinCpuPlatform") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return err } - opErr := ComputeOperationWaitTime(config, op, project, "updating min cpu platform", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "updating min cpu platform", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3199,11 +3595,26 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err req := &compute.InstancesSetMachineTypeRequest{ MachineType: mt.RelativeLink(), } - op, err := NewClient(config, userAgent).Instances.SetMachineType(project, zone, instance.Name, req).Do() + body, err := tpgresource.ConvertToMap(req) + if err != nil { + return fmt.Errorf("Error converting machine type request: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setMachineType") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return err } - opErr := ComputeOperationWaitTime(config, op, project, "updating machinetype", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "updating machinetype", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3217,11 +3628,26 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err req.Email = saMap["email"].(string) req.Scopes = tpgresource.CanonicalizeServiceScopes(tpgresource.ConvertStringSet(saMap["scopes"].(*schema.Set))) } - op, err := NewClient(config, userAgent).Instances.SetServiceAccount(project, zone, instance.Name, req).Do() + body, err := tpgresource.ConvertToMap(req) + if err != nil { + return fmt.Errorf("Error converting service account request: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setServiceAccount") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return err } - opErr := ComputeOperationWaitTime(config, op, project, "updating service account", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "updating service account", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3232,11 +3658,26 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err EnableDisplay: d.Get("enable_display").(bool), ForceSendFields: []string{"EnableDisplay"}, } - op, err := NewClient(config, userAgent).Instances.UpdateDisplayDevice(project, zone, instance.Name, req).Do() + body, err := tpgresource.ConvertToMap(req) + if err != nil { + return fmt.Errorf("Error converting display device request: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateDisplayDevice") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return fmt.Errorf("Error updating display device: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, "updating display device", userAgent, d.Timeout(schema.TimeoutUpdate)) + opErr := ComputeOperationWaitTime(config, res, project, "updating display device", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr } @@ -3245,12 +3686,27 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err if d.HasChange("shielded_instance_config") { shieldedVmConfig := expandShieldedVmConfigs(d) - op, err := NewClient(config, userAgent).Instances.UpdateShieldedInstanceConfig(project, zone, instance.Name, shieldedVmConfig).Do() + body, err := tpgresource.ConvertToMap(shieldedVmConfig) + if err != nil { + return fmt.Errorf("Error converting shielded vm config: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/updateShieldedInstanceConfig") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + }) if err != nil { return fmt.Errorf("Error updating shielded vm config: %s", err) } - opErr := ComputeOperationWaitTime(config, op, project, + opErr := ComputeOperationWaitTime(config, res, project, "shielded vm config update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr @@ -3263,14 +3719,28 @@ func resourceComputeInstanceUpdate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error creating request data to update scheduling: %s", err) } - op, err := NewClient(config, userAgent).Instances.SetScheduling( - project, zone, instance.Name, scheduling).Do() + schedulingBody, err := tpgresource.ConvertToMap(scheduling) + if err != nil { + return fmt.Errorf("Error converting scheduling: %s", err) + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}/setScheduling") + if err != nil { + return fmt.Errorf("Error generating URL: %s", err) + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: schedulingBody, + }) if err != nil { return fmt.Errorf("Error updating scheduling policy: %s", err) } opErr := ComputeOperationWaitTime( - config, op, project, "scheduling policy update", userAgent, + config, res, project, "scheduling policy update", userAgent, d.Timeout(schema.TimeoutUpdate)) if opErr != nil { return opErr @@ -3608,6 +4078,13 @@ func isGracefulMetadataStartupSwitch(d *schema.ResourceDiff) bool { } func resourceComputeInstanceDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -4070,13 +4547,23 @@ func isEmptyServiceAccountBlock(d *schema.ResourceData) bool { // Alias ip ranges cannot be removed and created at the same time. This checks if there are any unchanged alias ip ranges // to be kept in between the PATCH operations on Network Interface func CheckForCommonAliasIp(old, new *compute.NetworkInterface) []*compute.AliasIpRange { + return checkForCommonAliasIpRanges(old.AliasIpRanges, new.AliasIpRanges) +} + +{{ if ne $.TargetVersionName `ga` -}} +func CheckForCommonAliasIpv6(old, new *compute.NetworkInterface) []*compute.AliasIpRange { + return checkForCommonAliasIpRanges(old.AliasIpv6Ranges, new.AliasIpv6Ranges) +} +{{- end }} + +func checkForCommonAliasIpRanges(old, new []*compute.AliasIpRange) []*compute.AliasIpRange { newAliasIpMap := make(map[string]bool) - for _, ipRange := range new.AliasIpRanges { + for _, ipRange := range new { newAliasIpMap[ipRange.IpCidrRange] = true } resultAliasIpRanges := make([]*compute.AliasIpRange, 0) - for _, val := range old.AliasIpRanges { + for _, val := range old { if newAliasIpMap[val.IpCidrRange] { resultAliasIpRanges = append(resultAliasIpRanges, val) } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image.go.tmpl index 21c221a3f2c3..f1ab4cb0068b 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image.go.tmpl @@ -175,7 +175,7 @@ func resourceComputeInstanceFromMachineImageCreate(d *schema.ResourceData, meta tmp := strings.Split(src, "projects/") mi_project := strings.Split(tmp[len(tmp)-1], "/")[0] - miURL := fmt.Sprintf("%sprojects/%s/global/machineImages/%s", config.ComputeBasePath, mi_project, tpl.Name) + miURL := fmt.Sprintf("%sprojects/%s/global/machineImages/%s", transport_tpg.BaseUrl(Product, config), mi_project, tpl.Name) miRes, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", @@ -235,7 +235,7 @@ func resourceComputeInstanceFromMachineImageCreate(d *schema.ResourceData, meta if err = json.Unmarshal(instanceBytes, &instanceBody); err != nil { return fmt.Errorf("Error processing instance body: %s", err) } - insertURL := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, project, z) + insertURL := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(Product, config), project, z) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_meta.yaml.tmpl index 4a71c14cda16..3a0f4ef4c9e7 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_meta.yaml.tmpl @@ -151,6 +151,12 @@ fields: field: 'network_interface.alias_ip_range.ip_cidr_range' - api_field: 'networkInterfaces.aliasIpRanges.subnetworkRangeName' field: 'network_interface.alias_ip_range.subnetwork_range_name' +{{- if ne $.TargetVersionName "ga" }} + - api_field: 'networkInterfaces.aliasIpv6Ranges.ipCidrRange' + field: 'network_interface.alias_ipv6_range.ip_cidr_range' + - api_field: 'networkInterfaces.aliasIpv6Ranges.subnetworkRangeName' + field: 'network_interface.alias_ipv6_range.subnetwork_range_name' +{{- end }} - api_field: 'networkInterfaces.internalIpv6PrefixLength' field: 'network_interface.internal_ipv6_prefix_length' - api_field: 'networkInterfaces.ipv6AccessConfigs.externalIpv6' @@ -264,4 +270,6 @@ fields: {{- if ne $.TargetVersionName "ga" }} - api_field: 'eraseWindowsVssSignature' {{- end }} + - field: 'deletion_policy' + provider_only: true {{ end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_test.go.tmpl index 664b8bf7d00a..c5bc2ff42817 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_machine_image_test.go.tmpl @@ -9,23 +9,17 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} -{{- if ne $.TargetVersionName "ga" }} - "google.golang.org/api/googleapi" -{{- end }} ) func TestAccComputeInstanceFromMachineImage_basic(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" @@ -54,14 +48,11 @@ func TestAccComputeInstanceFromMachineImage_basic(t *testing.T) { func TestAccComputeInstanceFromMachineImage_maxRunDuration(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" - var expectedMaxRunDuration = compute.Duration{} - // Define in testAccComputeInstanceFromMachineImage_maxRunDuration - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + var expectedMaxRunDuration = map[string]interface{}{"nanos": float64(123), "seconds": "60"} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -87,7 +78,7 @@ func TestAccComputeInstanceFromMachineImage_maxRunDuration(t *testing.T) { func TestAccComputeInstanceFromMachineImage_preemptionNoticeDuration(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" @@ -116,7 +107,7 @@ func TestAccComputeInstanceFromMachineImage_terminationTime(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" @@ -146,13 +137,11 @@ func TestAccComputeInstanceFromMachineImage_terminationTime(t *testing.T) { func TestAccComputeInstanceFromMachineImage_localSsdRecoveryTimeout(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" - var expectedLocalSsdRecoveryTimeout = compute.Duration{} - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 3600 + var expectedLocalSsdRecoveryTimeout = map[string]interface{}{"nanos": float64(0), "seconds": "3600"} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -173,13 +162,11 @@ func TestAccComputeInstanceFromMachineImage_localSsdRecoveryTimeout(t *testing.T func TestAccComputeInstanceFromMachineImageWithOverride_localSsdRecoveryTimeout(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" - var expectedLocalSsdRecoveryTimeout = compute.Duration{} - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 7200 + var expectedLocalSsdRecoveryTimeout = map[string]interface{}{"nanos": float64(0), "seconds": "7200"} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -201,14 +188,20 @@ func TestAccComputeInstanceFromMachineImageWithOverride_localSsdRecoveryTimeout( func TestAccComputeInstanceFromMachineImageWithOverride_partnerMetadata(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := make(map[string]map[string]interface{}) + expectedPartnerMetadata[namespace] = map[string]interface{}{ + "entries": map[string]interface{}{ + "key1": "value1", + "key2": float64(2), + "key3": map[string]interface{}{ + "key31": "value31", + }, + }, } acctest.VcrTest(t, resource.TestCase{ @@ -231,7 +224,7 @@ func TestAccComputeInstanceFromMachineImageWithOverride_partnerMetadata(t *testi func TestAccComputeInstanceFromMachineImage_overrideMetadataDotStartupScript(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" @@ -256,7 +249,7 @@ func TestAccComputeInstanceFromMachineImage_overrideMetadataDotStartupScript(t * func TestAccComputeInstanceFromMachineImage_diffProject(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) generatedInstanceName := fmt.Sprintf("tf-test-generated-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_machine_image.foobar" @@ -287,7 +280,7 @@ func TestAccComputeInstanceFromMachineImage_diffProject(t *testing.T) { func TestAccComputeInstanceFromMachineImage_confidentialInstanceConfigMain(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -348,7 +341,7 @@ func TestAccComputeInstanceFromMachineImage_confidentialInstanceConfigMain(t *te func TestAccComputeInstanceFromMachineImage_withSourceMachineImageEncryptionKey(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var resourceName = "google_compute_instance_from_machine_image.foobar" var machineImageName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -379,7 +372,7 @@ func TestAccComputeInstanceFromMachineImage_withSourceMachineImageEncryptionKey( func TestAccComputeInstanceFromMachineImage_VSSWindows(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance1_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -433,7 +426,7 @@ func testAccCheckComputeInstanceFromMachineImageDestroyProducer(t *testing.T) fu } instanceURL := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", - config.ComputeBasePath, config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID) + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID) _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", @@ -1389,7 +1382,7 @@ resource "google_compute_instance_from_machine_image" "foobar" { func TestAccComputeInstanceFromMachineImage_IgmpQuery_v2(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) suffix := acctest.RandString(t, 10) envRegion := envvar.GetTestRegionFromEnv() diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_meta.yaml.tmpl index a7c0bd88a2a0..f4bd6732b378 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_meta.yaml.tmpl @@ -156,6 +156,12 @@ fields: field: 'network_interface.alias_ip_range.ip_cidr_range' - api_field: 'networkInterfaces.aliasIpRanges.subnetworkRangeName' field: 'network_interface.alias_ip_range.subnetwork_range_name' +{{- if ne $.TargetVersionName "ga" }} + - api_field: 'networkInterfaces.aliasIpv6Ranges.ipCidrRange' + field: 'network_interface.alias_ipv6_range.ip_cidr_range' + - api_field: 'networkInterfaces.aliasIpv6Ranges.subnetworkRangeName' + field: 'network_interface.alias_ipv6_range.subnetwork_range_name' +{{- end }} - api_field: 'networkInterfaces.internalIpv6PrefixLength' field: 'network_interface.internal_ipv6_prefix_length' - api_field: 'networkInterfaces.ipv6AccessConfigs.externalIpv6' @@ -277,3 +283,5 @@ fields: {{- if ne $.TargetVersionName "ga" }} - api_field: 'eraseWindowsVssSignature' {{- end }} + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_test.go.tmpl index 702e9b015272..7d0a6f876021 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_from_template_test.go.tmpl @@ -10,22 +10,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" - compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} -{{- if ne $.TargetVersionName "ga" }} - "google.golang.org/api/googleapi" -{{- end }} + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccComputeInstanceFromTemplate_basic(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -53,7 +45,7 @@ func TestAccComputeInstanceFromTemplate_basic(t *testing.T) { func TestAccComputeInstanceFromTemplate_self_link_unique(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -82,15 +74,12 @@ func TestAccComputeInstanceFromTemplate_self_link_unique(t *testing.T) { func TestAccComputeInstanceFromTemplate_maxRunDuration_onInstanceStopAction(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" - var expectedMaxRunDuration = compute.Duration{} - // Define in testAccComputeInstanceFromTemplate_maxRunDuration_onInstanceStopAction - expectedMaxRunDuration.Nanos = 456 - expectedMaxRunDuration.Seconds = 60 + var expectedMaxRunDuration = map[string]interface{}{"nanos": float64(456), "seconds": "60"} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -114,14 +103,12 @@ func TestAccComputeInstanceFromTemplate_maxRunDuration_onInstanceStopAction(t *t func TestAccComputeInstanceFromTemplate_localSsdRecoveryTimeout(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" - var expectedLocalSsdRecoveryTimeout = compute.Duration{} - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 3600 + var expectedLocalSsdRecoveryTimeout = map[string]interface{}{"nanos": float64(0), "seconds": "3600"} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -144,14 +131,12 @@ func TestAccComputeInstanceFromTemplate_localSsdRecoveryTimeout(t *testing.T) { func TestAccComputeInstanceFromTemplateWithOverride_localSsdRecoveryTimeout(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" - var expectedLocalSsdRecoveryTimeout = compute.Duration{} - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 7200 + var expectedLocalSsdRecoveryTimeout = map[string]interface{}{"nanos": float64(0), "seconds": "7200"} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -174,7 +159,7 @@ func TestAccComputeInstanceFromTemplateWithOverride_localSsdRecoveryTimeout(t *t func TestAccComputeInstanceFromTemplate_diskResourcePolicies(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) suffix := acctest.RandString(t, 10) @@ -207,14 +192,20 @@ func TestAccComputeInstanceFromTemplate_diskResourcePolicies(t *testing.T) { func TestAccComputeInstanceFromTemplate_partnerMetadata(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := make(map[string]map[string]interface{}) + expectedPartnerMetadata[namespace] = map[string]interface{}{ + "entries": map[string]interface{}{ + "key1": "value1", + "key2": float64(2), + "key3": map[string]interface{}{ + "key31": "value31", + }, + }, } acctest.VcrTest(t, resource.TestCase{ @@ -238,14 +229,20 @@ func TestAccComputeInstanceFromTemplate_partnerMetadata(t *testing.T) { func TestAccComputeInstanceFromTemplateWithOverride_partnerMetadata(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := make(map[string]map[string]interface{}) + expectedPartnerMetadata[namespace] = map[string]interface{}{ + "entries": map[string]interface{}{ + "key1": "value1", + "key2": float64(2), + "key3": map[string]interface{}{ + "key31": "value31", + }, + }, } acctest.VcrTest(t, resource.TestCase{ @@ -272,7 +269,7 @@ func TestAccComputeInstanceFromTemplateWithOverride_partnerMetadata(t *testing.T func TestAccComputeInstanceFromRegionTemplate_basic(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -302,7 +299,7 @@ func TestAccComputeInstanceFromRegionTemplate_basic(t *testing.T) { func TestAccComputeInstanceFromTemplate_overrideBootDisk(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateDisk := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -331,7 +328,7 @@ func TestAccComputeInstanceFromTemplate_overrideBootDisk(t *testing.T) { func TestAccComputeInstanceFromTemplate_overrideAttachedDisk(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateDisk := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -360,7 +357,7 @@ func TestAccComputeInstanceFromTemplate_overrideAttachedDisk(t *testing.T) { func TestAccComputeInstanceFromTemplate_overrideScratchDisk(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateDisk := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -391,7 +388,7 @@ func TestAccComputeInstanceFromTemplate_overrideScratchDisk(t *testing.T) { func TestAccComputeInstanceFromTemplate_overrideScheduling(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateDisk := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -417,7 +414,7 @@ func TestAccComputeInstanceFromTemplate_TerminationTime(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateDisk := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -444,7 +441,7 @@ func TestAccComputeInstanceFromTemplate_TerminationTime(t *testing.T) { func TestAccComputeInstanceFromTemplate_schedulingPreemptionNoticeDuration(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -469,7 +466,7 @@ func TestAccComputeInstanceFromTemplate_schedulingPreemptionNoticeDuration(t *te {{ end }} func TestAccComputeInstanceFromTemplate_overrideMetadataDotStartupScript(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.inst" @@ -493,7 +490,7 @@ func TestAccComputeInstanceFromTemplate_overrideMetadataDotStartupScript(t *test func TestAccComputeInstanceFromTemplate_useDiskSelfLink(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -522,8 +519,15 @@ func testAccCheckComputeInstanceFromTemplateDestroyProducer(t *testing.T) func(s continue } - _, err := compute_tpg.NewClient(config, config.UserAgent).Instances.Get( - config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID).Do() + instanceURL := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["zone"], rs.Primary.ID) + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: instanceURL, + UserAgent: config.UserAgent, + }) if err == nil { return fmt.Errorf("Instance still exists") } @@ -536,8 +540,8 @@ func testAccCheckComputeInstanceFromTemplateDestroyProducer(t *testing.T) func(s func TestAccComputeInstanceFromTemplate_confidentialInstanceConfigMain(t *testing.T) { t.Parallel() - var instance compute.Instance - var instance2 compute.Instance + var instance map[string]interface{} + var instance2 map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -599,7 +603,7 @@ func TestAccComputeInstanceFromTemplate_confidentialInstanceConfigMain(t *testin func TestAccComputeInstanceFromTemplate_DiskForceAttach(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -631,7 +635,7 @@ func TestAccComputeInstanceFromTemplate_DiskForceAttach(t *testing.T) { func TestAccComputeInstanceFromTemplate_VSSWindows(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "bootdisk_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -2184,7 +2188,7 @@ resource "google_compute_instance_from_template" "inst2" { func TestAccComputeInstanceFromTemplateWithOverride_interface(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) templateName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) resourceName := "google_compute_instance_from_template.foobar" @@ -2209,7 +2213,7 @@ func TestAccComputeInstanceFromTemplateWithOverride_interface(t *testing.T) { func TestAccComputeInstanceFromTemplate_IgmpQuery_v2(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) suffix := acctest.RandString(t, 10) envRegion := envvar.GetTestRegionFromEnv() @@ -2487,6 +2491,14 @@ resource "google_compute_disk" "foobar" { zone = "us-central1-a" } +resource "google_compute_disk" "barbaz" { + name = "%s-2" + image = data.google_compute_image.my_image.self_link + size = 10 + type = "pd-ssd" + zone = "us-central1-a" +} + resource "google_compute_instance_template" "foobar" { name = "%s" machine_type = "n1-standard-1" // can't be e2 because of local-ssd @@ -2524,11 +2536,11 @@ resource "google_compute_instance_from_template" "foobar" { force_attach = true } attached_disk { - source = google_compute_disk.foobar.name + source = google_compute_disk.barbaz.name force_attach = true } } -`, template, template, instance) +`, template, template, template, instance) } func testAccComputeInstanceFromTemplate_DiskForceAttach(instance, template string) string { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group.go.tmpl index d7d438fc9913..30c6616b1028 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group.go.tmpl @@ -39,6 +39,7 @@ func ResourceComputeInstanceGroup() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderZone, ), @@ -127,6 +128,9 @@ func ResourceComputeInstanceGroup() *schema.Resource { Computed: true, Description: `The number of instances in the group.`, }, +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -405,10 +409,20 @@ func resourceComputeInstanceGroupRead(d *schema.ResourceData, meta interface{}) if err := d.Set("self_link", instanceGroup.SelfLink); err != nil { return fmt.Errorf("Error setting self_link: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeInstanceGroup) { + return ResourceComputeInstanceGroup().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -547,6 +561,13 @@ func resourceComputeInstanceGroupUpdate(d *schema.ResourceData, meta interface{} } func resourceComputeInstanceGroupDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager.go.tmpl index ef3e0c2a3b51..f3d80ba6c1e0 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager.go.tmpl @@ -4,6 +4,8 @@ import ( "context" "fmt" "log" + "math" + "strconv" "strings" "time" @@ -38,6 +40,7 @@ func ResourceComputeInstanceGroupManager() *schema.Resource { Delete: schema.DefaultTimeout(15 * time.Minute), }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderZone, customdiff.ForceNewIfChange("resource_policies.0.workload_policy", ForceNewResourcePoliciesWorkloadPolicyIfNewIsEmpty), @@ -641,6 +644,9 @@ func ResourceComputeInstanceGroupManager() *schema.Resource { }, }, }, +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -716,6 +722,16 @@ func getNamedPortsBetaV2(nps []interface{}) []interface{} { return namedPorts } +func stringFromMap(m map[string]interface{}, key string) string { + if m == nil { + return "" + } + if v, ok := m[key].(string); ok { + return v + } + return "" +} + func mapFromInterface(v interface{}) map[string]interface{} { if v == nil { return nil @@ -726,6 +742,59 @@ func mapFromInterface(v interface{}) map[string]interface{} { return nil } +func sliceFromInterface(v interface{}) []interface{} { + if v == nil { + return nil + } + if s, ok := v.([]interface{}); ok { + return s + } + return nil +} + +func stringSliceFromInterface(v interface{}) []string { + raw := sliceFromInterface(v) + result := make([]string, 0, len(raw)) + for _, item := range raw { + if s, ok := item.(string); ok { + result = append(result, s) + } + } + return result +} + +func int64FromInterface(v interface{}) int64 { + switch value := v.(type) { + case int: + return int64(value) + case int64: + return value + case uint64: + if value <= math.MaxInt64 { + return int64(value) + } + case float64: + return int64(value) + case string: + parsed, err := strconv.ParseInt(value, 10, 64) + if err == nil { + return parsed + } + parsedUint, err := strconv.ParseUint(value, 10, 64) + if err == nil && parsedUint <= math.MaxInt64 { + return int64(parsedUint) + } + } + return 0 +} + +func boolFromInterface(v interface{}) bool { + if value, ok := v.(bool); ok { + return value + } + return false +} + func resourceComputeInstanceGroupManagerCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) @@ -746,7 +815,7 @@ func resourceComputeInstanceGroupManagerCreate(d *schema.ResourceData, meta inte "listManagedInstancesResults": d.Get("list_managed_instances_results").(string), "versions": expandVersionsV2(d.Get("version").([]interface{})), "standbyPolicy": expandStandbyPolicyV2(d), - "updatePolicy": expandUpdatePolicyV2(d.Get("update_policy").([]interface{})), + "updatePolicy": expandUpdatePolicy(d.Get("update_policy").([]interface{})), "instanceLifecyclePolicy": expandInstanceLifecyclePolicyV2(d.Get("instance_lifecycle_policy").([]interface{})), "statefulPolicy": expandStatefulPolicyV2(d), "resourcePolicies": expandResourcePoliciesV2(d.Get("resource_policies").([]interface{})), @@ -849,6 +918,19 @@ func flattenNamedPortsBeta(namedPorts []*compute.NamedPort) []map[string]interfa } +func flattenNamedPortsBetaV2(raw interface{}) []map[string]interface{} { + namedPorts := sliceFromInterface(raw) + result := make([]map[string]interface{}, 0, len(namedPorts)) + for _, namedPortRaw := range namedPorts { + namedPort := mapFromInterface(namedPortRaw) + result = append(result, map[string]interface{}{ + "name": stringFromMap(namedPort, "name"), + "port": int64FromInterface(namedPort["port"]), + }) + } + return result +} + func flattenVersions(versions []*compute.InstanceGroupManagerVersion) []map[string]interface{} { result := make([]map[string]interface{}, 0, len(versions)) for _, version := range versions { @@ -862,6 +944,20 @@ func flattenVersions(versions []*compute.InstanceGroupManagerVersion) []map[stri return result } +func flattenVersionsV2(raw interface{}) []map[string]interface{} { + versions := sliceFromInterface(raw) + result := make([]map[string]interface{}, 0, len(versions)) + for _, versionRaw := range versions { + version := mapFromInterface(versionRaw) + result = append(result, map[string]interface{}{ + "name": stringFromMap(version, "name"), + "instance_template": tpgresource.ConvertSelfLinkToV1(stringFromMap(version, "instanceTemplate")), + "target_size": flattenFixedOrPercentV2(version["targetSize"]), + }) + } + return result +} + func flattenFixedOrPercent(fixedOrPercent *compute.FixedOrPercent) []map[string]interface{} { result := make(map[string]interface{}) if value := fixedOrPercent.Percent; value > 0 { @@ -874,7 +970,20 @@ func flattenFixedOrPercent(fixedOrPercent *compute.FixedOrPercent) []map[string] return []map[string]interface{}{result} } -func getManager(d *schema.ResourceData, meta interface{}) (*compute.InstanceGroupManager, error) { +func flattenFixedOrPercentV2(raw interface{}) []map[string]interface{} { + fixedOrPercent := mapFromInterface(raw) + result := make(map[string]interface{}) + if value := int64FromInterface(fixedOrPercent["percent"]); value > 0 { + result["percent"] = value + } else if value := int64FromInterface(fixedOrPercent["fixed"]); value > 0 { + result["fixed"] = value + } else { + return []map[string]interface{}{} + } + return []map[string]interface{}{result} +} + +func readInstanceGroupManagerResponse(d *schema.ResourceData, meta interface{}) (map[string]interface{}, error) { config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) @@ -887,10 +996,20 @@ func getManager(d *schema.ResourceData, meta interface{}) (*compute.InstanceGrou return nil, err } - zone, _ := tpgresource.GetZone(d, config) name := d.Get("name").(string) - manager, err := NewClient(config, userAgent).InstanceGroupManagers.Get(project, zone, name).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroupManagers/{{"{{"}}name{{"}}"}}") + if err != nil { + return nil, err + } + + manager, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return nil, transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Instance Group Manager %q", name)) } @@ -902,6 +1021,7 @@ func getManager(d *schema.ResourceData, meta interface{}) (*compute.InstanceGrou d.SetId("") return nil, nil } + return manager, nil } @@ -921,9 +1041,9 @@ func resourceComputeInstanceGroupManagerRead(d *schema.ResourceData, meta interf if operation != "" { log.Printf("[DEBUG] in progress operation detected at %v, attempting to resume", operation) zone, _ := tpgresource.GetZone(d, config) - op := &compute.Operation{ - Name: operation, - Zone: zone, + op := map[string]interface{}{ + "name": operation, + "zone": zone, } if err := d.Set("operation", ""); err != nil { return fmt.Errorf("Error unsetting operation: %s", err) @@ -937,7 +1057,7 @@ func resourceComputeInstanceGroupManagerRead(d *schema.ResourceData, meta interf } } - manager, err := getManager(d, meta) + manager, err := readInstanceGroupManagerResponse(d, meta) if err != nil { return err } @@ -947,49 +1067,42 @@ func resourceComputeInstanceGroupManagerRead(d *schema.ResourceData, meta interf return nil } - if err := d.Set("base_instance_name", manager.BaseInstanceName); err != nil { + if err := d.Set("base_instance_name", stringFromMap(manager, "baseInstanceName")); err != nil { return fmt.Errorf("Error setting base_instance_name: %s", err) } - if err := d.Set("name", manager.Name); err != nil { + if err := d.Set("name", stringFromMap(manager, "name")); err != nil { return fmt.Errorf("Error setting name: %s", err) } - if err := d.Set("zone", tpgresource.GetResourceNameFromSelfLink(manager.Zone)); err != nil { + if err := d.Set("zone", tpgresource.GetResourceNameFromSelfLink(stringFromMap(manager, "zone"))); err != nil { return fmt.Errorf("Error setting zone: %s", err) } - if err := d.Set("creation_timestamp", manager.CreationTimestamp); err != nil { + if err := d.Set("creation_timestamp", stringFromMap(manager, "creationTimestamp")); err != nil { return fmt.Errorf("Error reading creation_timestamp: %s", err) } - if err := d.Set("description", manager.Description); err != nil { + if err := d.Set("description", stringFromMap(manager, "description")); err != nil { return fmt.Errorf("Error setting description: %s", err) } - if err := d.Set("instance_group_manager_id", manager.Id); err != nil { + if err := d.Set("instance_group_manager_id", int64FromInterface(manager["id"])); err != nil { return fmt.Errorf("Error setting description: %s", err) } if err := d.Set("project", project); err != nil { return fmt.Errorf("Error setting project: %s", err) } - if err := d.Set("target_size", manager.TargetSize); err != nil { + if err := d.Set("target_size", int64FromInterface(manager["targetSize"])); err != nil { return fmt.Errorf("Error setting target_size: %s", err) } - if err := d.Set("list_managed_instances_results", manager.ListManagedInstancesResults); err != nil { + if err := d.Set("list_managed_instances_results", stringFromMap(manager, "listManagedInstancesResults")); err != nil { return fmt.Errorf("Error setting list_managed_instances_results: %s", err) } - if err = d.Set("target_pools", tpgresource.MapStringArr(manager.TargetPools, tpgresource.ConvertSelfLinkToV1)); err != nil { + if err = d.Set("target_pools", tpgresource.MapStringArr(stringSliceFromInterface(manager["targetPools"]), tpgresource.ConvertSelfLinkToV1)); err != nil { return fmt.Errorf("Error setting target_pools in state: %s", err.Error()) } - if err = d.Set("named_port", flattenNamedPortsBeta(manager.NamedPorts)); err != nil { + if err = d.Set("named_port", flattenNamedPortsBetaV2(manager["namedPorts"])); err != nil { return fmt.Errorf("Error setting named_port in state: %s", err.Error()) } - var statefulPolicyMap map[string]interface{} - if manager.StatefulPolicy != nil { - spMap, err := tpgresource.ConvertToMap(manager.StatefulPolicy) - if err != nil { - return fmt.Errorf("Error converting stateful policy: %s", err) - } - statefulPolicyMap = spMap - } + statefulPolicyMap := mapFromInterface(manager["statefulPolicy"]) if err = d.Set("stateful_disk", flattenStatefulPolicy(statefulPolicyMap)); err != nil { return fmt.Errorf("Error setting stateful_disk in state: %s", err.Error()) } @@ -999,49 +1112,49 @@ func resourceComputeInstanceGroupManagerRead(d *schema.ResourceData, meta interf if err = d.Set("stateful_external_ip", flattenStatefulPolicyStatefulExternalIps(d, statefulPolicyMap)); err != nil { return fmt.Errorf("Error setting stateful_external_ip in state: %s", err.Error()) } - if err := d.Set("fingerprint", manager.Fingerprint); err != nil { + if err := d.Set("fingerprint", stringFromMap(manager, "fingerprint")); err != nil { return fmt.Errorf("Error setting fingerprint: %s", err) } - if err := d.Set("instance_group", tpgresource.ConvertSelfLinkToV1(manager.InstanceGroup)); err != nil { + if err := d.Set("instance_group", tpgresource.ConvertSelfLinkToV1(stringFromMap(manager, "instanceGroup"))); err != nil { return fmt.Errorf("Error setting instance_group: %s", err) } - if err := d.Set("self_link", tpgresource.ConvertSelfLinkToV1(manager.SelfLink)); err != nil { + if err := d.Set("self_link", tpgresource.ConvertSelfLinkToV1(stringFromMap(manager, "selfLink"))); err != nil { return fmt.Errorf("Error setting self_link: %s", err) } - if err = d.Set("auto_healing_policies", flattenAutoHealingPolicies(manager.AutoHealingPolicies)); err != nil { + if err = d.Set("auto_healing_policies", flattenAutoHealingPoliciesV2(manager["autoHealingPolicies"])); err != nil { return fmt.Errorf("Error setting auto_healing_policies in state: %s", err.Error()) } - if err := d.Set("version", flattenVersions(manager.Versions)); err != nil { + if err := d.Set("version", flattenVersionsV2(manager["versions"])); err != nil { return err } - if err = d.Set("standby_policy", flattenStandbyPolicy(manager.StandbyPolicy)); err != nil { + if err = d.Set("standby_policy", flattenStandbyPolicyV2(manager["standbyPolicy"])); err != nil { return fmt.Errorf("Error setting standby_policy in state: %s", err.Error()) } - if err := d.Set("target_suspended_size", manager.TargetSuspendedSize); err != nil { + if err := d.Set("target_suspended_size", int64FromInterface(manager["targetSuspendedSize"])); err != nil { return fmt.Errorf("Error setting target_suspended_size: %s", err) } - if err := d.Set("target_stopped_size", manager.TargetStoppedSize); err != nil { + if err := d.Set("target_stopped_size", int64FromInterface(manager["targetStoppedSize"])); err != nil { return fmt.Errorf("Error setting target_stopped_size: %s", err) } - if err = d.Set("update_policy", flattenUpdatePolicy(manager.UpdatePolicy)); err != nil { + if err = d.Set("update_policy", flattenUpdatePolicy(manager["updatePolicy"])); err != nil { return fmt.Errorf("Error setting update_policy in state: %s", err.Error()) } - if err = d.Set("instance_lifecycle_policy", flattenInstanceLifecyclePolicy(manager.InstanceLifecyclePolicy)); err != nil { + if err = d.Set("instance_lifecycle_policy", flattenInstanceLifecyclePolicyV2(manager["instanceLifecyclePolicy"])); err != nil { return fmt.Errorf("Error setting instance lifecycle policy in state: %s", err.Error()) } - if manager.AllInstancesConfig != nil { - if err = d.Set("all_instances_config", flattenAllInstancesConfig(manager.AllInstancesConfig)); err != nil { + if manager["allInstancesConfig"] != nil { + if err = d.Set("all_instances_config", flattenAllInstancesConfigV2(manager["allInstancesConfig"])); err != nil { return fmt.Errorf("Error setting all_instances_config in state: %s", err.Error()) } } - if err = d.Set("status", flattenStatus(manager.Status)); err != nil { + if err = d.Set("status", flattenStatusV2(manager["status"])); err != nil { return fmt.Errorf("Error setting status in state: %s", err.Error()) } - if err = d.Set("resource_policies", flattenResourcePolicies(manager.ResourcePolicies)); err != nil { + if err = d.Set("resource_policies", flattenResourcePoliciesV2(manager["resourcePolicies"])); err != nil { return fmt.Errorf("Error setting resource_policies in state: %s", err.Error()) } - if err = d.Set("target_size_policy", flattenTargetSizePolicy(manager.TargetSizePolicy)); err != nil { + if err = d.Set("target_size_policy", flattenTargetSizePolicyV2(manager["targetSizePolicy"])); err != nil { return fmt.Errorf("Error setting target_size_policy in state: %s", err.Error()) } @@ -1051,6 +1164,11 @@ func resourceComputeInstanceGroupManagerRead(d *schema.ResourceData, meta interf return fmt.Errorf("Error setting wait_for_instances_status in state: %s", err.Error()) } } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } @@ -1068,93 +1186,96 @@ func resourceComputeInstanceGroupManagerUpdate(d *schema.ResourceData, meta inte return err } - zone, err := tpgresource.GetZone(d, config) - if err != nil { - return err - } - - updatedManager := &compute.InstanceGroupManager{ - Fingerprint: d.Get("fingerprint").(string), + patchBody := map[string]interface{}{ + "fingerprint": d.Get("fingerprint").(string), } var change bool if d.HasChange("description") { - updatedManager.Description = d.Get("description").(string) - updatedManager.ForceSendFields = append(updatedManager.ForceSendFields, "Description") + patchBody["description"] = d.Get("description").(string) change = true } if d.HasChange("target_pools") { - updatedManager.TargetPools = tpgresource.ConvertStringSet(d.Get("target_pools").(*schema.Set)) - updatedManager.ForceSendFields = append(updatedManager.ForceSendFields, "TargetPools") + patchBody["targetPools"] = tpgresource.ConvertStringSet(d.Get("target_pools").(*schema.Set)) change = true } if d.HasChange("auto_healing_policies") { - updatedManager.AutoHealingPolicies = expandAutoHealingPolicies(d.Get("auto_healing_policies").([]interface{})) - updatedManager.ForceSendFields = append(updatedManager.ForceSendFields, "AutoHealingPolicies") + patchBody["autoHealingPolicies"] = expandAutoHealingPoliciesV2(d.Get("auto_healing_policies").([]interface{})) change = true } if d.HasChange("version") { - updatedManager.Versions = expandVersions(d.Get("version").([]interface{})) + patchBody["versions"] = expandVersionsV2(d.Get("version").([]interface{})) change = true } if d.HasChange("standby_policy") { - updatedManager.StandbyPolicy = expandStandbyPolicy(d) + patchBody["standbyPolicy"] = expandStandbyPolicyV2(d) change = true } if d.HasChange("target_suspended_size") { - updatedManager.TargetSuspendedSize = int64(d.Get("target_suspended_size").(int)) - updatedManager.ForceSendFields = append(updatedManager.ForceSendFields, "TargetSuspendedSize") + patchBody["targetSuspendedSize"] = int64(d.Get("target_suspended_size").(int)) change = true } if d.HasChange("target_stopped_size") { - updatedManager.TargetStoppedSize = int64(d.Get("target_stopped_size").(int)) - updatedManager.ForceSendFields = append(updatedManager.ForceSendFields, "TargetStoppedSize") + patchBody["targetStoppedSize"] = int64(d.Get("target_stopped_size").(int)) change = true } if d.HasChange("update_policy") { - updatedManager.UpdatePolicy = expandUpdatePolicy(d.Get("update_policy").([]interface{})) + patchBody["updatePolicy"] = expandUpdatePolicy(d.Get("update_policy").([]interface{})) change = true } if d.HasChange("instance_lifecycle_policy") { - updatedManager.InstanceLifecyclePolicy = expandInstanceLifecyclePolicy(d.Get("instance_lifecycle_policy").([]interface{})) + patchBody["instanceLifecyclePolicy"] = expandInstanceLifecyclePolicyV2(d.Get("instance_lifecycle_policy").([]interface{})) change = true } if d.HasChange("all_instances_config") { oldAic, newAic := d.GetChange("all_instances_config") if newAic == nil || len(newAic.([]interface{})) == 0 { - updatedManager.NullFields = append(updatedManager.NullFields, "AllInstancesConfig") + patchBody["allInstancesConfig"] = nil } else { - updatedManager.AllInstancesConfig = expandAllInstancesConfig(oldAic.([]interface{}), newAic.([]interface{})) + patchBody["allInstancesConfig"] = expandAllInstancesConfigV2(oldAic.([]interface{}), newAic.([]interface{})) } change = true } if d.HasChange("stateful_internal_ip") || d.HasChange("stateful_external_ip") || d.HasChange("stateful_disk") { - updatedManager.StatefulPolicy = expandStatefulPolicy(d) + patchBody["statefulPolicy"] = expandStatefulPolicyV2(d) change = true } if d.HasChange("list_managed_instances_results") { - updatedManager.ListManagedInstancesResults = d.Get("list_managed_instances_results").(string) + patchBody["listManagedInstancesResults"] = d.Get("list_managed_instances_results").(string) change = true } if d.HasChange("resource_policies") { - updatedManager.ResourcePolicies = expandResourcePolicies(d.Get("resource_policies").([]interface{})) + patchBody["resourcePolicies"] = expandResourcePoliciesV2(d.Get("resource_policies").([]interface{})) change = true } if change { - op, err := NewClient(config, userAgent).InstanceGroupManagers.Patch(project, zone, d.Get("name").(string), updatedManager).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroupManagers/{{"{{"}}name{{"}}"}}") + if err != nil { + return err + } + + op, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: patchBody, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) if err != nil { return fmt.Errorf("Error updating managed group instances: %s", err) } @@ -1171,14 +1292,24 @@ func resourceComputeInstanceGroupManagerUpdate(d *schema.ResourceData, meta inte d.Partial(true) // Build the parameters for a "SetNamedPorts" request: - namedPorts := getNamedPortsBeta(d.Get("named_port").(*schema.Set).List()) - setNamedPorts := &compute.InstanceGroupsSetNamedPortsRequest{ - NamedPorts: namedPorts, + setNamedPortsBody := map[string]interface{}{ + "namedPorts": getNamedPortsBetaV2(d.Get("named_port").(*schema.Set).List()), + } + + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroups/{{"{{"}}name{{"}}"}}/setNamedPorts") + if err != nil { + return err } - // Make the request: - op, err := NewClient(config, userAgent).InstanceGroups.SetNamedPorts( - project, zone, d.Get("name").(string), setNamedPorts).Do() + op, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: setNamedPortsBody, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) if err != nil { return fmt.Errorf("Error updating InstanceGroupManager: %s", err) @@ -1196,8 +1327,23 @@ func resourceComputeInstanceGroupManagerUpdate(d *schema.ResourceData, meta inte d.Partial(true) targetSize := int64(d.Get("target_size").(int)) - op, err := NewClient(config, userAgent).InstanceGroupManagers.Resize( - project, zone, d.Get("name").(string), targetSize).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroupManagers/{{"{{"}}name{{"}}"}}/resize") + if err != nil { + return err + } + url, err = transport_tpg.AddQueryParams(url, map[string]string{"size": strconv.FormatInt(targetSize, 10)}) + if err != nil { + return err + } + + op, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) if err != nil { return fmt.Errorf("Error updating InstanceGroupManager: %s", err) @@ -1235,15 +1381,31 @@ func resourceComputeInstanceGroupManagerDelete(d *schema.ResourceData, meta inte return err } - zone, _ := tpgresource.GetZone(d, config) - name := d.Get("name").(string) + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroupManagers/{{"{{"}}name{{"}}"}}") + if err != nil { + return err + } - op, err := NewClient(config, userAgent).InstanceGroupManagers.Delete(project, zone, name).Do() + op, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: project, + RawURL: url, + UserAgent: userAgent, + Timeout: d.Timeout(schema.TimeoutDelete), + }) attempt := 0 for err != nil && attempt < 20 { attempt++ time.Sleep(2000 * time.Millisecond) - op, err = NewClient(config, userAgent).InstanceGroupManagers.Delete(project, zone, name).Do() + op, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: project, + RawURL: url, + UserAgent: userAgent, + Timeout: d.Timeout(schema.TimeoutDelete), + }) } if err != nil { @@ -1260,13 +1422,23 @@ func resourceComputeInstanceGroupManagerDelete(d *schema.ResourceData, meta inte return err } - instanceGroup, igErr := NewClient(config, userAgent).InstanceGroups.Get( - project, zone, name).Do() + instanceGroupURL, igErr := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroups/{{"{{"}}name{{"}}"}}") + if igErr != nil { + return igErr + } + instanceGroup, igErr := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: instanceGroupURL, + UserAgent: userAgent, + Timeout: d.Timeout(schema.TimeoutDelete), + }) if igErr != nil { return fmt.Errorf("Error getting instance group size: %s", err) } - instanceGroupSize := instanceGroup.Size + instanceGroupSize := int64FromInterface(instanceGroup["size"]) if instanceGroupSize >= currentSize { return fmt.Errorf("Error, instance group isn't shrinking during delete") @@ -1286,7 +1458,7 @@ func computeIGMWaitForInstanceStatus(d *schema.ResourceData, meta interface{}) e conf := retry.StateChangeConf{ Pending: []string{"creating", "error", "updating per instance configs", "reaching version target", "updating all instances config"}, Target: []string{"created"}, - Refresh: waitForInstancesRefreshFunc(getManager, waitForUpdates, d, meta), + Refresh: instanceGroupManagerStatusRefreshFunc(waitForUpdates, d, meta), Timeout: d.Timeout(schema.TimeoutCreate), } _, err := conf.WaitForState() @@ -1296,6 +1468,45 @@ func computeIGMWaitForInstanceStatus(d *schema.ResourceData, meta interface{}) e return nil } +func instanceGroupManagerStatusRefreshFunc(waitForUpdates bool, d *schema.ResourceData, meta interface{}) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + manager, err := readInstanceGroupManagerResponse(d, meta) + if err != nil { + log.Printf("[WARNING] Error in fetching manager while waiting for instances to come up: %s\n", err) + return nil, "error", err + } + if manager == nil { + return nil, "error", fmt.Errorf("instance manager not found") + } + + status := mapFromInterface(manager["status"]) + if boolFromInterface(status["isStable"]) { + if waitForUpdates { + stateful := mapFromInterface(status["stateful"]) + if boolFromInterface(stateful["hasStatefulConfig"]) { + perInstanceConfigs := mapFromInterface(stateful["perInstanceConfigs"]) + if !boolFromInterface(perInstanceConfigs["allEffective"]) { + return false, "updating per instance configs", nil + } + } + + versionTarget := mapFromInterface(status["versionTarget"]) + if !boolFromInterface(versionTarget["isReached"]) { + return false, "reaching version target", nil + } + + allInstancesConfig := mapFromInterface(status["allInstancesConfig"]) + if allInstancesConfig != nil && !boolFromInterface(allInstancesConfig["effective"]) { + return false, "updating all instances config", nil + } + } + return true, "created", nil + } + + return false, "creating", nil + } +} + func expandAutoHealingPolicies(configured []interface{}) []*compute.InstanceGroupManagerAutoHealingPolicy { autoHealingPolicies := make([]*compute.InstanceGroupManagerAutoHealingPolicy, 0, len(configured)) for _, raw := range configured { @@ -1666,59 +1877,7 @@ func expandStandbyPolicyV2(d *schema.ResourceData) map[string]interface{} { return standbyPolicy } -func expandUpdatePolicy(configured []interface{}) *compute.InstanceGroupManagerUpdatePolicy { - updatePolicy := &compute.InstanceGroupManagerUpdatePolicy{} - for _, raw := range configured { - data := raw.(map[string]interface{}) - - updatePolicy.MinimalAction = data["minimal_action"].(string) - mostDisruptiveAllowedAction := data["most_disruptive_allowed_action"].(string) - if mostDisruptiveAllowedAction != "" { - updatePolicy.MostDisruptiveAllowedAction = mostDisruptiveAllowedAction - } else { - updatePolicy.NullFields = append(updatePolicy.NullFields, "MostDisruptiveAllowedAction") - } - updatePolicy.Type = data["type"].(string) - updatePolicy.ReplacementMethod = data["replacement_method"].(string) -{{- if ne $.TargetVersionName "ga" }} - updatePolicy.MinReadySec = int64(data["min_ready_sec"].(int)) - updatePolicy.ForceSendFields = []string{"MinReadySec"} -{{- end }} - - // percent and fixed values are conflicting - // when the percent values are set, the fixed values will be ignored - if v := data["max_surge_percent"]; v.(int) > 0 { - updatePolicy.MaxSurge = &compute.FixedOrPercent{ - Percent: int64(v.(int)), - NullFields: []string{"Fixed"}, - } - } else { - updatePolicy.MaxSurge = &compute.FixedOrPercent{ - Fixed: int64(data["max_surge_fixed"].(int)), - // allow setting this value to 0 - ForceSendFields: []string{"Fixed"}, - NullFields: []string{"Percent"}, - } - } - - if v := data["max_unavailable_percent"]; v.(int) > 0 { - updatePolicy.MaxUnavailable = &compute.FixedOrPercent{ - Percent: int64(v.(int)), - NullFields: []string{"Fixed"}, - } - } else { - updatePolicy.MaxUnavailable = &compute.FixedOrPercent{ - Fixed: int64(data["max_unavailable_fixed"].(int)), - // allow setting this value to 0 - ForceSendFields: []string{"Fixed"}, - NullFields: []string{"Percent"}, - } - } - } - return updatePolicy -} - -func expandUpdatePolicyV2(configured []interface{}) map[string]interface{} { +func expandUpdatePolicy(configured []interface{}) map[string]interface{} { updatePolicy := map[string]interface{}{} for _, raw := range configured { data := raw.(map[string]interface{}) @@ -1795,6 +1954,19 @@ func flattenAutoHealingPolicies(autoHealingPolicies []*compute.InstanceGroupMana return autoHealingPoliciesSchema } +func flattenAutoHealingPoliciesV2(raw interface{}) []map[string]interface{} { + autoHealingPolicies := sliceFromInterface(raw) + result := make([]map[string]interface{}, 0, len(autoHealingPolicies)) + for _, autoHealingPolicyRaw := range autoHealingPolicies { + autoHealingPolicy := mapFromInterface(autoHealingPolicyRaw) + result = append(result, map[string]interface{}{ + "health_check": stringFromMap(autoHealingPolicy, "healthCheck"), + "initial_delay_sec": int64FromInterface(autoHealingPolicy["initialDelaySec"]), + }) + } + return result +} + func flattenStatefulPolicy(statefulPolicy map[string]interface{}) []map[string]interface{} { if statefulPolicy == nil { return make([]map[string]interface{}, 0, 0) @@ -1890,31 +2062,47 @@ func flattenStandbyPolicy(standbyPolicy *compute.InstanceGroupManagerStandbyPoli } return results } -func flattenUpdatePolicy(updatePolicy *compute.InstanceGroupManagerUpdatePolicy) []map[string]interface{} { + +func flattenStandbyPolicyV2(raw interface{}) []map[string]any { + standbyPolicy := mapFromInterface(raw) + results := []map[string]any{} + if standbyPolicy != nil { + results = append(results, map[string]any{ + "initial_delay_sec": int64FromInterface(standbyPolicy["initialDelaySec"]), + "mode": stringFromMap(standbyPolicy, "mode"), + }) + } + return results +} + +func flattenUpdatePolicy(raw interface{}) []map[string]interface{} { + updatePolicy := mapFromInterface(raw) results := []map[string]interface{}{} if updatePolicy != nil { up := map[string]interface{}{} - if updatePolicy.MaxSurge != nil { - up["max_surge_fixed"] = updatePolicy.MaxSurge.Fixed - up["max_surge_percent"] = updatePolicy.MaxSurge.Percent + maxSurge := mapFromInterface(updatePolicy["maxSurge"]) + if maxSurge != nil { + up["max_surge_fixed"] = int64FromInterface(maxSurge["fixed"]) + up["max_surge_percent"] = int64FromInterface(maxSurge["percent"]) } else { up["max_surge_fixed"] = 0 up["max_surge_percent"] = 0 } - if updatePolicy.MaxUnavailable != nil { - up["max_unavailable_fixed"] = updatePolicy.MaxUnavailable.Fixed - up["max_unavailable_percent"] = updatePolicy.MaxUnavailable.Percent + maxUnavailable := mapFromInterface(updatePolicy["maxUnavailable"]) + if maxUnavailable != nil { + up["max_unavailable_fixed"] = int64FromInterface(maxUnavailable["fixed"]) + up["max_unavailable_percent"] = int64FromInterface(maxUnavailable["percent"]) } else { up["max_unavailable_fixed"] = 0 up["max_unavailable_percent"] = 0 } {{- if ne $.TargetVersionName "ga" }} - up["min_ready_sec"] = updatePolicy.MinReadySec + up["min_ready_sec"] = int64FromInterface(updatePolicy["minReadySec"]) {{- end }} - up["minimal_action"] = updatePolicy.MinimalAction - up["most_disruptive_allowed_action"] = updatePolicy.MostDisruptiveAllowedAction - up["type"] = updatePolicy.Type - up["replacement_method"] = updatePolicy.ReplacementMethod + up["minimal_action"] = stringFromMap(updatePolicy, "minimalAction") + up["most_disruptive_allowed_action"] = stringFromMap(updatePolicy, "mostDisruptiveAllowedAction") + up["type"] = stringFromMap(updatePolicy, "type") + up["replacement_method"] = stringFromMap(updatePolicy, "replacementMethod") results = append(results, up) } return results @@ -1939,6 +2127,26 @@ func flattenInstanceLifecyclePolicy(instanceLifecyclePolicy *compute.InstanceGro return results } +func flattenInstanceLifecyclePolicyV2(raw interface{}) []map[string]interface{} { + instanceLifecyclePolicy := mapFromInterface(raw) + results := []map[string]interface{}{} + if instanceLifecyclePolicy != nil { + ilp := map[string]interface{}{} + ilp["force_update_on_repair"] = stringFromMap(instanceLifecyclePolicy, "forceUpdateOnRepair") + ilp["default_action_on_failure"] = stringFromMap(instanceLifecyclePolicy, "defaultActionOnFailure") + + {{ if ne $.TargetVersionName `ga` -}} + ilp["on_failed_health_check"] = stringFromMap(instanceLifecyclePolicy, "onFailedHealthCheck") + {{- end }} + + {{ if ne $.TargetVersionName `ga` -}} + ilp["on_repair"] = flattenOnRepairV2(instanceLifecyclePolicy["onRepair"]) + {{- end }} + results = append(results, ilp) + } + return results +} + {{ if ne $.TargetVersionName `ga` -}} func flattenOnRepair(onRepair *compute.InstanceGroupManagerInstanceLifecyclePolicyOnRepair) []map[string]any { results := []map[string]any{} @@ -1949,6 +2157,17 @@ func flattenOnRepair(onRepair *compute.InstanceGroupManagerInstanceLifecyclePoli } return results } + +func flattenOnRepairV2(raw interface{}) []map[string]any { + onRepair := mapFromInterface(raw) + results := []map[string]any{} + if onRepair != nil { + results = append(results, map[string]any{ + "allow_changing_zone": stringFromMap(onRepair, "allowChangingZone"), + }) + } + return results +} {{- end }} func expandAllInstancesConfig(old []interface{}, new []interface{}) *compute.InstanceGroupManagerAllInstancesConfig { @@ -1995,9 +2214,8 @@ func expandAllInstancesConfig(old []interface{}, new []interface{}) *compute.Ins } func expandAllInstancesConfigV2(old []interface{}, new []interface{}) map[string]interface{} { - var properties map[string]interface{} + properties := map[string]interface{}{} for _, raw := range new { - properties = map[string]interface{}{} if raw != nil { data := raw.(map[string]interface{}) metadata := map[string]interface{}{} @@ -2022,43 +2240,42 @@ func expandAllInstancesConfigV2(old []interface{}, new []interface{}) map[string } } - if properties != nil { - metadata := mapFromInterface(properties["metadata"]) - labels := mapFromInterface(properties["labels"]) - for _, raw := range old { - if raw != nil { - data := raw.(map[string]interface{}) - for k := range data["metadata"].(map[string]interface{}) { - if _, exist := metadata[k]; !exist { - if metadata == nil { - metadata = map[string]interface{}{} - } - metadata[k] = nil + if len(properties) == 0 { + return nil + } + + metadata := mapFromInterface(properties["metadata"]) + labels := mapFromInterface(properties["labels"]) + for _, raw := range old { + if raw != nil { + data := raw.(map[string]interface{}) + for k := range data["metadata"].(map[string]interface{}) { + if _, exist := metadata[k]; !exist { + if metadata == nil { + metadata = map[string]interface{}{} } + metadata[k] = nil } - for k := range data["labels"].(map[string]interface{}) { - if _, exist := labels[k]; !exist { - if labels == nil { - labels = map[string]interface{}{} - } - labels[k] = nil + } + for k := range data["labels"].(map[string]interface{}) { + if _, exist := labels[k]; !exist { + if labels == nil { + labels = map[string]interface{}{} } + labels[k] = nil } } } - if metadata != nil { - properties["metadata"] = metadata - } - if labels != nil { - properties["labels"] = labels - } } - if properties != nil { - return map[string]interface{}{ - "properties": properties, - } + if metadata != nil { + properties["metadata"] = metadata + } + if labels != nil { + properties["labels"] = labels + } + return map[string]interface{}{ + "properties": properties, } - return nil } func flattenAllInstancesConfig(allInstancesConfig *compute.InstanceGroupManagerAllInstancesConfig) []map[string]interface{} { @@ -2074,6 +2291,23 @@ func flattenAllInstancesConfig(allInstancesConfig *compute.InstanceGroupManagerA return results } +func flattenAllInstancesConfigV2(raw interface{}) []map[string]interface{} { + allInstancesConfig := mapFromInterface(raw) + results := []map[string]interface{}{} + props := map[string]interface{}{} + properties := mapFromInterface(allInstancesConfig["properties"]) + metadata := mapFromInterface(properties["metadata"]) + if len(metadata) > 0 { + props["metadata"] = metadata + } + labels := mapFromInterface(properties["labels"]) + if len(labels) > 0 { + props["labels"] = labels + } + results = append(results, props) + return results +} + func flattenStatus(status *compute.InstanceGroupManagerStatus) []map[string]interface{} { results := []map[string]interface{}{} data := map[string]interface{}{ @@ -2088,6 +2322,21 @@ func flattenStatus(status *compute.InstanceGroupManagerStatus) []map[string]inte return results } +func flattenStatusV2(raw interface{}) []map[string]interface{} { + status := mapFromInterface(raw) + results := []map[string]interface{}{} + data := map[string]interface{}{ + "is_stable": boolFromInterface(status["isStable"]), + "stateful": flattenStatusStatefulV2(status["stateful"]), + "version_target": flattenStatusVersionTargetV2(status["versionTarget"]), + } + if status["allInstancesConfig"] != nil { + data["all_instances_config"] = flattenStatusAllInstancesConfigV2(status["allInstancesConfig"]) + } + results = append(results, data) + return results +} + func flattenStatusStateful(stateful *compute.InstanceGroupManagerStatusStateful) []map[string]interface{} { results := []map[string]interface{}{} data := map[string]interface{}{ @@ -2098,6 +2347,17 @@ func flattenStatusStateful(stateful *compute.InstanceGroupManagerStatusStateful) return results } +func flattenStatusStatefulV2(raw interface{}) []map[string]interface{} { + stateful := mapFromInterface(raw) + results := []map[string]interface{}{} + data := map[string]interface{}{ + "has_stateful_config": boolFromInterface(stateful["hasStatefulConfig"]), + "per_instance_configs": flattenStatusStatefulConfigsV2(stateful["perInstanceConfigs"]), + } + results = append(results, data) + return results +} + func flattenStatusStatefulConfigs(statefulConfigs *compute.InstanceGroupManagerStatusStatefulPerInstanceConfigs) []map[string]interface{} { results := []map[string]interface{}{} data := map[string]interface{}{ @@ -2107,6 +2367,16 @@ func flattenStatusStatefulConfigs(statefulConfigs *compute.InstanceGroupManagerS return results } +func flattenStatusStatefulConfigsV2(raw interface{}) []map[string]interface{} { + statefulConfigs := mapFromInterface(raw) + results := []map[string]interface{}{} + data := map[string]interface{}{ + "all_effective": boolFromInterface(statefulConfigs["allEffective"]), + } + results = append(results, data) + return results +} + func flattenStatusVersionTarget(versionTarget *compute.InstanceGroupManagerStatusVersionTarget) []map[string]interface{} { results := []map[string]interface{}{} data := map[string]interface{}{ @@ -2116,6 +2386,16 @@ func flattenStatusVersionTarget(versionTarget *compute.InstanceGroupManagerStatu return results } +func flattenStatusVersionTargetV2(raw interface{}) []map[string]interface{} { + versionTarget := mapFromInterface(raw) + results := []map[string]interface{}{} + data := map[string]interface{}{ + "is_reached": boolFromInterface(versionTarget["isReached"]), + } + results = append(results, data) + return results +} + func flattenStatusAllInstancesConfig(allInstancesConfig *compute.InstanceGroupManagerStatusAllInstancesConfig) []map[string]interface{} { results := []map[string]interface{}{} data := map[string]interface{}{ @@ -2126,6 +2406,17 @@ func flattenStatusAllInstancesConfig(allInstancesConfig *compute.InstanceGroupMa return results } +func flattenStatusAllInstancesConfigV2(raw interface{}) []map[string]interface{} { + allInstancesConfig := mapFromInterface(raw) + results := []map[string]interface{}{} + data := map[string]interface{}{ + "effective": boolFromInterface(allInstancesConfig["effective"]), + "current_revision": stringFromMap(allInstancesConfig, "currentRevision"), + } + results = append(results, data) + return results +} + func flattenTargetSizePolicy(targetSizePolicy *compute.InstanceGroupManagerTargetSizePolicy) []map[string]interface{} { if targetSizePolicy == nil { return nil @@ -2136,6 +2427,19 @@ func flattenTargetSizePolicy(targetSizePolicy *compute.InstanceGroupManagerTarge }, } } + +func flattenTargetSizePolicyV2(raw interface{}) []map[string]interface{} { + targetSizePolicy := mapFromInterface(raw) + if targetSizePolicy == nil { + return nil + } + return []map[string]interface{}{ + { + "mode": stringFromMap(targetSizePolicy, "mode"), + }, + } +} + func flattenResourcePolicies(resourcePolicies *compute.InstanceGroupManagerResourcePolicies) []map[string]interface{} { results := []map[string]interface{}{} if resourcePolicies != nil { @@ -2147,6 +2451,18 @@ func flattenResourcePolicies(resourcePolicies *compute.InstanceGroupManagerResou return results } +func flattenResourcePoliciesV2(raw interface{}) []map[string]interface{} { + resourcePolicies := mapFromInterface(raw) + results := []map[string]interface{}{} + if resourcePolicies != nil { + data := map[string]interface{}{ + "workload_policy": stringFromMap(resourcePolicies, "workloadPolicy"), + } + results = append(results, data) + } + return results +} + func resourceInstanceGroupManagerStateImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { if err := d.Set("wait_for_instances", false); err != nil { return nil, fmt.Errorf("Error setting wait_for_instances: %s", err) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_meta.yaml.tmpl index 4dba069eefb9..9a030a3b0bb3 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_meta.yaml.tmpl @@ -98,3 +98,5 @@ fields: - field: 'wait_for_instances_status' provider_only: true - api_field: 'zone' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_test.go.tmpl index 2351f3be6eb9..4b57c452cace 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_manager_test.go.tmpl @@ -9,10 +9,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" {{- if ne $.TargetVersionName "ga" }} "github.com/hashicorp/terraform-provider-google/google/envvar" {{- end }} tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestForceNewResourcePoliciesWorkloadPolicyIfNewIsEmpty(t *testing.T) { @@ -637,8 +639,15 @@ func testAccCheckInstanceGroupManagerDestroyProducer(t *testing.T) func(s *terra if rs.Type != "google_compute_instance_group_manager" { continue } - _, err := tpgcompute.NewClient(config, config.UserAgent).InstanceGroupManagers.Get( - config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do() + url := fmt.Sprintf("%sprojects/%s/zones/%s/instanceGroupManagers/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]) + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err == nil { return fmt.Errorf("InstanceGroupManager still exists") } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_membership_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_membership_test.go.tmpl index 9a79df77d221..3767a7e6128f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_membership_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_membership_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_meta.yaml.tmpl index ba2bac8da7de..e095ed5ae81f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_group_meta.yaml.tmpl @@ -22,3 +22,5 @@ fields: - api_field: 'selfLink' - api_field: 'size' - api_field: 'zone' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_meta.yaml.tmpl index 88696add0a62..96b6f910b537 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_meta.yaml.tmpl @@ -156,6 +156,12 @@ fields: field: 'network_interface.alias_ip_range.ip_cidr_range' - api_field: 'networkInterfaces.aliasIpRanges.subnetworkRangeName' field: 'network_interface.alias_ip_range.subnetwork_range_name' +{{- if ne $.TargetVersionName "ga" }} + - api_field: 'networkInterfaces.aliasIpv6Ranges.ipCidrRange' + field: 'network_interface.alias_ipv6_range.ip_cidr_range' + - api_field: 'networkInterfaces.aliasIpv6Ranges.subnetworkRangeName' + field: 'network_interface.alias_ipv6_range.subnetwork_range_name' +{{- end }} - api_field: 'networkInterfaces.internalIpv6PrefixLength' field: 'network_interface.internal_ipv6_prefix_length' - api_field: 'networkInterfaces.ipv6AccessConfigs.externalIpv6' @@ -279,4 +285,6 @@ fields: - api_field: 'zone' {{- if ne $.TargetVersionName "ga" }} - api_field: 'eraseWindowsVssSignature' -{{- end }} \ No newline at end of file +{{- end }} + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate.go b/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate.go index bab2e01015fa..89089e7d747e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate.go @@ -347,7 +347,7 @@ func getInstanceFromInstanceState(config *transport_tpg.Config, is *terraform.In } } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", config.ComputeBasePath, project, zone, is.ID) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", transport_tpg.BaseUrl(Product, config), project, zone, is.ID) instance, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", @@ -388,7 +388,7 @@ func getAllDisksFromInstanceState(config *transport_tpg.Config, is *terraform.In if token != "" { params.Set("pageToken", token) } - url := fmt.Sprintf("%sprojects/%s/zones/%s/disks", config.ComputeBasePath, project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/disks", transport_tpg.BaseUrl(Product, config), project, zone) if len(params) > 0 { url = fmt.Sprintf("%s?%s", url, params.Encode()) } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate_test.go index 320843c3cfa3..18178c6e491e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_migrate_test.go @@ -107,7 +107,7 @@ func TestAccComputeInstanceMigrateState(t *testing.T) { }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, config.Zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, config.Zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -187,7 +187,7 @@ func TestAccComputeInstanceMigrateState_bootDisk(t *testing.T) { }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -263,7 +263,7 @@ func TestAccComputeInstanceMigrateState_v4FixBootDisk(t *testing.T) { }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -325,7 +325,7 @@ func TestAccComputeInstanceMigrateState_attachedDiskFromSource(t *testing.T) { "sourceImage": "projects/debian-cloud/global/images/family/debian-11", "zone": zone, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/disks", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/disks", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -365,7 +365,7 @@ func TestAccComputeInstanceMigrateState_attachedDiskFromSource(t *testing.T) { }, }, } - url = fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url = fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -422,7 +422,7 @@ func TestAccComputeInstanceMigrateState_v4FixAttachedDiskFromSource(t *testing.T "sourceImage": "projects/debian-cloud/global/images/family/debian-11", "zone": zone, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/disks", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/disks", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -462,7 +462,7 @@ func TestAccComputeInstanceMigrateState_v4FixAttachedDiskFromSource(t *testing.T }, }, } - url = fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url = fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -539,7 +539,7 @@ func TestAccComputeInstanceMigrateState_attachedDiskFromEncryptionKey(t *testing }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -616,7 +616,7 @@ func TestAccComputeInstanceMigrateState_v4FixAttachedDiskFromEncryptionKey(t *te }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -695,7 +695,7 @@ func TestAccComputeInstanceMigrateState_attachedDiskFromAutoDeleteAndImage(t *te }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -776,7 +776,7 @@ func TestAccComputeInstanceMigrateState_v4FixAttachedDiskFromAutoDeleteAndImage( }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -853,7 +853,7 @@ func TestAccComputeInstanceMigrateState_scratchDisk(t *testing.T) { }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -926,7 +926,7 @@ func TestAccComputeInstanceMigrateState_v4FixScratchDisk(t *testing.T) { }, }, } - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", config.ComputeBasePath, config.Project, zone) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "POST", @@ -1010,7 +1010,7 @@ func runInstanceMigrateTest(t *testing.T, id, testName string, version int, attr } func cleanUpInstance(config *transport_tpg.Config, instanceName, zone string) { - url := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", config.ComputeBasePath, config.Project, zone, instanceName) + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone, instanceName) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "DELETE", @@ -1031,7 +1031,7 @@ func cleanUpInstance(config *transport_tpg.Config, instanceName, zone string) { } func cleanUpDisk(config *transport_tpg.Config, diskName, zone string) { - url := fmt.Sprintf("%sprojects/%s/zones/%s/disks/%s", config.ComputeBasePath, config.Project, zone, diskName) + url := fmt.Sprintf("%sprojects/%s/zones/%s/disks/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, zone, diskName) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "DELETE", @@ -1064,8 +1064,6 @@ func getInitializedConfig(t *testing.T) *transport_tpg.Config { Zone: envvar.GetTestZoneFromEnv(), } - transport_tpg.ConfigureBasePaths(config) - err := config.LoadAndValidate(context.Background()) if err != nil { t.Fatal(err) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_settings_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_instance_settings_test.go index 58d1a7abb5f9..edbf84df8bd6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_settings_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_settings_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeInstanceSettings_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl index 9619fe9ef2cc..31717ac5f041 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template.go.tmpl @@ -71,6 +71,7 @@ func ResourceComputeInstanceTemplate() *schema.Resource { }, SchemaVersion: 1, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, resourceComputeInstanceTemplateSourceImageCustomizeDiff, resourceComputeInstanceTemplateScratchDiskCustomizeDiff, @@ -625,6 +626,32 @@ Google Cloud KMS. Only one of kms_key_self_link, rsa_encrypted_key and raw_key m }, }, + {{ if ne $.TargetVersionName `ga` -}} + "alias_ipv6_range": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `An array of alias IPv6 ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ip_cidr_range": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: IpCidrRangeDiffSuppress, + Description: `The IP CIDR range represented by this alias IPv6 range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces. At the time of writing only a netmask (e.g. /96) may be supplied, with a CIDR format resulting in an API error.`, + }, + "subnetwork_range_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IPv6 range. If left unspecified, the primary range of the subnetwork will be used.`, + }, + }, + }, + }, + {{- end }} + "stack_type": { Type: schema.TypeString, Optional: true, diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_meta.yaml.tmpl index cb121eabe26b..089b5e3d606d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_meta.yaml.tmpl @@ -129,6 +129,12 @@ fields: api_field: 'properties.networkInterfaces.aliasIpRanges.ipCidrRange' - field: 'network_interface.alias_ip_range.subnetwork_range_name' api_field: 'properties.networkInterfaces.aliasIpRanges.subnetworkRangeName' +{{- if ne $.TargetVersionName "ga" }} + - field: 'network_interface.alias_ipv6_range.ip_cidr_range' + api_field: 'properties.networkInterfaces.aliasIpv6Ranges.ipCidrRange' + - field: 'network_interface.alias_ipv6_range.subnetwork_range_name' + api_field: 'properties.networkInterfaces.aliasIpv6Ranges.subnetworkRangeName' +{{- end }} - field: 'network_interface.internal_ipv6_prefix_length' api_field: 'properties.networkInterfaces.internalIpv6PrefixLength' - field: 'network_interface.ipv6_access_config.external_ipv6' diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_test.go.tmpl index 6a6faa98ca6a..d97e9337e012 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_template_test.go.tmpl @@ -16,8 +16,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/tpgresource" {{ if eq $.TargetVersionName `ga` }} @@ -285,6 +289,35 @@ func TestAccComputeInstanceTemplate_IPv6(t *testing.T) { }) } +{{ if ne $.TargetVersionName `ga` -}} +func TestAccComputeInstanceTemplate_aliasIpv6Range(t *testing.T) { + t.Parallel() + + var instanceTemplate compute.InstanceTemplate + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeInstanceTemplateDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeInstanceTemplate_aliasIpv6Range(acctest.RandString(t, 10)), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceTemplateExists( + t, "google_compute_instance_template.foobar", &instanceTemplate), + resource.TestCheckResourceAttr("google_compute_instance_template.foobar", "network_interface.0.alias_ipv6_range.0.ip_cidr_range", "/96"), + ), + }, + { + ResourceName: "google_compute_instance_template.foobar", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} +{{- end }} + func TestAccComputeInstanceTemplate_networkTier(t *testing.T) { t.Parallel() @@ -700,7 +733,7 @@ func TestAccComputeInstanceTemplate_EncryptKMS(t *testing.T) { t.Parallel() var instanceTemplate compute.InstanceTemplate - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -708,7 +741,7 @@ func TestAccComputeInstanceTemplate_EncryptKMS(t *testing.T) { CheckDestroy: testAccCheckComputeInstanceTemplateDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccComputeInstanceTemplate_encryptionKMS(acctest.RandString(t, 10), kms.CryptoKey.Name, tpgresource.GetResourceNameFromSelfLink(kms.KeyRing.Name)), + Config: testAccComputeInstanceTemplate_encryptionKMS(acctest.RandString(t, 10), bootstrapped.CryptoKey.Name, tpgresource.GetResourceNameFromSelfLink(bootstrapped.KeyRing.Name)), Check: resource.ComposeTestCheckFunc( testAccCheckComputeInstanceTemplateExists(t, "google_compute_instance_template.foobar", &instanceTemplate), ), @@ -1584,7 +1617,7 @@ func TestAccComputeInstanceTemplate_sourceSnapshotEncryptionKey(t *testing.T) { t.Parallel() var instanceTemplate compute.InstanceTemplate - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "kms_ring_name": tpgresource.GetResourceNameFromSelfLink(kmsKey.KeyRing.Name), @@ -1647,7 +1680,7 @@ func TestAccComputeInstanceTemplate_sourceImageEncryptionKey(t *testing.T) { t.Parallel() var instanceTemplate compute.InstanceTemplate - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "kms_ring_name": tpgresource.GetResourceNameFromSelfLink(kmsKey.KeyRing.Name), @@ -1708,9 +1741,9 @@ func TestAccComputeInstanceTemplate_sourceImageEncryptionKey(t *testing.T) { func TestAccComputeInstanceTemplate_NetworkAttachment(t *testing.T) { t.Parallel() - testNetworkName := acctest.BootstrapSharedTestNetwork(t, "attachment-network") - subnetName := acctest.BootstrapSubnet(t, "tf-test-subnet", testNetworkName) - networkAttachmentName := acctest.BootstrapNetworkAttachment(t, "tf-test-attachment", subnetName) + testNetworkName := tpgcompute.BootstrapSharedTestNetwork(t, "attachment-network") + subnetName := tpgcompute.BootstrapSubnet(t, "tf-test-subnet", testNetworkName) + networkAttachmentName := tpgcompute.BootstrapNetworkAttachment(t, "tf-test-attachment", subnetName) // Need to have the full network attachment name in the format project/{project_id}/regions/{region_id}/networkAttachments/{networkAttachmentName} fullFormNetworkAttachmentName := fmt.Sprintf("projects/%s/regions/%s/networkAttachments/%s", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), networkAttachmentName) @@ -5664,3 +5697,48 @@ resource "google_compute_instance_template" "foobar" { } `, context) } + + +{{ if ne $.TargetVersionName `ga` -}} +func testAccComputeInstanceTemplate_aliasIpv6Range(suffix string) string { + return fmt.Sprintf(` +resource "google_compute_network" "custom-test" { + name = "tf-test-network-%s" + auto_create_subnetworks = false + enable_ula_internal_ipv6 = true +} + +resource "google_compute_subnetwork" "custom-test" { + name = "tf-test-subnetwork-%s" + region = "us-central1" + network = google_compute_network.custom-test.id + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } +} + +resource "google_compute_instance_template" "foobar" { + name = "tf-test-template-%s" + machine_type = "e2-medium" + + disk { + source_image = "debian-cloud/debian-11" + auto_delete = true + boot = true + } + + network_interface { + subnetwork = google_compute_subnetwork.custom-test.name + stack_type = "IPV6_ONLY" + alias_ipv6_range { + ip_cidr_range = "/96" + } + } +} +`, suffix, suffix, suffix) +} +{{- end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instance_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instance_test.go.tmpl index 4d7898ef55ab..d87fdaa8446e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instance_test.go.tmpl @@ -1,13 +1,7 @@ package compute_test import ( - {{- if ne $.TargetVersionName "ga" }} - "encoding/json" - {{- end }} "fmt" - {{- if ne $.TargetVersionName "ga" }} - "google.golang.org/api/googleapi" - {{- end }} "reflect" "regexp" "sort" @@ -22,8 +16,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-provider-google/google/envvar" tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" {{ if eq $.TargetVersionName `ga` }} @@ -31,6 +28,7 @@ import ( {{- else }} compute "google.golang.org/api/compute/v0.beta" {{- end }} + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestMinCpuPlatformDiffSuppress(t *testing.T) { @@ -259,7 +257,7 @@ func computeInstanceImportStep(zone, instanceName string, additionalImportIgnore func TestAccComputeInstance_basic1(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -295,7 +293,7 @@ func TestAccComputeInstance_basic1(t *testing.T) { func TestAccComputeInstance_basic2(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -320,7 +318,7 @@ func TestAccComputeInstance_basic2(t *testing.T) { func TestAccComputeInstance_basic3(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -345,7 +343,7 @@ func TestAccComputeInstance_basic3(t *testing.T) { func TestAccComputeInstance_basic4(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -370,7 +368,7 @@ func TestAccComputeInstance_basic4(t *testing.T) { func TestAccComputeInstance_basic5(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -395,7 +393,7 @@ func TestAccComputeInstance_basic5(t *testing.T) { func TestAccComputeInstance_metadataGceContainerDeclaration(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -420,7 +418,7 @@ func TestAccComputeInstance_metadataGceContainerDeclaration(t *testing.T) { func TestAccComputeInstance_resourceManagerTags(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) context := map[string]interface{}{ "project": envvar.GetTestProjectFromEnv(), @@ -453,7 +451,7 @@ func TestAccComputeInstance_resourceManagerTags(t *testing.T) { func TestAccComputeInstance_diskResourcePolicies(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) context := map[string]interface{}{ "project": envvar.GetTestProjectFromEnv(), @@ -489,7 +487,7 @@ func TestAccComputeInstance_diskResourcePolicies(t *testing.T) { func TestAccComputeInstance_diskResourcePolicies_attachmentDiff(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "random_suffix": acctest.RandString(t, 10), @@ -546,7 +544,7 @@ func TestAccComputeInstance_diskResourcePolicies_attachmentDiff(t *testing.T) { func TestAccComputeInstance_machineTypeUrl(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var machineTypeUrl = "zones/us-central1-a/machineTypes/e2-medium" @@ -570,7 +568,7 @@ func TestAccComputeInstance_machineTypeUrl(t *testing.T) { func TestAccComputeInstance_descriptionUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -601,7 +599,7 @@ func TestAccComputeInstance_descriptionUpdate(t *testing.T) { func TestAccComputeInstance_IP(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var ipName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -624,7 +622,7 @@ func TestAccComputeInstance_IP(t *testing.T) { func TestAccComputeInstance_IPv6(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var ipName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var ptrName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -678,7 +676,7 @@ func TestAccComputeInstance_ipv6OnlyMacAddress(t *testing.T) { func TestAccComputeInstance_ipv6ExternalReservation(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -701,7 +699,7 @@ func TestAccComputeInstance_ipv6ExternalReservation(t *testing.T) { func TestAccComputeInstance_internalIPv6(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var ipName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -726,7 +724,7 @@ func TestAccComputeInstance_internalIPv6(t *testing.T) { func TestAccComputeInstance_internalIPv6PrefixLength(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -750,7 +748,7 @@ func TestAccComputeInstance_internalIPv6PrefixLength(t *testing.T) { func TestAccComputeInstance_PTRRecord(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var ptrName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var ipName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -783,7 +781,7 @@ func TestAccComputeInstance_PTRRecord(t *testing.T) { } func TestAccComputeInstance_networkTier(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -808,22 +806,22 @@ func TestAccComputeInstance_networkTier(t *testing.T) { func TestAccComputeInstance_diskEncryption(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) bootEncryptionKey := "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=" bootEncryptionKeyHash := "esTuF7d4eatX4cnc4JsiEiaI+Rff78JgPhA/v1zxX9E=" - diskNameToEncryptionKey := map[string]*compute.CustomerEncryptionKey{ + diskNameToEncryptionKey := map[string]map[string]interface{}{ fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - RawKey: "Ym9vdDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", - Sha256: "awJ7p57H+uVZ9axhJjl1D3lfC2MgA/wnt/z88Ltfvss=", + "rawKey": "Ym9vdDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", + "sha256": "awJ7p57H+uVZ9axhJjl1D3lfC2MgA/wnt/z88Ltfvss=", }, fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - RawKey: "c2Vjb25kNzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", - Sha256: "7TpIwUdtCOJpq2m+3nt8GFgppu6a2Xsj1t0Gexk13Yc=", + "rawKey": "c2Vjb25kNzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", + "sha256": "7TpIwUdtCOJpq2m+3nt8GFgppu6a2Xsj1t0Gexk13Yc=", }, fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - RawKey: "dGhpcmQ2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", - Sha256: "b3pvaS7BjDbCKeLPPTx7yXBuQtxyMobCHN1QJR43xeM=", + "rawKey": "dGhpcmQ2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", + "sha256": "b3pvaS7BjDbCKeLPPTx7yXBuQtxyMobCHN1QJR43xeM=", }, } @@ -847,14 +845,14 @@ func TestAccComputeInstance_diskEncryption(t *testing.T) { func TestAccComputeInstance_diskEncryptionRestart(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) bootEncryptionKey := "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=" bootEncryptionKeyHash := "esTuF7d4eatX4cnc4JsiEiaI+Rff78JgPhA/v1zxX9E=" - diskNameToEncryptionKey := map[string]*compute.CustomerEncryptionKey{ + diskNameToEncryptionKey := map[string]map[string]interface{}{ fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - RawKey: "Ym9vdDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", - Sha256: "awJ7p57H+uVZ9axhJjl1D3lfC2MgA/wnt/z88Ltfvss=", + "rawKey": "Ym9vdDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=", + "sha256": "awJ7p57H+uVZ9axhJjl1D3lfC2MgA/wnt/z88Ltfvss=", }, } @@ -886,24 +884,24 @@ func TestAccComputeInstance_diskEncryptionRestart(t *testing.T) { func TestAccComputeInstance_kmsDiskEncryption(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) - bootKmsKeyName := kms.CryptoKey.Name - diskNameToEncryptionKey := map[string]*compute.CustomerEncryptionKey{ + bootKmsKeyName := bootstrapped.CryptoKey.Name + diskNameToEncryptionKey := map[string]map[string]interface{}{ fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - KmsKeyName: kms.CryptoKey.Name, + "kmsKeyName": bootstrapped.CryptoKey.Name, }, fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - KmsKeyName: kms.CryptoKey.Name, + "kmsKeyName": bootstrapped.CryptoKey.Name, }, fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)): { - KmsKeyName: kms.CryptoKey.Name, + "kmsKeyName": bootstrapped.CryptoKey.Name, }, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -930,7 +928,7 @@ func TestAccComputeInstance_kmsDiskEncryption(t *testing.T) { func TestAccComputeInstance_rsaBootDiskEncryption(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "rsa_encrypted_key": "ieCx/NcW06PcT7Ep1X6LUTc/hLvUDYyzSZPPVCVPTVEohpeHASqC8uw5TzyO9U+Fka9JFHz0mBibXUInrC/jEk014kCK/NPjYgEMOyssZ4ZINPKxlUh2zn1bV+MCaTICrdmuSBTWlUUiFoDD6PYznLwh8ZNdaheCeZ8ewEXgFQ8V+sDroLaN3Xs3MDTXQEMMoNUXMCZEIpg9Vtp9x2oeQ5lAbtt7bYAAHf5l+gJWw3sUfs0/Glw5fpdjT8Uggrr+RMZezGrltJEF293rvTIjWOEB3z5OHyHwQkvdrPDFcTqsLfh+8Hr8g+mf+7zVPEC8nEbqpdl3GPv3A7AwpFp7MA==", @@ -954,12 +952,12 @@ func TestAccComputeInstance_rsaBootDiskEncryption(t *testing.T) { func TestAccComputeInstance_instanceEncryption(t *testing.T) { t.Parallel() - var instance compute.Instance - kms := acctest.BootstrapKMSKey(t) + var instance map[string]interface{} + bootstrapped := kms.BootstrapKMSKey(t) context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), - "encryption_key": kms.CryptoKey.Name, + "encryption_key": bootstrapped.CryptoKey.Name, "desired_status": "RUNNING", } @@ -975,7 +973,7 @@ func TestAccComputeInstance_instanceEncryption(t *testing.T) { "desired_status": "RUNNING", } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:{project_number}-compute@developer.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -1016,7 +1014,7 @@ func TestAccComputeInstance_instanceEncryption(t *testing.T) { func TestAccComputeInstance_snapshot(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context := map[string]interface{}{ "instance_name1": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -1044,7 +1042,7 @@ func TestAccComputeInstance_snapshot(t *testing.T) { func TestAccComputeInstance_repdBootFromSnapshot(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context := map[string]interface{}{ "network_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -1075,13 +1073,13 @@ func TestAccComputeInstance_repdBootFromSnapshot(t *testing.T) { func TestAccComputeInstance_snapshotEncryption(t *testing.T) { t.Parallel() - var instance compute.Instance - kms := acctest.BootstrapKMSKey(t) + var instance map[string]interface{} + bootstrapped := kms.BootstrapKMSKey(t) context := map[string]interface{}{ "instance_name1": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "instance_name2": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "snapshot_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), - "kms_key": kms.CryptoKey.Name, + "kms_key": bootstrapped.CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "ieCx/NcW06PcT7Ep1X6LUTc/hLvUDYyzSZPPVCVPTVEohpeHASqC8uw5TzyO9U+Fka9JFHz0mBibXUInrC/jEk014kCK/NPjYgEMOyssZ4ZINPKxlUh2zn1bV+MCaTICrdmuSBTWlUUiFoDD6PYznLwh8ZNdaheCeZ8ewEXgFQ8V+sDroLaN3Xs3MDTXQEMMoNUXMCZEIpg9Vtp9x2oeQ5lAbtt7bYAAHf5l+gJWw3sUfs0/Glw5fpdjT8Uggrr+RMZezGrltJEF293rvTIjWOEB3z5OHyHwQkvdrPDFcTqsLfh+8Hr8g+mf+7zVPEC8nEbqpdl3GPv3A7AwpFp7MA==", } @@ -1116,13 +1114,13 @@ func TestAccComputeInstance_snapshotEncryption(t *testing.T) { func TestAccComputeInstance_imageEncryption(t *testing.T) { t.Parallel() - var instance compute.Instance - kms := acctest.BootstrapKMSKey(t) + var instance map[string]interface{} + bootstrapped := kms.BootstrapKMSKey(t) context := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "image_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "disk_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), - "kms_key": kms.CryptoKey.Name, + "kms_key": bootstrapped.CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "ieCx/NcW06PcT7Ep1X6LUTc/hLvUDYyzSZPPVCVPTVEohpeHASqC8uw5TzyO9U+Fka9JFHz0mBibXUInrC/jEk014kCK/NPjYgEMOyssZ4ZINPKxlUh2zn1bV+MCaTICrdmuSBTWlUUiFoDD6PYznLwh8ZNdaheCeZ8ewEXgFQ8V+sDroLaN3Xs3MDTXQEMMoNUXMCZEIpg9Vtp9x2oeQ5lAbtt7bYAAHf5l+gJWw3sUfs0/Glw5fpdjT8Uggrr+RMZezGrltJEF293rvTIjWOEB3z5OHyHwQkvdrPDFcTqsLfh+8Hr8g+mf+7zVPEC8nEbqpdl3GPv3A7AwpFp7MA==", } @@ -1157,7 +1155,7 @@ func TestAccComputeInstance_imageEncryption(t *testing.T) { func TestAccComputeInstance_attachedDisk_RSAencryption(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "disk_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -1182,7 +1180,7 @@ func TestAccComputeInstance_attachedDisk_RSAencryption(t *testing.T) { func TestAccComputeInstance_resourcePolicyUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var scheduleName1 = fmt.Sprintf("tf-tests-%s", acctest.RandString(t, 10)) var scheduleName2 = fmt.Sprintf("tf-tests-%s", acctest.RandString(t, 10)) @@ -1234,7 +1232,7 @@ func TestAccComputeInstance_resourcePolicyUpdate(t *testing.T) { func TestAccComputeInstance_attachedDisk(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) @@ -1259,7 +1257,7 @@ func TestAccComputeInstance_attachedDisk(t *testing.T) { func TestAccComputeInstance_attachedDisk_sourceUrl(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) @@ -1284,7 +1282,7 @@ func TestAccComputeInstance_attachedDisk_sourceUrl(t *testing.T) { func TestAccComputeInstance_attachedDisk_modeRo(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) @@ -1309,7 +1307,7 @@ func TestAccComputeInstance_attachedDisk_modeRo(t *testing.T) { func TestAccComputeInstance_attachDisk_forceAttach(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) var forceAttachSetToTrue = true @@ -1355,7 +1353,7 @@ func TestAccComputeInstance_attachDisk_forceAttach(t *testing.T) { func TestAccComputeInstance_bootDiskUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "disk_size": 10, @@ -1400,7 +1398,7 @@ func TestAccComputeInstance_bootDiskUpdate(t *testing.T) { func TestAccComputeInstance_attachedDiskUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) var diskName2 = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) @@ -1453,7 +1451,7 @@ func TestAccComputeInstance_attachedDiskUpdate(t *testing.T) { func TestAccComputeInstance_bootDisk_source(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -1478,7 +1476,7 @@ func TestAccComputeInstance_bootDisk_source(t *testing.T) { func TestAccComputeInstance_bootDisk_sourceUrl(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -1503,7 +1501,7 @@ func TestAccComputeInstance_bootDisk_sourceUrl(t *testing.T) { func TestAccComputeInstance_bootDisk_type(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskType = "pd-ssd" @@ -1546,7 +1544,7 @@ func TestAccComputeInstance_bootDisk_mode(t *testing.T) { func TestAccComputeInstance_bootDisk_forceAttach(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var forceAttachSetToTrue = true @@ -1592,7 +1590,7 @@ func TestAccComputeInstance_bootDisk_forceAttach(t *testing.T) { func TestAccComputeInstance_with375GbScratchDisk(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1634,7 +1632,7 @@ func TestAccComputeInstance_with18TbScratchDisk(t *testing.T) { t.Skip() t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1677,7 +1675,7 @@ func TestAccComputeInstance_with18TbScratchDisk(t *testing.T) { func TestAccComputeInstance_forceNewAndChangeMetadata(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1708,7 +1706,7 @@ func TestAccComputeInstance_forceNewAndChangeMetadata(t *testing.T) { func TestAccComputeInstance_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1742,7 +1740,7 @@ func TestAccComputeInstance_update(t *testing.T) { func TestAccComputeInstance_stopInstanceToUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1784,7 +1782,7 @@ func TestAccComputeInstance_stopInstanceToUpdate(t *testing.T) { func TestAccComputeInstance_serviceAccount(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1813,7 +1811,7 @@ func TestAccComputeInstance_serviceAccount(t *testing.T) { func TestAccComputeInstance_noServiceAccount(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1837,7 +1835,7 @@ func TestAccComputeInstance_noServiceAccount(t *testing.T) { func TestAccComputeInstance_serviceAccountEmail_0scopes(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1861,7 +1859,7 @@ func TestAccComputeInstance_serviceAccountEmail_0scopes(t *testing.T) { func TestAccComputeInstance_serviceAccount_updated(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1916,7 +1914,7 @@ func TestAccComputeInstance_serviceAccount_updated(t *testing.T) { func TestAccComputeInstance_serviceAccount_updated0to1to0scopes(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1961,7 +1959,7 @@ func TestAccComputeInstance_serviceAccount_updated0to1to0scopes(t *testing.T) { func TestAccComputeInstance_scheduling(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1994,7 +1992,7 @@ func TestAccComputeInstance_schedulingTerminationTime(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) now := time.Now().UTC() terminationTimeNonFormatted := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 9999, now.Location()) @@ -2047,7 +2045,7 @@ func TestAccComputeInstance_schedulingTerminationTime(t *testing.T) { func TestAccComputeInstance_advancedMachineFeatures(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2078,7 +2076,7 @@ func TestAccComputeInstance_advancedMachineFeatures(t *testing.T) { func TestAccComputeInstance_performanceMonitoringUnit(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "performance_monitoring_unit": "STANDARD", @@ -2117,7 +2115,7 @@ func TestAccComputeInstance_performanceMonitoringUnit(t *testing.T) { func TestAccComputeInstance_enableUefiNetworking(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "enable_uefi_networking": "true", @@ -2176,7 +2174,7 @@ func TestAccComputeInstance_soleTenantNodeAffinities(t *testing.T) { func TestAccComputeInstance_reservationAffinities(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-resaffinity-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2216,7 +2214,7 @@ func TestAccComputeInstance_reservationAffinities(t *testing.T) { func TestAccComputeInstance_hostErrorTimeoutSecconds(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "zone": "us-central1-a", @@ -2294,7 +2292,7 @@ func TestAccComputeInstance_hostErrorTimeoutSecconds(t *testing.T) { func TestAccComputeInstance_subnet_auto(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2318,7 +2316,7 @@ func TestAccComputeInstance_subnet_auto(t *testing.T) { func TestAccComputeInstance_subnet_custom(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2344,7 +2342,7 @@ func TestAccComputeInstance_subnet_xpn(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) org := envvar.GetTestOrgFromEnv(t) billingId := envvar.GetTestBillingAccountFromEnv(t) @@ -2374,7 +2372,7 @@ func TestAccComputeInstance_subnet_xpn(t *testing.T) { func TestAccComputeInstance_networkIPAuto(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2397,7 +2395,7 @@ func TestAccComputeInstance_networkIPAuto(t *testing.T) { func TestAccComputeInstance_network_ip_custom(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var ipAddress = "10.0.200.200" acctest.VcrTest(t, resource.TestCase{ @@ -2420,7 +2418,7 @@ func TestAccComputeInstance_network_ip_custom(t *testing.T) { func TestAccComputeInstance_private_image_family(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) var familyName = fmt.Sprintf("tf-testf-%s", acctest.RandString(t, 10)) @@ -2444,7 +2442,7 @@ func TestAccComputeInstance_private_image_family(t *testing.T) { func TestAccComputeInstance_networkPerformanceConfig(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-testd-%s", acctest.RandString(t, 10)) var imageName = fmt.Sprintf("tf-testf-%s", acctest.RandString(t, 10)) @@ -2469,7 +2467,7 @@ func TestAccComputeInstance_networkPerformanceConfig(t *testing.T) { func TestAccComputeInstance_forceChangeMachineTypeManually(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2498,7 +2496,7 @@ func TestAccComputeInstance_forceChangeMachineTypeManually(t *testing.T) { func TestAccComputeInstance_multiNic(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) subnetworkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -2523,7 +2521,7 @@ func TestAccComputeInstance_multiNic(t *testing.T) { func TestAccComputeInstance_nictype_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2552,7 +2550,7 @@ func TestAccComputeInstance_nictype_update(t *testing.T) { func TestAccComputeInstance_guestAccelerator(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2576,7 +2574,7 @@ func TestAccComputeInstance_guestAccelerator(t *testing.T) { func TestAccComputeInstance_guestAcceleratorSkip(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2599,7 +2597,7 @@ func TestAccComputeInstance_guestAcceleratorSkip(t *testing.T) { func TestAccComputeInstance_minCpuPlatform(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2630,7 +2628,7 @@ func TestAccComputeInstance_minCpuPlatform(t *testing.T) { func TestAccComputeInstance_deletionProtectionExplicitFalse(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2653,7 +2651,7 @@ func TestAccComputeInstance_deletionProtectionExplicitFalse(t *testing.T) { func TestAccComputeInstance_deletionProtectionExplicitTrueAndUpdateFalse(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2686,7 +2684,7 @@ func TestAccComputeInstance_deletionProtectionExplicitTrueAndUpdateFalse(t *test func TestAccComputeInstance_primaryAliasIpRange(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2709,7 +2707,7 @@ func TestAccComputeInstance_primaryAliasIpRange(t *testing.T) { func TestAccComputeInstance_secondaryAliasIpRange(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) subnetName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -2739,10 +2737,74 @@ func TestAccComputeInstance_secondaryAliasIpRange(t *testing.T) { }) } +{{ if ne $.TargetVersionName `ga` -}} +func TestAccComputeInstance_addAliasIpv6Range(t *testing.T) { + t.Parallel() + + var instance map[string]interface{} + instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + subnetName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeInstance_aliasIpv6Range_noAlias(networkName, subnetName, instanceName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceExists(t, "google_compute_instance.foobar", &instance), + ), + }, + { + Config: testAccComputeInstance_aliasIpv6Range(networkName, subnetName, instanceName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceExists(t, "google_compute_instance.foobar", &instance), + testAccCheckComputeInstanceHasAliasIpv6Range(&instance, "/96"), + ), + }, + computeInstanceImportStep("us-central1-a", instanceName, []string{"network_interface.0.alias_ipv6_range.0.ip_cidr_range"}), + }, + }) +} + +func TestAccComputeInstance_removeAliasIpv6Range(t *testing.T) { + t.Parallel() + + var instance map[string]interface{} + instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + subnetName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeInstance_aliasIpv6Range(networkName, subnetName, instanceName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceExists(t, "google_compute_instance.foobar", &instance), + testAccCheckComputeInstanceHasAliasIpv6Range(&instance, "/96"), + ), + }, + { + Config: testAccComputeInstance_aliasIpv6Range_noAlias(networkName, subnetName, instanceName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeInstanceExists(t, "google_compute_instance.foobar", &instance), + testAccCheckComputeInstanceNoAliasIpv6Range(&instance), + ), + }, + }, + }) +} +{{- end }} + func TestAccComputeInstance_aliasIpRangeCommonAddresses(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) networkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) subnetName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -2786,7 +2848,7 @@ func TestAccComputeInstance_aliasIpRangeCommonAddresses(t *testing.T) { func TestAccComputeInstance_hostname(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2809,7 +2871,7 @@ func TestAccComputeInstance_hostname(t *testing.T) { func TestAccComputeInstance_shieldedVmConfig(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -2840,11 +2902,11 @@ func TestAccComputeInstance_shieldedVmConfig(t *testing.T) { func TestAccComputeInstanceConfidentialInstanceConfigMain(t *testing.T) { t.Parallel() - var instance compute.Instance - var instance2 compute.Instance + var instance map[string]interface{} + var instance2 map[string]interface{} {{- if ne $.TargetVersionName "ga" }} - var instance3 compute.Instance - var instance4 compute.Instance + var instance3 map[string]interface{} + var instance4 map[string]interface{} {{- end }} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -2890,13 +2952,13 @@ func TestAccComputeInstanceConfidentialInstanceConfigMain(t *testing.T) { func TestAccComputeInstance_confidentialHyperDiskBootDisk(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-hyperdisk-key1") + bootstrapped := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-hyperdisk-key1") context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "confidential_compute": true, - "key_ring": kms.KeyRing.Name, - "key_name": kms.CryptoKey.Name, + "key_ring": bootstrapped.KeyRing.Name, + "key_name": bootstrapped.CryptoKey.Name, "zone": "us-central1-a", "machine_type": "n2d-standard-16", "confidential_instance_config": "confidential_instance_config { \n \t enable_confidential_compute = true \n }", @@ -2983,7 +3045,7 @@ func TestAccComputeInstance_enableDisplay(t *testing.T) { func TestAccComputeInstance_desiredStatusTerminatedOnCreation(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -3023,7 +3085,7 @@ func TestAccComputeInstance_desiredStatusTerminatedOnCreation(t *testing.T) { func TestAccComputeInstance_desiredStatusSuspendedOnCreation(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -3063,7 +3125,7 @@ func TestAccComputeInstance_desiredStatusSuspendedOnCreation(t *testing.T) { func TestAccComputeInstance_desiredStatusUpdateBasic(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3117,7 +3179,7 @@ func TestAccComputeInstance_desiredStatusUpdateBasic(t *testing.T) { func TestAccComputeInstance_desiredStatusTerminatedUpdateFields(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3159,7 +3221,7 @@ func TestAccComputeInstance_desiredStatusTerminatedUpdateFields(t *testing.T) { func TestAccComputeInstance_updateRunning_desiredStatusRunning_allowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3193,7 +3255,7 @@ const errorAllowStoppingMsg = "please set allow_stopping_for_update" func TestAccComputeInstance_updateRunning_desiredStatusNotSet_notAllowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3220,7 +3282,7 @@ func TestAccComputeInstance_updateRunning_desiredStatusNotSet_notAllowStoppingFo func TestAccComputeInstance_updateRunning_desiredStatusRunning_notAllowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3247,7 +3309,7 @@ func TestAccComputeInstance_updateRunning_desiredStatusRunning_notAllowStoppingF func TestAccComputeInstance_updateRunning_desiredStatusTerminated_allowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3279,7 +3341,7 @@ func TestAccComputeInstance_updateRunning_desiredStatusTerminated_allowStoppingF func TestAccComputeInstance_updateRunning_desiredStatusTerminated_notAllowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3311,7 +3373,7 @@ func TestAccComputeInstance_updateRunning_desiredStatusTerminated_notAllowStoppi func TestAccComputeInstance_updateTerminated_desiredStatusNotSet_allowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3351,7 +3413,7 @@ func TestAccComputeInstance_updateTerminated_desiredStatusNotSet_allowStoppingFo func TestAccComputeInstance_updateTerminated_desiredStatusTerminated_allowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3391,7 +3453,7 @@ func TestAccComputeInstance_updateTerminated_desiredStatusTerminated_allowStoppi func TestAccComputeInstance_updateTerminated_desiredStatusNotSet_notAllowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3431,7 +3493,7 @@ func TestAccComputeInstance_updateTerminated_desiredStatusNotSet_notAllowStoppin func TestAccComputeInstance_updateTerminated_desiredStatusTerminated_notAllowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3471,7 +3533,7 @@ func TestAccComputeInstance_updateTerminated_desiredStatusTerminated_notAllowSto func TestAccComputeInstance_updateTerminated_desiredStatusRunning_allowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3511,7 +3573,7 @@ func TestAccComputeInstance_updateTerminated_desiredStatusRunning_allowStoppingF func TestAccComputeInstance_updateTerminated_desiredStatusRunning_notAllowStoppingForUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -3551,7 +3613,7 @@ func TestAccComputeInstance_updateTerminated_desiredStatusRunning_notAllowStoppi func TestAccComputeInstance_desiredStatus_suspended(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "desired_status": "RUNNING", @@ -3616,7 +3678,7 @@ func TestAccComputeInstance_resourcePolicySpread(t *testing.T) { t.Parallel() instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - var instance compute.Instance + var instance map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3683,7 +3745,7 @@ func TestAccComputeInstance_subnetworkProjectMustMatchError(t *testing.T) { func TestAccComputeInstance_networkIpUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) suffix := fmt.Sprintf("%s", acctest.RandString(t, 10)) @@ -3740,7 +3802,7 @@ func TestAccComputeInstance_queueCount(t *testing.T) { func TestAccComputeInstance_spotVM(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3762,7 +3824,7 @@ func TestAccComputeInstance_spotVM(t *testing.T) { func TestAccComputeInstance_spotVM_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3792,12 +3854,13 @@ func TestAccComputeInstance_spotVM_update(t *testing.T) { func TestAccComputeInstance_maxRunDuration_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-mrd-%s", acctest.RandString(t, 10)) - var expectedMaxRunDuration = compute.Duration{} // Define in testAccComputeInstance_standardVM_maxRunDurationUpdated - expectedMaxRunDuration.Nanos = 456 - expectedMaxRunDuration.Seconds = 60 + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(456), + "seconds": "60", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3825,12 +3888,13 @@ func TestAccComputeInstance_maxRunDuration_update(t *testing.T) { func TestAccComputeInstance_standardVM_maxRunDuration_stopTerminationAction(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - var expectedMaxRunDuration = compute.Duration{} // Define in testAccComputeInstance_standardVM_maxRunDuration - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "60", + } var instanceTerminationAction = "STOP" acctest.VcrTest(t, resource.TestCase{ @@ -3855,12 +3919,13 @@ func TestAccComputeInstance_standardVM_maxRunDuration_stopTerminationAction(t *t func TestAccComputeInstance_localSsdVM_maxRunDuration_stopTerminationAction(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - var expectedMaxRunDuration = compute.Duration{} // Define in testAccComputeInstance_localSsdVM_maxRunDuration - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 180 + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "180", + } var instanceTerminationAction = "STOP" acctest.VcrTest(t, resource.TestCase{ @@ -3885,12 +3950,13 @@ func TestAccComputeInstance_localSsdVM_maxRunDuration_stopTerminationAction(t *t func TestAccComputeInstance_spotVM_maxRunDuration_deleteTerminationAction(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - var expectedMaxRunDuration = compute.Duration{} // Define in testAccComputeInstance_spotVM_maxRunDuration - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "60", + } var instanceTerminationAction = "DELETE" acctest.VcrTest(t, resource.TestCase{ @@ -3915,12 +3981,13 @@ func TestAccComputeInstance_spotVM_maxRunDuration_deleteTerminationAction(t *tes func TestAccComputeInstance_standardVM_maxRunDuration_deleteTerminationAction(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - var expectedMaxRunDuration = compute.Duration{} // Define in testAccComputeInstance_standardVM_maxRunDuration - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "60", + } var instanceTerminationAction = "DELETE" acctest.VcrTest(t, resource.TestCase{ @@ -3945,12 +4012,13 @@ func TestAccComputeInstance_standardVM_maxRunDuration_deleteTerminationAction(t func TestAccComputeInstance_spotVM_maxRunDuration_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) // Define in testAccComputeInstance_spotVM_maxRunDuration - var expectedMaxRunDuration = compute.Duration{} - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "60", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -3980,12 +4048,13 @@ func TestAccComputeInstance_spotVM_maxRunDuration_update(t *testing.T) { func TestAccComputeInstance_localSsdRecoveryTimeout(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - var expectedLocalSsdRecoveryTimeout = compute.Duration{} // Define in testAccComputeInstance_localSsdRecoveryTimeout - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 3600 + expectedLocalSsdRecoveryTimeout := map[string]interface{}{ + "nanos": float64(0), + "seconds": "3600", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4008,12 +4077,13 @@ func TestAccComputeInstance_localSsdRecoveryTimeout(t *testing.T) { func TestAccComputeInstance_localSsdRecoveryTimeout_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) // Define in testAccComputeInstance_localSsdRecoveryTimeout - var expectedLocalSsdRecoveryTimeout = compute.Duration{} - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 3600 + expectedLocalSsdRecoveryTimeout := map[string]interface{}{ + "nanos": float64(0), + "seconds": "3600", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -4044,12 +4114,16 @@ func TestAccComputeInstance_localSsdRecoveryTimeout_update(t *testing.T) { func TestAccComputeInstance_partnerMetadata(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := make(map[string]map[string]interface{}) + expectedPartnerMetadata[namespace] = map[string]interface{}{ + "entries": map[string]interface{}{ + "key1": "value1", + "key2": float64(2), + "key3": map[string]interface{}{"key31": "value31"}, + }, } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4072,12 +4146,16 @@ func TestAccComputeInstance_partnerMetadata(t *testing.T) { func TestAccComputeInstance_partnerMetadata_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := make(map[string]map[string]interface{}) + expectedPartnerMetadata[namespace] = map[string]interface{}{ + "entries": map[string]interface{}{ + "key1": "value1", + "key2": float64(2), + "key3": map[string]interface{}{"key31": "value31"}, + }, } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4108,12 +4186,16 @@ func TestAccComputeInstance_partnerMetadata_update(t *testing.T) { func TestAccComputeInstance_partnerMetadata_deletePartnerMetadata(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := make(map[string]map[string]interface{}) + expectedPartnerMetadata[namespace] = map[string]interface{}{ + "entries": map[string]interface{}{ + "key1": "value1", + "key2": float64(2), + "key3": map[string]interface{}{"key31": "value31"}, + }, } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4145,7 +4227,7 @@ func TestAccComputeInstance_partnerMetadata_deletePartnerMetadata(t *testing.T) func TestAccComputeInstance_metadataStartupScript_update(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -4174,7 +4256,7 @@ func TestAccComputeInstance_metadataStartupScript_update(t *testing.T) { func TestAccComputeInstance_metadataStartupScript_gracefulSwitch(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -4211,7 +4293,7 @@ func TestAccComputeInstance_metadataStartupScript_gracefulSwitch(t *testing.T) { func TestAccComputeInstance_regionBootDisk(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var diskName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var suffix = acctest.RandString(t, 10) @@ -4236,7 +4318,7 @@ func TestAccComputeInstance_regionBootDisk(t *testing.T) { func TestAccComputeInstance_creationOnlyAttributionLabel(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -4271,7 +4353,7 @@ func TestAccComputeInstance_creationOnlyAttributionLabelConfiguredOnUpdate(t *te acctest.SkipIfVcr(t) t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -4306,7 +4388,7 @@ func TestAccComputeInstance_proactiveAttributionLabel(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -4339,7 +4421,7 @@ func TestAccComputeInstance_proactiveAttributionLabel(t *testing.T) { func TestAccComputeInstance_autoDeleteUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "auto_delete": "true", @@ -4382,7 +4464,7 @@ func TestAccComputeInstance_autoDeleteUpdate(t *testing.T) { func TestAccComputeInstance_keyRevocationActionType(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "key_revocation_action_type": `"NONE"`, @@ -4469,7 +4551,7 @@ func TestAccComputeInstanceNetworkIntefaceWithSecurityPolicy(t *testing.T) { func TestAccComputeInstance_GracefulShutdownWithResetUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acceptableByApi_1 := map[string]interface{}{ "instance_name": instanceName, @@ -4553,7 +4635,7 @@ func TestAccComputeInstance_GracefulShutdownWithResetUpdate(t *testing.T) { func TestAccComputeInstance_GracefulShutdownWithoutResetUpdate(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acceptableByApi_1 := map[string]interface{}{ "instance_name": instanceName, @@ -4656,7 +4738,7 @@ func TestAccComputeInstance_GracefulShutdownWithoutResetUpdate(t *testing.T) { func TestAccComputeInstance_schedulingSkipGuestOSShutdown(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -4687,7 +4769,7 @@ func TestAccComputeInstance_schedulingSkipGuestOSShutdown(t *testing.T) { func TestAccComputeInstance_preemptionNoticeDuration(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4709,7 +4791,7 @@ func TestAccComputeInstance_preemptionNoticeDuration(t *testing.T) { } func testAccComputeInstance_nic_securityPolicyCreateWithTwoAccessConfigs(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var policyName = fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) var suffix = acctest.RandString(t, 10) @@ -4737,7 +4819,7 @@ func testAccComputeInstance_nic_securityPolicyCreateWithTwoAccessConfigs(t *test } func testAccComputeInstance_nic_securityPolicyCreateWithEmptyAndNullSecurityPolicies(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var suffix = acctest.RandString(t, 10) @@ -4764,7 +4846,7 @@ func testAccComputeInstance_nic_securityPolicyCreateWithEmptyAndNullSecurityPoli } func testAccComputeInstance_nic_securityPolicyCreateWithTwoNicsAndTwoAccessConfigsUpdateOnlyOnePolicy(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var policyName = fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) var policyName2 = fmt.Sprintf("tf-test-policy2-%s", acctest.RandString(t, 10)) @@ -4806,7 +4888,7 @@ func testAccComputeInstance_nic_securityPolicyCreateWithTwoNicsAndTwoAccessConfi } func testAccComputeInstance_nic_securityPolicyCreateWithTwoAccessConfigsUpdateSecurityPoliciesWithStoppedMachine(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var policyName = fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) var suffix = acctest.RandString(t, 10) @@ -4841,7 +4923,7 @@ func testAccComputeInstance_nic_securityPolicyCreateWithTwoAccessConfigsUpdateSe } func testAccComputeInstance_nic_securityPolicyCreateWithTwoNicsAndTwoAccessConfigsUpdateRemoveAccessConfig(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var policyName = fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) var policyName2 = fmt.Sprintf("tf-test-policy2-%s", acctest.RandString(t, 10)) @@ -4879,7 +4961,7 @@ func testAccComputeInstance_nic_securityPolicyCreateWithTwoNicsAndTwoAccessConfi } func testAccComputeInstance_nic_securityPolicyCreateWithTwoNicsAndTwoAccessConfigsUpdateSwapPolicies(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var policyName = fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) var policyName2 = fmt.Sprintf("tf-test-policy2-%s", acctest.RandString(t, 10)) @@ -4948,7 +5030,7 @@ func testAccComputeInstance_nic_securityPolicyCreateWithTwoNicsAndTwoAccessConfi } func testAccComputeInstance_nic_securityPolicyCreateWithAccessConfigUpdateAccessConfig(t *testing.T) { - var instance compute.Instance + var instance map[string]interface{} var instanceName = fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) var policyName = fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) var suffix = acctest.RandString(t, 10) @@ -5151,25 +5233,37 @@ func testAccCheckComputeInstanceUpdateMachineType(t *testing.T, n string) resour config := acctest.GoogleProviderConfig(t) - op, err := tpgcompute.NewClient(config, config.UserAgent).Instances.Stop(config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do() + stopUrl := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s/stop", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: config.Project, + RawURL: stopUrl, + UserAgent: config.UserAgent, + }) if err != nil { return fmt.Errorf("Could not stop instance: %s", err) } - err = tpgcompute.ComputeOperationWaitTime(config, op, config.Project, "Waiting on stop", config.UserAgent, 20*time.Minute) + err = tpgcompute.ComputeOperationWaitTime(config, res, config.Project, "Waiting on stop", config.UserAgent, 20*time.Minute) if err != nil { return fmt.Errorf("Could not stop instance: %s", err) } - machineType := compute.InstancesSetMachineTypeRequest{ - MachineType: "zones/us-central1-a/machineTypes/f1-micro", - } - - op, err = tpgcompute.NewClient(config, config.UserAgent).Instances.SetMachineType( - config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"], &machineType).Do() + setMachineTypeUrl := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s/setMachineType", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]) + res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: config.Project, + RawURL: setMachineTypeUrl, + UserAgent: config.UserAgent, + Body: map[string]interface{}{ + "machineType": "zones/us-central1-a/machineTypes/f1-micro", + }, + }) if err != nil { return fmt.Errorf("Could not change machine type: %s", err) } - err = tpgcompute.ComputeOperationWaitTime(config, op, config.Project, "Waiting machine type change", config.UserAgent, 20*time.Minute) + err = tpgcompute.ComputeOperationWaitTime(config, res, config.Project, "Waiting machine type change", config.UserAgent, 20*time.Minute) if err != nil { return fmt.Errorf("Could not change machine type: %s", err) } @@ -5181,7 +5275,7 @@ func TestAccComputeInstance_NetworkAttachment(t *testing.T) { t.Parallel() suffix := fmt.Sprintf("%s", acctest.RandString(t, 10)) envRegion := envvar.GetTestRegionFromEnv() - var instance compute.Instance + var instance map[string]interface{} {{ if eq $.TargetVersionName `ga` }} providerVersion := "v1" @@ -5277,7 +5371,7 @@ func TestAccComputeInstance_NicStackTypeUpdate(t *testing.T) { func TestAccComputeInstance_IgmpQuery_v2(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} instanceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) suffix := acctest.RandString(t, 10) envRegion := envvar.GetTestRegionFromEnv() @@ -5350,7 +5444,7 @@ func TestAccComputeInstance_NicStackType_IPV6(t *testing.T) { func TestAccComputeInstance_guestOsFeatures(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "guest_os_features": `["UEFI_COMPATIBLE", "VIRTIO_SCSI_MULTIQUEUE", "GVNIC", "IDPF"]`, @@ -5401,7 +5495,7 @@ func TestAccComputeInstance_dynamicNic(t *testing.T) { func TestAccComputeInstance_VSSWindowsDefault(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} var instance1_name = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var snapshot_name = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) var instance2_name = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) @@ -5427,7 +5521,7 @@ func TestAccComputeInstance_VSSWindowsDefault(t *testing.T) { func TestAccComputeInstance_VSSWindows(t *testing.T) { t.Parallel() - var instance compute.Instance + var instance map[string]interface{} context_1 := map[string]interface{}{ "instance1_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), @@ -5537,8 +5631,14 @@ func testAccCheckComputeInstanceDestroyProducer(t *testing.T) func(s *terraform. continue } - _, err := tpgcompute.NewClient(config, config.UserAgent).Instances.Get( - config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do() + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]) + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err == nil { return fmt.Errorf("Instance still exists") } @@ -5553,10 +5653,10 @@ func testAccCheckComputeInstanceExists(t *testing.T, n string, instance interfac panic("Attempted to check existence of Instance that was nil.") } - return testAccCheckComputeInstanceExistsInProject(t, n, envvar.GetTestProjectFromEnv(), instance.(*compute.Instance)) + return testAccCheckComputeInstanceExistsInProject(t, n, envvar.GetTestProjectFromEnv(), instance.(*map[string]interface{})) } -func testAccCheckComputeInstanceExistsInProject(t *testing.T, n, p string, instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceExistsInProject(t *testing.T, n, p string, instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -5568,55 +5668,72 @@ func testAccCheckComputeInstanceExistsInProject(t *testing.T, n, p string, insta } config := acctest.GoogleProviderConfig(t) - {{- if eq $.TargetVersionName "ga" }} - found, err := tpgcompute.NewClient(config, config.UserAgent).Instances.Get( - p, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).Do() - {{- else }} - found, err := tpgcompute.NewClient(config, config.UserAgent).Instances.Get( - p, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]).View("FULL").Do() + url := fmt.Sprintf("%sprojects/%s/zones/%s/instances/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), p, rs.Primary.Attributes["zone"], rs.Primary.Attributes["name"]) + {{- if ne $.TargetVersionName "ga" }} + url = fmt.Sprintf("%s?view=FULL", url) {{- end }} + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: p, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.Name != rs.Primary.Attributes["name"] { + name, _ := found["name"].(string) + if name != rs.Primary.Attributes["name"] { return fmt.Errorf("Instance not found") } - *instance = *found + *instance = found return nil } } func testAccCheckComputeInstanceMetadata( - instance *compute.Instance, + instance *map[string]interface{}, k string, v string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Metadata == nil { + metadata, ok := (*instance)["metadata"].(map[string]interface{}) + if !ok { return fmt.Errorf("no metadata") } - for _, item := range instance.Metadata.Items { - if k != item.Key { + items, _ := metadata["items"].([]interface{}) + for _, raw := range items { + item, ok := raw.(map[string]interface{}) + if !ok { + continue + } + if k != item["key"].(string) { continue } - if item.Value != nil && v == *item.Value { + if val, ok := item["value"].(string); ok && v == val { return nil } - return fmt.Errorf("bad value for %s: %s", k, *item.Value) + return fmt.Errorf("bad value for %s: %v", k, item["value"]) } return fmt.Errorf("metadata not found: %s", k) } } -func testAccCheckComputeInstanceAccessConfig(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceAccessConfig(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - if len(i.AccessConfigs) == 0 { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, raw := range nics { + i, ok := raw.(map[string]interface{}) + if !ok { + continue + } + ac, _ := i["accessConfigs"].([]interface{}) + if len(ac) == 0 { return fmt.Errorf("no access_config") } } @@ -5625,11 +5742,21 @@ func testAccCheckComputeInstanceAccessConfig(instance *compute.Instance) resourc } } -func testAccCheckComputeInstanceAccessConfigHasNatIP(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceAccessConfigHasNatIP(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - for _, c := range i.AccessConfigs { - if c.NatIP == "" { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNic := range nics { + i, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + acs, _ := i["accessConfigs"].([]interface{}) + for _, rawAC := range acs { + c, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + if natIP, _ := c["natIP"].(string); natIP == "" { return fmt.Errorf("no NAT IP") } } @@ -5639,11 +5766,21 @@ func testAccCheckComputeInstanceAccessConfigHasNatIP(instance *compute.Instance) } } -func testAccCheckComputeInstanceIpv6AccessConfigHasExternalIPv6(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceIpv6AccessConfigHasExternalIPv6(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - for _, c := range i.Ipv6AccessConfigs { - if c.ExternalIpv6 == "" { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNic := range nics { + i, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + acs, _ := i["ipv6AccessConfigs"].([]interface{}) + for _, rawAC := range acs { + c, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + if extIPv6, _ := c["externalIpv6"].(string); extIPv6 == "" { return fmt.Errorf("no External IPv6") } } @@ -5653,10 +5790,15 @@ func testAccCheckComputeInstanceIpv6AccessConfigHasExternalIPv6(instance *comput } } -func testAccCheckComputeInstanceIpv6AccessConfigHasInternalIPv6(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceIpv6AccessConfigHasInternalIPv6(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - if i.Ipv6Address == "" { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNic := range nics { + i, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + if ipv6Addr, _ := i["ipv6Address"].(string); ipv6Addr == "" { return fmt.Errorf("no internal IPv6 address") } } @@ -5665,11 +5807,21 @@ func testAccCheckComputeInstanceIpv6AccessConfigHasInternalIPv6(instance *comput } } -func testAccCheckComputeInstanceAccessConfigHasPTR(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceAccessConfigHasPTR(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - for _, c := range i.AccessConfigs { - if c.PublicPtrDomainName == "" { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNic := range nics { + i, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + acs, _ := i["accessConfigs"].([]interface{}) + for _, rawAC := range acs { + c, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + if ptr, _ := c["publicPtrDomainName"].(string); ptr == "" { return fmt.Errorf("no PTR Record") } } @@ -5679,66 +5831,82 @@ func testAccCheckComputeInstanceAccessConfigHasPTR(instance *compute.Instance) r } } -func testAccCheckComputeResourcePolicy(instance *compute.Instance, scheduleName string, resourcePolicyCountWant int) resource.TestCheckFunc { +func testAccCheckComputeResourcePolicy(instance *map[string]interface{}, scheduleName string, resourcePolicyCountWant int) resource.TestCheckFunc { return func(s *terraform.State) error { - resourcePoliciesCountHave := len(instance.ResourcePolicies) + policies, _ := (*instance)["resourcePolicies"].([]interface{}) + resourcePoliciesCountHave := len(policies) if resourcePoliciesCountHave != resourcePolicyCountWant { return fmt.Errorf("number of resource polices does not match: have: %d; want: %d", resourcePoliciesCountHave, resourcePolicyCountWant) } - if resourcePoliciesCountHave == 1 && !strings.Contains(instance.ResourcePolicies[0], scheduleName) { - return fmt.Errorf("got the wrong schedule: have: %s; want: %s", instance.ResourcePolicies[0], scheduleName) + if resourcePoliciesCountHave == 1 { + first, _ := policies[0].(string) + if !strings.Contains(first, scheduleName) { + return fmt.Errorf("got the wrong schedule: have: %s; want: %s", first, scheduleName) + } } return nil } } -func testAccCheckComputeInstanceMaxRunDuration(instance *compute.Instance, instanceMaxRunDurationWant compute.Duration) resource.TestCheckFunc { +func testAccCheckComputeInstanceMaxRunDuration(instance *map[string]interface{}, instanceMaxRunDurationWant map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance == nil { + if instance == nil || *instance == nil { return fmt.Errorf("instance is nil") } - if instance.Scheduling == nil { + scheduling, ok := (*instance)["scheduling"].(map[string]interface{}) + if !ok { return fmt.Errorf("no scheduling") } + mrd, ok := scheduling["maxRunDuration"].(map[string]interface{}) + if !ok { + return fmt.Errorf("no maxRunDuration") + } - if !reflect.DeepEqual(*instance.Scheduling.MaxRunDuration, instanceMaxRunDurationWant) { - return fmt.Errorf("got the wrong instance max run duration action: have: %#v; want: %#v", instance.Scheduling.MaxRunDuration, instanceMaxRunDurationWant) + if !reflect.DeepEqual(mrd, instanceMaxRunDurationWant) { + return fmt.Errorf("got the wrong instance max run duration action: have: %#v; want: %#v", mrd, instanceMaxRunDurationWant) } return nil } } -func testAccCheckComputeInstanceHasAvailabilityDomain(instance *compute.Instance, availabilityDomain int64) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasAvailabilityDomain(instance *map[string]interface{}, availabilityDomain int64) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance == nil { + if instance == nil || *instance == nil { return fmt.Errorf("instance is nil") } - if instance.Scheduling == nil { + scheduling, ok := (*instance)["scheduling"].(map[string]interface{}) + if !ok { return fmt.Errorf("no scheduling") } - if instance.Scheduling.AvailabilityDomain != availabilityDomain { - return fmt.Errorf("got the wrong availability domain: have %d; want %d", instance.Scheduling.AvailabilityDomain, availabilityDomain) + got, _ := scheduling["availabilityDomain"].(float64) + if int64(got) != availabilityDomain { + return fmt.Errorf("got the wrong availability domain: have %d; want %d", int64(got), availabilityDomain) } return nil } } -func testAccCheckComputeInstanceLocalSsdRecoveryTimeout(instance *compute.Instance, instanceLocalSsdRecoveryTiemoutWant compute.Duration) resource.TestCheckFunc { +func testAccCheckComputeInstanceLocalSsdRecoveryTimeout(instance *map[string]interface{}, instanceLocalSsdRecoveryTiemoutWant map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance == nil { + if instance == nil || *instance == nil { return fmt.Errorf("instance is nil") } - if instance.Scheduling == nil { + scheduling, ok := (*instance)["scheduling"].(map[string]interface{}) + if !ok { return fmt.Errorf("no scheduling") } + got, ok := scheduling["localSsdRecoveryTimeout"].(map[string]interface{}) + if !ok { + return fmt.Errorf("no localSsdRecoveryTimeout") + } - if !reflect.DeepEqual(*instance.Scheduling.LocalSsdRecoveryTimeout, instanceLocalSsdRecoveryTiemoutWant) { - return fmt.Errorf("got the wrong instance local ssd recovery timeout action: have: %#v; want: %#v", instance.Scheduling.LocalSsdRecoveryTimeout, instanceLocalSsdRecoveryTiemoutWant) + if !reflect.DeepEqual(got, instanceLocalSsdRecoveryTiemoutWant) { + return fmt.Errorf("got the wrong instance local ssd recovery timeout action: have: %#v; want: %#v", got, instanceLocalSsdRecoveryTiemoutWant) } return nil @@ -5746,25 +5914,23 @@ func testAccCheckComputeInstanceLocalSsdRecoveryTimeout(instance *compute.Instan } {{ if ne $.TargetVersionName `ga` -}} -func testAccCheckComputeInstancePartnerMetadata(instance *compute.Instance, expectedPartnerMetadata map[string]compute.StructuredEntries) resource.TestCheckFunc { +func testAccCheckComputeInstancePartnerMetadata(instance *map[string]interface{}, expectedPartnerMetadata map[string]map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance == nil { + if instance == nil || *instance == nil { return fmt.Errorf("instance is nil") } - if instance.PartnerMetadata == nil { + partnerMetadata, ok := (*instance)["partnerMetadata"].(map[string]interface{}) + if !ok { return fmt.Errorf("no partner metadata") } expectedPartnerMetadataMap := make(map[string]interface{}) acutalPartnerMetadataMap := make(map[string]interface{}) - for key, value := range instance.PartnerMetadata { - var jsonMap map[string]interface{} - json.Unmarshal(value.Entries, jsonMap) - acutalPartnerMetadataMap[key] = jsonMap + for key, value := range partnerMetadata { + entry, _ := value.(map[string]interface{}) + acutalPartnerMetadataMap[key] = entry["entries"] } for key, value := range expectedPartnerMetadata { - var jsonMap map[string]interface{} - json.Unmarshal(value.Entries, jsonMap) - expectedPartnerMetadataMap[key] = jsonMap + expectedPartnerMetadataMap[key] = value["entries"] } if !reflect.DeepEqual(acutalPartnerMetadataMap, expectedPartnerMetadataMap) { return fmt.Errorf("got the wrong instance partne metadata action: have: %+v; want: %+v", acutalPartnerMetadataMap, expectedPartnerMetadataMap) @@ -5775,31 +5941,41 @@ func testAccCheckComputeInstancePartnerMetadata(instance *compute.Instance, expe } {{- end }} -func testAccCheckComputeInstanceTerminationAction(instance *compute.Instance, instanceTerminationActionWant string) resource.TestCheckFunc { +func testAccCheckComputeInstanceTerminationAction(instance *map[string]interface{}, instanceTerminationActionWant string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance == nil { + if instance == nil || *instance == nil { return fmt.Errorf("instance is nil") } - if instance.Scheduling == nil { + scheduling, ok := (*instance)["scheduling"].(map[string]interface{}) + if !ok { return fmt.Errorf("no scheduling") } - if instance.Scheduling.InstanceTerminationAction != instanceTerminationActionWant { - return fmt.Errorf("got the wrong instance termniation action: have: %s; want: %s", instance.Scheduling.InstanceTerminationAction, instanceTerminationActionWant) + got, _ := scheduling["instanceTerminationAction"].(string) + if got != instanceTerminationActionWant { + return fmt.Errorf("got the wrong instance termniation action: have: %s; want: %s", got, instanceTerminationActionWant) } return nil } } -func testAccCheckComputeInstanceDisk(instance *compute.Instance, source string, delete bool, boot bool) resource.TestCheckFunc { +func testAccCheckComputeInstanceDisk(instance *map[string]interface{}, source string, delete bool, boot bool) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Disks == nil { + disks, ok := (*instance)["disks"].([]interface{}) + if !ok { return fmt.Errorf("no disks") } - for _, disk := range instance.Disks { - if strings.HasSuffix(disk.Source, "/"+source) && disk.AutoDelete == delete && disk.Boot == boot { + for _, raw := range disks { + disk, ok := raw.(map[string]interface{}) + if !ok { + continue + } + diskSource, _ := disk["source"].(string) + autoDelete, _ := disk["autoDelete"].(bool) + diskBoot, _ := disk["boot"].(bool) + if strings.HasSuffix(diskSource, "/"+source) && autoDelete == delete && diskBoot == boot { return nil } } @@ -5808,14 +5984,15 @@ func testAccCheckComputeInstanceDisk(instance *compute.Instance, source string, } } -func testAccCheckComputeInstanceHasInstanceId(instance *compute.Instance, n string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasInstanceId(instance *map[string]interface{}, n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } - remote := fmt.Sprintf("%d", instance.Id) + id, _ := (*instance)["id"].(string) + remote := id local := rs.Primary.Attributes["instance_id"] if remote != local { @@ -5827,17 +6004,22 @@ func testAccCheckComputeInstanceHasInstanceId(instance *compute.Instance, n stri } } -func testAccCheckComputeInstanceBootDisk(instance *compute.Instance, source string) resource.TestCheckFunc { +func testAccCheckComputeInstanceBootDisk(instance *map[string]interface{}, source string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Disks == nil { + disks, ok := (*instance)["disks"].([]interface{}) + if !ok { return fmt.Errorf("no disks") } - for _, disk := range instance.Disks { - if disk.Boot == true { - if strings.HasSuffix(disk.Source, source) { - return nil - } + for _, raw := range disks { + disk, ok := raw.(map[string]interface{}) + if !ok { + continue + } + diskBoot, _ := disk["boot"].(bool) + diskSource, _ := disk["source"].(string) + if diskBoot && strings.HasSuffix(diskSource, source) { + return nil } } @@ -5850,11 +6032,19 @@ func testAccCheckComputeInstanceBootDiskType(t *testing.T, instanceName string, config := acctest.GoogleProviderConfig(t) // boot disk is named the same as the Instance - disk, err := tpgcompute.NewClient(config, config.UserAgent).Disks.Get(config.Project, "us-central1-a", instanceName).Do() + url := fmt.Sprintf("%sprojects/%s/zones/%s/disks/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, "us-central1-a", instanceName) + disk, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if strings.Contains(disk.Type, diskType) { + diskTypeStr, _ := disk["type"].(string) + if strings.Contains(diskTypeStr, diskType) { return nil } @@ -5862,26 +6052,34 @@ func testAccCheckComputeInstanceBootDiskType(t *testing.T, instanceName string, } } -func testAccCheckComputeInstanceScratchDisk(instance *compute.Instance, interfaces []map[string]string) resource.TestCheckFunc { +func testAccCheckComputeInstanceScratchDisk(instance *map[string]interface{}, interfaces []map[string]string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Disks == nil { + disks, ok := (*instance)["disks"].([]interface{}) + if !ok { return fmt.Errorf("no disks") } i := 0 - for _, disk := range instance.Disks { - if disk.Type == "SCRATCH" { + for _, raw := range disks { + disk, ok := raw.(map[string]interface{}) + if !ok { + continue + } + diskType, _ := disk["type"].(string) + if diskType == "SCRATCH" { if i >= len(interfaces) { return fmt.Errorf("Expected %d scratch disks, found more", len(interfaces)) } - if disk.Interface != interfaces[i]["interface"] { + diskInterface, _ := disk["interface"].(string) + if diskInterface != interfaces[i]["interface"] { return fmt.Errorf("Mismatched interface on scratch disk #%d, expected: %q, found: %q", - i, interfaces[i], disk.Interface) + i, interfaces[i], diskInterface) } if deviceName, ok := interfaces[i]["deviceName"]; ok { - if disk.DeviceName != deviceName { + diskDeviceName, _ := disk["deviceName"].(string) + if diskDeviceName != deviceName { return fmt.Errorf("Mismatched device name on scratch disk #%d, expected: %q, found: %q", - i, deviceName, disk.DeviceName) + i, deviceName, diskDeviceName) } } @@ -5897,31 +6095,43 @@ func testAccCheckComputeInstanceScratchDisk(instance *compute.Instance, interfac } } -func testAccCheckComputeInstanceDiskEncryptionKey(n string, instance *compute.Instance, bootDiskEncryptionKey string, diskNameToEncryptionKey map[string]*compute.CustomerEncryptionKey) resource.TestCheckFunc { +func testAccCheckComputeInstanceDiskEncryptionKey(n string, instance *map[string]interface{}, bootDiskEncryptionKey string, diskNameToEncryptionKey map[string]map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } - for i, disk := range instance.Disks { - if disk.Boot { + disks, _ := (*instance)["disks"].([]interface{}) + for i, raw := range disks { + disk, ok := raw.(map[string]interface{}) + if !ok { + continue + } + boot, _ := disk["boot"].(bool) + source, _ := disk["source"].(string) + diskKey, _ := disk["diskEncryptionKey"].(map[string]interface{}) + if boot { attr := rs.Primary.Attributes["boot_disk.0.disk_encryption_key_sha256"] if attr != bootDiskEncryptionKey { return fmt.Errorf("Boot disk has wrong encryption key in state.\nExpected: %s\nActual: %s", bootDiskEncryptionKey, attr) } - if disk.DiskEncryptionKey == nil && attr != "" { + if diskKey == nil && attr != "" { return fmt.Errorf("Disk %d has mismatched encryption key.\nTF State: %+v\nGCP State: ", i, attr) } - if disk.DiskEncryptionKey != nil && attr != disk.DiskEncryptionKey.Sha256 { - return fmt.Errorf("Disk %d has mismatched encryption key.\nTF State: %+v\nGCP State: %+v", - i, attr, disk.DiskEncryptionKey.Sha256) + if diskKey != nil { + sha256, _ := diskKey["sha256"].(string) + if attr != sha256 { + return fmt.Errorf("Disk %d has mismatched encryption key.\nTF State: %+v\nGCP State: %+v", + i, attr, sha256) + } } } else { - if disk.DiskEncryptionKey != nil { - expectedKey := diskNameToEncryptionKey[tpgresource.GetResourceNameFromSelfLink(disk.Source)].Sha256 - if disk.DiskEncryptionKey.Sha256 != expectedKey { - return fmt.Errorf("Disk %d has unexpected encryption key in GCP.\nExpected: %s\nActual: %s", i, expectedKey, disk.DiskEncryptionKey.Sha256) + if diskKey != nil { + expectedKey, _ := diskNameToEncryptionKey[tpgresource.GetResourceNameFromSelfLink(source)]["sha256"].(string) + sha256, _ := diskKey["sha256"].(string) + if sha256 != expectedKey { + return fmt.Errorf("Disk %d has unexpected encryption key in GCP.\nExpected: %s\nActual: %s", i, expectedKey, sha256) } } } @@ -5935,7 +6145,7 @@ func testAccCheckComputeInstanceDiskEncryptionKey(n string, instance *compute.In diskName := tpgresource.GetResourceNameFromSelfLink(rs.Primary.Attributes[fmt.Sprintf("attached_disk.%d.source", i)]) encryptionKey := rs.Primary.Attributes[fmt.Sprintf("attached_disk.%d.disk_encryption_key_sha256", i)] if key, ok := diskNameToEncryptionKey[diskName]; ok { - expectedEncryptionKey := key.Sha256 + expectedEncryptionKey, _ := key["sha256"].(string) if encryptionKey != expectedEncryptionKey { return fmt.Errorf("Attached disk %d has unexpected encryption key in state.\nExpected: %s\nActual: %s", i, expectedEncryptionKey, encryptionKey) } @@ -5945,28 +6155,37 @@ func testAccCheckComputeInstanceDiskEncryptionKey(n string, instance *compute.In } } -func testAccCheckComputeInstanceDiskKmsEncryptionKey(n string, instance *compute.Instance, bootDiskEncryptionKey string, diskNameToEncryptionKey map[string]*compute.CustomerEncryptionKey) resource.TestCheckFunc { +func testAccCheckComputeInstanceDiskKmsEncryptionKey(n string, instance *map[string]interface{}, bootDiskEncryptionKey string, diskNameToEncryptionKey map[string]map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } - for i, disk := range instance.Disks { - if disk.Boot { + disks, _ := (*instance)["disks"].([]interface{}) + for i, raw := range disks { + disk, ok := raw.(map[string]interface{}) + if !ok { + continue + } + boot, _ := disk["boot"].(bool) + source, _ := disk["source"].(string) + diskKey, _ := disk["diskEncryptionKey"].(map[string]interface{}) + if boot { attr := rs.Primary.Attributes["boot_disk.0.kms_key_self_link"] if attr != bootDiskEncryptionKey { return fmt.Errorf("Boot disk has wrong encryption key in state.\nExpected: %s\nActual: %s", bootDiskEncryptionKey, attr) } - if disk.DiskEncryptionKey == nil && attr != "" { + if diskKey == nil && attr != "" { return fmt.Errorf("Disk %d has mismatched encryption key.\nTF State: %+v\nGCP State: ", i, attr) } } else { - if disk.DiskEncryptionKey != nil { - expectedKey := diskNameToEncryptionKey[tpgresource.GetResourceNameFromSelfLink(disk.Source)].KmsKeyName + if diskKey != nil { + expectedKey, _ := diskNameToEncryptionKey[tpgresource.GetResourceNameFromSelfLink(source)]["kmsKeyName"].(string) + kmsKeyName, _ := diskKey["kmsKeyName"].(string) // The response for crypto keys often includes the version of the key which needs to be removed // format: projects//locations//keyRings//cryptoKeys//cryptoKeyVersions/1 - actualKey := strings.Split(disk.DiskEncryptionKey.KmsKeyName, "/cryptoKeyVersions")[0] + actualKey := strings.Split(kmsKeyName, "/cryptoKeyVersions")[0] if actualKey != expectedKey { return fmt.Errorf("Disk %d has unexpected encryption key in GCP.\nExpected: %s\nActual: %s", i, expectedKey, actualKey) } @@ -5982,7 +6201,7 @@ func testAccCheckComputeInstanceDiskKmsEncryptionKey(n string, instance *compute diskName := tpgresource.GetResourceNameFromSelfLink(rs.Primary.Attributes[fmt.Sprintf("attached_disk.%d.source", i)]) kmsKeyName := rs.Primary.Attributes[fmt.Sprintf("attached_disk.%d.kms_key_self_link", i)] if key, ok := diskNameToEncryptionKey[diskName]; ok { - expectedEncryptionKey := key.KmsKeyName + expectedEncryptionKey, _ := key["kmsKeyName"].(string) if kmsKeyName != expectedEncryptionKey { return fmt.Errorf("Attached disk %d has unexpected encryption key in state.\nExpected: %s\nActual: %s", i, expectedEncryptionKey, kmsKeyName) } @@ -5992,13 +6211,16 @@ func testAccCheckComputeInstanceDiskKmsEncryptionKey(n string, instance *compute } } -func testAccCheckComputeInstanceTag(instance *compute.Instance, n string) resource.TestCheckFunc { +func testAccCheckComputeInstanceTag(instance *map[string]interface{}, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Tags == nil { + tags, ok := (*instance)["tags"].(map[string]interface{}) + if !ok { return fmt.Errorf("no tags") } - for _, k := range instance.Tags.Items { + items, _ := tags["items"].([]interface{}) + for _, raw := range items { + k, _ := raw.(string) if k == n { return nil } @@ -6008,37 +6230,42 @@ func testAccCheckComputeInstanceTag(instance *compute.Instance, n string) resour } } -func testAccCheckComputeInstanceLabel(instance *compute.Instance, key string, value string) resource.TestCheckFunc { +func testAccCheckComputeInstanceLabel(instance *map[string]interface{}, key string, value string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Labels == nil { - return fmt.Errorf("no labels found on instance %s", instance.Name) + name, _ := (*instance)["name"].(string) + labels, ok := (*instance)["labels"].(map[string]interface{}) + if !ok { + return fmt.Errorf("no labels found on instance %s", name) } - v, ok := instance.Labels[key] + v, ok := labels[key] if !ok { - return fmt.Errorf("No label found with key %s on instance %s", key, instance.Name) + return fmt.Errorf("No label found with key %s on instance %s", key, name) } - if v != value { - return fmt.Errorf("Expected value '%s' but found value '%s' for label '%s' on instance %s", value, v, key, instance.Name) + vStr, _ := v.(string) + if vStr != value { + return fmt.Errorf("Expected value '%s' but found value '%s' for label '%s' on instance %s", value, vStr, key, name) } return nil } } -func testAccCheckComputeInstanceAttributionLabel(instance *compute.Instance, present bool) resource.TestCheckFunc { +func testAccCheckComputeInstanceAttributionLabel(instance *map[string]interface{}, present bool) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Labels == nil { + name, _ := (*instance)["name"].(string) + labels, ok := (*instance)["labels"].(map[string]interface{}) + if !ok { if present { - return fmt.Errorf("no labels found on instance %s", instance.Name) + return fmt.Errorf("no labels found on instance %s", name) } return nil } - _, ok := instance.Labels["goog-terraform-provisioned"] + _, ok = labels["goog-terraform-provisioned"] if ok { if !present { - return fmt.Errorf("Attribution label found on instance %s", instance.Name) + return fmt.Errorf("Attribution label found on instance %s", name) } } @@ -6046,14 +6273,18 @@ func testAccCheckComputeInstanceAttributionLabel(instance *compute.Instance, pre } } -func testAccCheckComputeInstanceServiceAccount(instance *compute.Instance, scope string) resource.TestCheckFunc { +func testAccCheckComputeInstanceServiceAccount(instance *map[string]interface{}, scope string) resource.TestCheckFunc { return func(s *terraform.State) error { - if count := len(instance.ServiceAccounts); count != 1 { + serviceAccounts, _ := (*instance)["serviceAccounts"].([]interface{}) + if count := len(serviceAccounts); count != 1 { return fmt.Errorf("Wrong number of ServiceAccounts: expected 1, got %d", count) } - for _, val := range instance.ServiceAccounts[0].Scopes { - if val == scope { + sa, _ := serviceAccounts[0].(map[string]interface{}) + scopes, _ := sa["scopes"].([]interface{}) + for _, val := range scopes { + valStr, _ := val.(string) + if valStr == scope { return nil } } @@ -6062,22 +6293,25 @@ func testAccCheckComputeInstanceServiceAccount(instance *compute.Instance, scope } } -func testAccCheckComputeInstanceNoServiceAccount(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceNoServiceAccount(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if count := len(instance.ServiceAccounts); count != 0 { + serviceAccounts, _ := (*instance)["serviceAccounts"].([]interface{}) + if count := len(serviceAccounts); count != 0 { return fmt.Errorf("Wrong number of ServiceAccounts: expected 0, got %d", count) } return nil } } -func testAccCheckComputeInstanceMatchServiceAccount(instance *compute.Instance, serviceAcctRegexp string) resource.TestCheckFunc { +func testAccCheckComputeInstanceMatchServiceAccount(instance *map[string]interface{}, serviceAcctRegexp string) resource.TestCheckFunc { return func(s *terraform.State) error { - if count := len(instance.ServiceAccounts); count != 1 { + serviceAccounts, _ := (*instance)["serviceAccounts"].([]interface{}) + if count := len(serviceAccounts); count != 1 { return fmt.Errorf("Wrong number of ServiceAccounts: expected 1, got %d", count) } - email := instance.ServiceAccounts[0].Email + sa, _ := serviceAccounts[0].(map[string]interface{}) + email, _ := sa["email"].(string) if !regexp.MustCompile(serviceAcctRegexp).MatchString(email) { return fmt.Errorf("ServiceAccount email didn't match:\"%s\", got \"%s\"", serviceAcctRegexp, email) } @@ -6086,21 +6320,24 @@ func testAccCheckComputeInstanceMatchServiceAccount(instance *compute.Instance, } } -func testAccCheckComputeInstanceScopes(instance *compute.Instance, scopeCount int) resource.TestCheckFunc { +func testAccCheckComputeInstanceScopes(instance *map[string]interface{}, scopeCount int) resource.TestCheckFunc { return func(s *terraform.State) error { + serviceAccounts, _ := (*instance)["serviceAccounts"].([]interface{}) - if count := len(instance.ServiceAccounts); count == 0 { + if count := len(serviceAccounts); count == 0 { if scopeCount == 0 { return nil } else { return fmt.Errorf("Scope count expected: %s, but got %s", fmt.Sprint(scopeCount), fmt.Sprint(count)) } } else { - if count := len(instance.ServiceAccounts); count != 1 { + if count := len(serviceAccounts); count != 1 { return fmt.Errorf("Wrong number of ServiceAccounts: expected 1, got %d", count) } - if scount := len(instance.ServiceAccounts[0].Scopes); scount == scopeCount { + sa, _ := serviceAccounts[0].(map[string]interface{}) + scopes, _ := sa["scopes"].([]interface{}) + if scount := len(scopes); scount == scopeCount { return nil } else { return fmt.Errorf("Scope count expected: %s, but got %s", fmt.Sprint(scopeCount), fmt.Sprint(scount)) @@ -6109,10 +6346,15 @@ func testAccCheckComputeInstanceScopes(instance *compute.Instance, scopeCount in } } -func testAccCheckComputeInstanceHasSubnet(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasSubnet(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - if i.Subnetwork == "" { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, raw := range nics { + i, ok := raw.(map[string]interface{}) + if !ok { + continue + } + if subnet, _ := i["subnetwork"].(string); subnet == "" { return fmt.Errorf("no subnet") } } @@ -6121,10 +6363,15 @@ func testAccCheckComputeInstanceHasSubnet(instance *compute.Instance) resource.T } } -func testAccCheckComputeInstanceHasAnyNetworkIP(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasAnyNetworkIP(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - if i.NetworkIP == "" { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, raw := range nics { + i, ok := raw.(map[string]interface{}) + if !ok { + continue + } + if networkIP, _ := i["networkIP"].(string); networkIP == "" { return fmt.Errorf("no network_ip") } } @@ -6133,11 +6380,17 @@ func testAccCheckComputeInstanceHasAnyNetworkIP(instance *compute.Instance) reso } } -func testAccCheckComputeInstanceHasNetworkIP(instance *compute.Instance, networkIP string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasNetworkIP(instance *map[string]interface{}, networkIP string) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instance.NetworkInterfaces { - if i.NetworkIP != networkIP { - return fmt.Errorf("Wrong network_ip found: expected %v, got %v", networkIP, i.NetworkIP) + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, raw := range nics { + i, ok := raw.(map[string]interface{}) + if !ok { + continue + } + got, _ := i["networkIP"].(string) + if got != networkIP { + return fmt.Errorf("Wrong network_ip found: expected %v, got %v", networkIP, got) } } @@ -6145,50 +6398,58 @@ func testAccCheckComputeInstanceHasNetworkIP(instance *compute.Instance, network } } -func testAccCheckComputeInstanceHasNetworkPerformanceConfig(instance *compute.Instance, bandwidthTier string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasNetworkPerformanceConfig(instance *map[string]interface{}, bandwidthTier string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.NetworkPerformanceConfig == nil { + npc, ok := (*instance)["networkPerformanceConfig"].(map[string]interface{}) + if !ok { return fmt.Errorf("Expected instance to have network performance config, but it was nil") } - if instance.NetworkPerformanceConfig.TotalEgressBandwidthTier != bandwidthTier { - return fmt.Errorf("Incorrect network_performance_config.total_egress_bandwidth_tier found: expected %v, got %v", bandwidthTier, instance.NetworkPerformanceConfig.TotalEgressBandwidthTier) + got, _ := npc["totalEgressBandwidthTier"].(string) + if got != bandwidthTier { + return fmt.Errorf("Incorrect network_performance_config.total_egress_bandwidth_tier found: expected %v, got %v", bandwidthTier, got) } return nil } } -func testAccCheckComputeInstanceHasMultiNic(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasMultiNic(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if len(instance.NetworkInterfaces) < 2 { - return fmt.Errorf("only saw %d nics", len(instance.NetworkInterfaces)) + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + if len(nics) < 2 { + return fmt.Errorf("only saw %d nics", len(nics)) } return nil } } -func testAccCheckComputeInstanceHasGuestAccelerator(instance *compute.Instance, acceleratorType string, acceleratorCount int64) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasGuestAccelerator(instance *map[string]interface{}, acceleratorType string, acceleratorCount int64) resource.TestCheckFunc { return func(s *terraform.State) error { - if len(instance.GuestAccelerators) != 1 { + accels, _ := (*instance)["guestAccelerators"].([]interface{}) + if len(accels) != 1 { return fmt.Errorf("Expected only one guest accelerator") } - if !strings.HasSuffix(instance.GuestAccelerators[0].AcceleratorType, acceleratorType) { - return fmt.Errorf("Wrong accelerator type: expected %v, got %v", acceleratorType, instance.GuestAccelerators[0].AcceleratorType) + first, _ := accels[0].(map[string]interface{}) + gotType, _ := first["acceleratorType"].(string) + if !strings.HasSuffix(gotType, acceleratorType) { + return fmt.Errorf("Wrong accelerator type: expected %v, got %v", acceleratorType, gotType) } - if instance.GuestAccelerators[0].AcceleratorCount != acceleratorCount { - return fmt.Errorf("Wrong accelerator acceleratorCount: expected %d, got %d", acceleratorCount, instance.GuestAccelerators[0].AcceleratorCount) + gotCount, _ := first["acceleratorCount"].(float64) + if int64(gotCount) != acceleratorCount { + return fmt.Errorf("Wrong accelerator acceleratorCount: expected %d, got %d", acceleratorCount, int64(gotCount)) } return nil } } -func testAccCheckComputeInstanceLacksGuestAccelerator(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceLacksGuestAccelerator(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if len(instance.GuestAccelerators) > 0 { + accels, _ := (*instance)["guestAccelerators"].([]interface{}) + if len(accels) > 0 { return fmt.Errorf("Expected no guest accelerators") } @@ -6196,20 +6457,27 @@ func testAccCheckComputeInstanceLacksGuestAccelerator(instance *compute.Instance } } -func testAccCheckComputeInstanceHasMinCpuPlatform(instance *compute.Instance, minCpuPlatform string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasMinCpuPlatform(instance *map[string]interface{}, minCpuPlatform string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.MinCpuPlatform != minCpuPlatform { - return fmt.Errorf("Wrong minimum CPU platform: expected %s, got %s", minCpuPlatform, instance.MinCpuPlatform) + got, _ := (*instance)["minCpuPlatform"].(string) + if got != minCpuPlatform { + return fmt.Errorf("Wrong minimum CPU platform: expected %s, got %s", minCpuPlatform, got) } return nil } } -func testAccCheckComputeInstanceHasNetworkAttachment(instance *compute.Instance, networkAttachmentName string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasNetworkAttachment(instance *map[string]interface{}, networkAttachmentName string) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, networkInterface := range instance.NetworkInterfaces { - if networkInterface.NetworkAttachment != "" && networkInterface.NetworkAttachment == networkAttachmentName { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, raw := range nics { + ni, ok := raw.(map[string]interface{}) + if !ok { + continue + } + na, _ := ni["networkAttachment"].(string) + if na != "" && na == networkAttachmentName { return nil } } @@ -6217,9 +6485,10 @@ func testAccCheckComputeInstanceHasNetworkAttachment(instance *compute.Instance, } } -func testAccCheckComputeInstanceHasMachineType(instance *compute.Instance, machineType string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasMachineType(instance *map[string]interface{}, machineType string) resource.TestCheckFunc { return func(s *terraform.State) error { - instanceMachineType := tpgresource.GetResourceNameFromSelfLink(instance.MachineType) + mt, _ := (*instance)["machineType"].(string) + instanceMachineType := tpgresource.GetResourceNameFromSelfLink(mt) if instanceMachineType != machineType { return fmt.Errorf("Wrong machine type: expected %s, got %s", machineType, instanceMachineType) } @@ -6228,11 +6497,23 @@ func testAccCheckComputeInstanceHasMachineType(instance *compute.Instance, machi } } -func testAccCheckComputeInstanceHasAliasIpRange(instance *compute.Instance, subnetworkRangeName, iPCidrRange string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasAliasIpRange(instance *map[string]interface{}, subnetworkRangeName, iPCidrRange string) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, networkInterface := range instance.NetworkInterfaces { - for _, aliasIpRange := range networkInterface.AliasIpRanges { - if aliasIpRange.SubnetworkRangeName == subnetworkRangeName && (aliasIpRange.IpCidrRange == iPCidrRange || tpgcompute.IpCidrRangeDiffSuppress("ip_cidr_range", aliasIpRange.IpCidrRange, iPCidrRange, nil)) { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNi := range nics { + ni, ok := rawNi.(map[string]interface{}) + if !ok { + continue + } + ranges, _ := ni["aliasIpRanges"].([]interface{}) + for _, rawRange := range ranges { + aliasIpRange, ok := rawRange.(map[string]interface{}) + if !ok { + continue + } + name, _ := aliasIpRange["subnetworkRangeName"].(string) + cidr, _ := aliasIpRange["ipCidrRange"].(string) + if name == subnetworkRangeName && (cidr == iPCidrRange || tpgcompute.IpCidrRangeDiffSuppress("ip_cidr_range", cidr, iPCidrRange, nil)) { return nil } } @@ -6242,6 +6523,51 @@ func testAccCheckComputeInstanceHasAliasIpRange(instance *compute.Instance, subn } } +{{ if ne $.TargetVersionName `ga` -}} +func testAccCheckComputeInstanceHasAliasIpv6Range(instance *map[string]interface{}, iPCidrRange string) resource.TestCheckFunc { + return func(s *terraform.State) error { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNi := range nics { + ni, ok := rawNi.(map[string]interface{}) + if !ok { + continue + } + ranges, _ := ni["aliasIpv6Ranges"].([]interface{}) + for _, rawRange := range ranges { + aliasIpRange, ok := rawRange.(map[string]interface{}) + if !ok { + continue + } + cidr, _ := aliasIpRange["ipCidrRange"].(string) + if cidr == iPCidrRange || tpgcompute.IpCidrRangeDiffSuppress("ip_cidr_range", cidr, iPCidrRange, nil) { + return nil + } + } + } + + return fmt.Errorf("Alias ipv6 range with cidr %s not present", iPCidrRange) + } +} + +func testAccCheckComputeInstanceNoAliasIpv6Range(instance *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNi := range nics { + ni, ok := rawNi.(map[string]interface{}) + if !ok { + continue + } + ranges, _ := ni["aliasIpv6Ranges"].([]interface{}) + if len(ranges) > 0 { + return fmt.Errorf("Alias ipv6 range still present on instance") + } + + } + return nil + } +} +{{- end }} + func testAccCheckComputeInstanceHasAssignedNatIP(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "google_compute_instance" { @@ -6255,37 +6581,46 @@ func testAccCheckComputeInstanceHasAssignedNatIP(s *terraform.State) error { return nil } -func testAccCheckComputeInstanceHasConfiguredDeletionProtection(instance *compute.Instance, configuredDeletionProtection bool) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasConfiguredDeletionProtection(instance *map[string]interface{}, configuredDeletionProtection bool) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.DeletionProtection != configuredDeletionProtection { - return fmt.Errorf("Wrong deletion protection flag: expected %t, got %t", configuredDeletionProtection, instance.DeletionProtection) + got, _ := (*instance)["deletionProtection"].(bool) + if got != configuredDeletionProtection { + return fmt.Errorf("Wrong deletion protection flag: expected %t, got %t", configuredDeletionProtection, got) } return nil } } -func testAccCheckComputeInstanceHasReservationAffinity(instance *compute.Instance, reservationType string, specificReservationNames ...string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasReservationAffinity(instance *map[string]interface{}, reservationType string, specificReservationNames ...string) resource.TestCheckFunc { if len(specificReservationNames) > 1 { panic("too many specificReservationNames provided in test") } return func(*terraform.State) error { - if instance.ReservationAffinity == nil { + ra, ok := (*instance)["reservationAffinity"].(map[string]interface{}) + if !ok { return fmt.Errorf("expected instance to have reservation affinity, but it was nil") } - if instance.ReservationAffinity.ConsumeReservationType != reservationType { - return fmt.Errorf("Wrong reservationAffinity consumeReservationType: expected %s, got, %s", reservationType, instance.ReservationAffinity.ConsumeReservationType) + gotType, _ := ra["consumeReservationType"].(string) + if gotType != reservationType { + return fmt.Errorf("Wrong reservationAffinity consumeReservationType: expected %s, got, %s", reservationType, gotType) } if len(specificReservationNames) > 0 { const reservationNameKey = "compute.googleapis.com/reservation-name" - if instance.ReservationAffinity.Key != reservationNameKey { - return fmt.Errorf("Wrong reservationAffinity key: expected %s, got, %s", reservationNameKey, instance.ReservationAffinity.Key) + gotKey, _ := ra["key"].(string) + if gotKey != reservationNameKey { + return fmt.Errorf("Wrong reservationAffinity key: expected %s, got, %s", reservationNameKey, gotKey) } - if len(instance.ReservationAffinity.Values) != 1 || instance.ReservationAffinity.Values[0] != specificReservationNames[0] { - return fmt.Errorf("Wrong reservationAffinity values: expected %s, got, %s", specificReservationNames, instance.ReservationAffinity.Values) + values, _ := ra["values"].([]interface{}) + if len(values) != 1 { + return fmt.Errorf("Wrong reservationAffinity values: expected %s, got, %v", specificReservationNames, values) + } + firstVal, _ := values[0].(string) + if firstVal != specificReservationNames[0] { + return fmt.Errorf("Wrong reservationAffinity values: expected %s, got, %v", specificReservationNames, values) } } @@ -6293,41 +6628,48 @@ func testAccCheckComputeInstanceHasReservationAffinity(instance *compute.Instanc } } -func testAccCheckComputeInstanceHasShieldedVmConfig(instance *compute.Instance, enableSecureBoot bool, enableVtpm bool, enableIntegrityMonitoring bool) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasShieldedVmConfig(instance *map[string]interface{}, enableSecureBoot bool, enableVtpm bool, enableIntegrityMonitoring bool) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.ShieldedInstanceConfig.EnableSecureBoot != enableSecureBoot { - return fmt.Errorf("Wrong shieldedVmConfig enableSecureBoot: expected %t, got, %t", enableSecureBoot, instance.ShieldedInstanceConfig.EnableSecureBoot) + sic, _ := (*instance)["shieldedInstanceConfig"].(map[string]interface{}) + gotSecureBoot, _ := sic["enableSecureBoot"].(bool) + if gotSecureBoot != enableSecureBoot { + return fmt.Errorf("Wrong shieldedVmConfig enableSecureBoot: expected %t, got, %t", enableSecureBoot, gotSecureBoot) } - if instance.ShieldedInstanceConfig.EnableVtpm != enableVtpm { - return fmt.Errorf("Wrong shieldedVmConfig enableVtpm: expected %t, got, %t", enableVtpm, instance.ShieldedInstanceConfig.EnableVtpm) + gotVtpm, _ := sic["enableVtpm"].(bool) + if gotVtpm != enableVtpm { + return fmt.Errorf("Wrong shieldedVmConfig enableVtpm: expected %t, got, %t", enableVtpm, gotVtpm) } - if instance.ShieldedInstanceConfig.EnableIntegrityMonitoring != enableIntegrityMonitoring { - return fmt.Errorf("Wrong shieldedVmConfig enableIntegrityMonitoring: expected %t, got, %t", enableIntegrityMonitoring, instance.ShieldedInstanceConfig.EnableIntegrityMonitoring) + gotIM, _ := sic["enableIntegrityMonitoring"].(bool) + if gotIM != enableIntegrityMonitoring { + return fmt.Errorf("Wrong shieldedVmConfig enableIntegrityMonitoring: expected %t, got, %t", enableIntegrityMonitoring, gotIM) } return nil } } -func testAccCheckComputeInstanceHasConfidentialInstanceConfig(instance *compute.Instance, EnableConfidentialCompute bool, ConfidentialInstanceType string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasConfidentialInstanceConfig(instance *map[string]interface{}, EnableConfidentialCompute bool, ConfidentialInstanceType string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.ConfidentialInstanceConfig.EnableConfidentialCompute != EnableConfidentialCompute { - return fmt.Errorf("Wrong ConfidentialInstanceConfig EnableConfidentialCompute: expected %t, got, %t", EnableConfidentialCompute, instance.ConfidentialInstanceConfig.EnableConfidentialCompute) + cic, _ := (*instance)["confidentialInstanceConfig"].(map[string]interface{}) + gotEnable, _ := cic["enableConfidentialCompute"].(bool) + if gotEnable != EnableConfidentialCompute { + return fmt.Errorf("Wrong ConfidentialInstanceConfig EnableConfidentialCompute: expected %t, got, %t", EnableConfidentialCompute, gotEnable) } - if instance.ConfidentialInstanceConfig.ConfidentialInstanceType != ConfidentialInstanceType { - return fmt.Errorf("Wrong ConfidentialInstanceConfig ConfidentialInstanceType: expected %s, got, %s", ConfidentialInstanceType, instance.ConfidentialInstanceConfig.ConfidentialInstanceType) + gotType, _ := cic["confidentialInstanceType"].(string) + if gotType != ConfidentialInstanceType { + return fmt.Errorf("Wrong ConfidentialInstanceConfig ConfidentialInstanceType: expected %s, got, %s", ConfidentialInstanceType, gotType) } return nil } } -func testAccCheckComputeInstanceLacksShieldedVmConfig(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceLacksShieldedVmConfig(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.ShieldedInstanceConfig != nil { + if _, ok := (*instance)["shieldedInstanceConfig"].(map[string]interface{}); ok { return fmt.Errorf("Expected no shielded vm config") } @@ -6335,27 +6677,45 @@ func testAccCheckComputeInstanceLacksShieldedVmConfig(instance *compute.Instance } } -func testAccCheckComputeInstanceHasStatus(instance *compute.Instance, status string) resource.TestCheckFunc { +func testAccCheckComputeInstanceHasStatus(instance *map[string]interface{}, status string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instance.Status != status { - return fmt.Errorf("Instance has not status %s, status: %s", status, instance.Status) + got, _ := (*instance)["status"].(string) + if got != status { + return fmt.Errorf("Instance has not status %s, status: %s", status, got) } return nil } } {{ if ne $.TargetVersionName `ga` -}} -func testAccCheckComputeInstanceNicAccessConfigHasSecurityPolicy(instance *compute.Instance, securityPolicy string) resource.TestCheckFunc { +func testAccCheckComputeInstanceNicAccessConfigHasSecurityPolicy(instance *map[string]interface{}, securityPolicy string) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, networkInterface := range instance.NetworkInterfaces { - for _, accessConfig := range networkInterface.AccessConfigs { - if strings.Contains(accessConfig.SecurityPolicy, securityPolicy) { + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNi := range nics { + ni, ok := rawNi.(map[string]interface{}) + if !ok { + continue + } + acs, _ := ni["accessConfigs"].([]interface{}) + for _, rawAC := range acs { + ac, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + sp, _ := ac["securityPolicy"].(string) + if strings.Contains(sp, securityPolicy) { return nil } } - for _, accessConfigIpv6 := range networkInterface.Ipv6AccessConfigs { - if strings.Contains(accessConfigIpv6.SecurityPolicy, securityPolicy) { + ipv6ACs, _ := ni["ipv6AccessConfigs"].([]interface{}) + for _, rawAC := range ipv6ACs { + ac, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + sp, _ := ac["securityPolicy"].(string) + if strings.Contains(sp, securityPolicy) { return nil } } @@ -6365,19 +6725,33 @@ func testAccCheckComputeInstanceNicAccessConfigHasSecurityPolicy(instance *compu } } -func testAccCheckComputeInstanceNicAccessConfigHasNoSecurityPolicy(instance *compute.Instance) resource.TestCheckFunc { +func testAccCheckComputeInstanceNicAccessConfigHasNoSecurityPolicy(instance *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, networkInterface := range instance.NetworkInterfaces { - for _, accessConfig := range networkInterface.AccessConfigs { - if accessConfig.SecurityPolicy != "" { - return fmt.Errorf("Security Policy with name %s is present", accessConfig.SecurityPolicy) + nics, _ := (*instance)["networkInterfaces"].([]interface{}) + for _, rawNi := range nics { + ni, ok := rawNi.(map[string]interface{}) + if !ok { + continue + } + acs, _ := ni["accessConfigs"].([]interface{}) + for _, rawAC := range acs { + ac, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + if sp, _ := ac["securityPolicy"].(string); sp != "" { + return fmt.Errorf("Security Policy with name %s is present", sp) } - } - for _, accessConfigIpv6 := range networkInterface.Ipv6AccessConfigs { - if accessConfigIpv6.SecurityPolicy != "" { - return fmt.Errorf("Security Policy with name %s is present", accessConfigIpv6.SecurityPolicy) + ipv6ACs, _ := ni["ipv6AccessConfigs"].([]interface{}) + for _, rawAC := range ipv6ACs { + ac, ok := rawAC.(map[string]interface{}) + if !ok { + continue + } + if sp, _ := ac["securityPolicy"].(string); sp != "" { + return fmt.Errorf("Security Policy with name %s is present", sp) } } } @@ -7446,7 +7820,7 @@ resource "google_compute_instance" "foobar" { `, instance) } -func testAccComputeInstance_disks_encryption(bootEncryptionKey string, diskNameToEncryptionKey map[string]*compute.CustomerEncryptionKey, instance, suffix string) string { +func testAccComputeInstance_disks_encryption(bootEncryptionKey string, diskNameToEncryptionKey map[string]map[string]interface{}, instance, suffix string) string { diskNames := []string{} for k := range diskNameToEncryptionKey { diskNames = append(diskNames, k) @@ -7539,15 +7913,15 @@ resource "google_compute_instance" "foobar" { allow_stopping_for_update = true } -`, diskNames[0], diskNameToEncryptionKey[diskNames[0]].RawKey, - diskNames[1], diskNameToEncryptionKey[diskNames[1]].RawKey, - diskNames[2], diskNameToEncryptionKey[diskNames[2]].RawKey, +`, diskNames[0], diskNameToEncryptionKey[diskNames[0]]["rawKey"], + diskNames[1], diskNameToEncryptionKey[diskNames[1]]["rawKey"], + diskNames[2], diskNameToEncryptionKey[diskNames[2]]["rawKey"], "tf-testd-"+suffix, instance, bootEncryptionKey, - diskNameToEncryptionKey[diskNames[0]].RawKey, diskNameToEncryptionKey[diskNames[1]].RawKey, diskNameToEncryptionKey[diskNames[2]].RawKey) + diskNameToEncryptionKey[diskNames[0]]["rawKey"], diskNameToEncryptionKey[diskNames[1]]["rawKey"], diskNameToEncryptionKey[diskNames[2]]["rawKey"]) } -func testAccComputeInstance_disks_encryption_restart(bootEncryptionKey string, diskNameToEncryptionKey map[string]*compute.CustomerEncryptionKey, instance string) string { +func testAccComputeInstance_disks_encryption_restart(bootEncryptionKey string, diskNameToEncryptionKey map[string]map[string]interface{}, instance string) string { diskNames := []string{} for k := range diskNameToEncryptionKey { diskNames = append(diskNames, k) @@ -7596,12 +7970,12 @@ resource "google_compute_instance" "foobar" { allow_stopping_for_update = true } -`, diskNames[0], diskNameToEncryptionKey[diskNames[0]].RawKey, +`, diskNames[0], diskNameToEncryptionKey[diskNames[0]]["rawKey"], instance, bootEncryptionKey, - diskNameToEncryptionKey[diskNames[0]].RawKey) + diskNameToEncryptionKey[diskNames[0]]["rawKey"]) } -func testAccComputeInstance_disks_encryption_restartUpdate(bootEncryptionKey string, diskNameToEncryptionKey map[string]*compute.CustomerEncryptionKey, instance string) string { +func testAccComputeInstance_disks_encryption_restartUpdate(bootEncryptionKey string, diskNameToEncryptionKey map[string]map[string]interface{}, instance string) string { diskNames := []string{} for k := range diskNameToEncryptionKey { diskNames = append(diskNames, k) @@ -7650,12 +8024,12 @@ resource "google_compute_instance" "foobar" { allow_stopping_for_update = true } -`, diskNames[0], diskNameToEncryptionKey[diskNames[0]].RawKey, +`, diskNames[0], diskNameToEncryptionKey[diskNames[0]]["rawKey"], instance, bootEncryptionKey, - diskNameToEncryptionKey[diskNames[0]].RawKey) + diskNameToEncryptionKey[diskNames[0]]["rawKey"]) } -func testAccComputeInstance_disks_kms(bootEncryptionKey string, diskNameToEncryptionKey map[string]*compute.CustomerEncryptionKey, instance, suffix string) string { +func testAccComputeInstance_disks_kms(bootEncryptionKey string, diskNameToEncryptionKey map[string]map[string]interface{}, instance, suffix string) string { diskNames := []string{} for k := range diskNameToEncryptionKey { diskNames = append(diskNames, k) @@ -7745,12 +8119,12 @@ resource "google_compute_instance" "foobar" { foo = "bar" } } -`, diskNames[0], diskNameToEncryptionKey[diskNames[0]].KmsKeyName, - diskNames[1], diskNameToEncryptionKey[diskNames[1]].KmsKeyName, - diskNames[2], diskNameToEncryptionKey[diskNames[2]].KmsKeyName, +`, diskNames[0], diskNameToEncryptionKey[diskNames[0]]["kmsKeyName"], + diskNames[1], diskNameToEncryptionKey[diskNames[1]]["kmsKeyName"], + diskNames[2], diskNameToEncryptionKey[diskNames[2]]["kmsKeyName"], "tf-testd-"+suffix, instance, bootEncryptionKey, - diskNameToEncryptionKey[diskNames[0]].KmsKeyName, diskNameToEncryptionKey[diskNames[1]].KmsKeyName) + diskNameToEncryptionKey[diskNames[0]]["kmsKeyName"], diskNameToEncryptionKey[diskNames[1]]["kmsKeyName"]) } func testAccComputeInstance_instanceSchedule(instance, schedule string) string { @@ -9662,6 +10036,103 @@ resource "google_compute_instance" "foobar" { `, network, subnet, instance) } +{{ if ne $.TargetVersionName `ga` -}} +func testAccComputeInstance_aliasIpv6Range_noAlias(network, subnet, instance string) string { + return fmt.Sprintf(` +data "google_compute_image" "my_image" { + family = "debian-11" + project = "debian-cloud" +} + +resource "google_compute_network" "test-network" { + name = "%s" + auto_create_subnetworks = false + enable_ula_internal_ipv6 = true +} + +resource "google_compute_subnetwork" "test-subnetwork" { + name = "%s" + region = "us-central1" + network = google_compute_network.test-network.id + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } +} + +resource "google_compute_instance" "foobar" { + name = "%s" + machine_type = "e2-medium" + zone = "us-central1-a" + + boot_disk { + initialize_params { + image = data.google_compute_image.my_image.self_link + } + } + + network_interface { + subnetwork = google_compute_subnetwork.test-subnetwork.self_link + stack_type = "IPV6_ONLY" + } +} +`, network, subnet, instance) +} + +func testAccComputeInstance_aliasIpv6Range(network, subnet, instance string) string { + return fmt.Sprintf(` +data "google_compute_image" "my_image" { + family = "debian-11" + project = "debian-cloud" +} + +resource "google_compute_network" "test-network" { + name = "%s" + auto_create_subnetworks = false + enable_ula_internal_ipv6 = true +} + +resource "google_compute_subnetwork" "test-subnetwork" { + name = "%s" + region = "us-central1" + network = google_compute_network.test-network.id + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } +} + +resource "google_compute_instance" "foobar" { + name = "%s" + machine_type = "e2-medium" + zone = "us-central1-a" + + boot_disk { + initialize_params { + image = data.google_compute_image.my_image.self_link + } + } + + network_interface { + subnetwork = google_compute_subnetwork.test-subnetwork.self_link + stack_type = "IPV6_ONLY" + + alias_ipv6_range { + subnetwork_range_name = "v6-ula" + ip_cidr_range = "/96" + } + } +} +`, network, subnet, instance) +} +{{- end }} + func testAccComputeInstance_secondaryAliasIpRangeUpdate(network, subnet, instance string) string { return fmt.Sprintf(` data "google_compute_image" "my_image" { @@ -12771,7 +13242,7 @@ func TestAccComputeInstance_bootDisk_storagePoolSpecified(t *testing.T) { t.Parallel() instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) - storagePoolNameLong := acctest.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") + storagePoolNameLong := tpgcompute.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -12793,7 +13264,7 @@ func TestAccComputeInstance_bootDisk_storagePoolSpecified_nameOnly(t *testing.T) t.Parallel() instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) - acctest.BootstrapComputeStoragePool(t, "basic-2", "hyperdisk-balanced") + tpgcompute.BootstrapComputeStoragePool(t, "basic-2", "hyperdisk-balanced") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -13745,4 +14216,4 @@ resource "google_compute_instance" "foobar" { } `, context) } -{{- end }} \ No newline at end of file +{{- end }} diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_instant_snapshot_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_instant_snapshot_test.go similarity index 88% rename from mmv1/third_party/terraform/services/compute/resource_compute_instant_snapshot_test.go.tmpl rename to mmv1/third_party/terraform/services/compute/resource_compute_instant_snapshot_test.go index 30583d3bf191..c3e9e69086d9 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_instant_snapshot_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_instant_snapshot_test.go @@ -8,19 +8,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" - compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-provider-google/google/tpgresource" - - {{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" - {{- else }} - compute "google.golang.org/api/compute/v0.beta" - {{- end }} + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccComputeInstantSnapshot_basicFeatures(t *testing.T) { - var is compute.InstantSnapshot + var is map[string]interface{} context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), } @@ -41,7 +36,7 @@ func TestAccComputeInstantSnapshot_basicFeatures(t *testing.T) { } func TestAccComputeInstantSnapshot_labelsUpdate(t *testing.T) { - var is compute.InstantSnapshot + var is map[string]interface{} context_1 := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "label_key": "test-1", @@ -85,8 +80,7 @@ func TestAccComputeInstantSnapshot_labelsUpdate(t *testing.T) { }) } - -func testAccCheckComputeInstantSnapshotExists(t *testing.T, n, p string, is *compute.InstantSnapshot) resource.TestCheckFunc { +func testAccCheckComputeInstantSnapshotExists(t *testing.T, n, p string, is *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -101,17 +95,23 @@ func testAccCheckComputeInstantSnapshotExists(t *testing.T, n, p string, is *com zone := tpgresource.GetResourceNameFromSelfLink(rs.Primary.Attributes["zone"]) - found, err := compute_tpg.NewClient(config, config.UserAgent).InstantSnapshots.Get( - p, zone, rs.Primary.Attributes["name"]).Do() + url := fmt.Sprintf("%sprojects/%s/zones/%s/instantSnapshots/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), p, zone, rs.Primary.Attributes["name"]) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: p, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.Name != rs.Primary.Attributes["name"] { + if foundName, ok := found["name"].(string); !ok || foundName != rs.Primary.Attributes["name"] { return fmt.Errorf("Instant Snapshot not found") } - *is = *found + *is = found return nil } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_application_awareness_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_application_awareness_test.go.tmpl index fa2406ef7f8f..2c0d2e279410 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_application_awareness_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_application_awareness_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeInterconnect_computeInterconnectBasicTestExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_group_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_group_test.go index 0b6c23691860..b1118cef329f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_group_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_group_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeInterconnectAttachmentGroup_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_l2_enabled_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_l2_enabled_test.go index 735bf699e5d6..42b744c3e151 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_l2_enabled_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_attachment_l2_enabled_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_group_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_group_test.go index 89b7d56fcd60..f685f43f0274 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_group_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_group_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeInterconnectGroup_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_macsec_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_macsec_test.go index 8ff6c684c733..6ba973739287 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_macsec_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_interconnect_macsec_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_attachment_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_network_attachment_test.go index 3aa877e8b1c7..e3da86f02302 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_attachment_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_attachment_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeNetworkAttachment_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_sweeper.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_sweeper.go.tmpl index 03cf752b20d9..52d720490808 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_sweeper.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_sweeper.go.tmpl @@ -3,9 +3,11 @@ package compute import ( "context" + "fmt" "log" "github.com/hashicorp/terraform-provider-google/google/sweeper" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) @@ -30,7 +32,14 @@ func testSweepComputeNetworkEdgeSecurityService(region string) error { return err } - found, err := NewClient(config, config.UserAgent).NetworkEdgeSecurityServices.AggregatedList(config.Project).Do() + listUrl := fmt.Sprintf("%sprojects/%s/aggregated/networkEdgeSecurityServices", transport_tpg.BaseUrl(Product, config), config.Project) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: listUrl, + UserAgent: config.UserAgent, + }) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error in response from request: %s", err) return nil @@ -38,19 +47,43 @@ func testSweepComputeNetworkEdgeSecurityService(region string) error { // Keep count of items that aren't sweepable for logging. nonPrefixCount := 0 - for zone, itemList := range found.Items { - for _, tp := range itemList.NetworkEdgeSecurityServices { - if !sweeper.IsSweepableTestResource(tp.Name) { + // Aggregated list response: items is a map keyed by "regions/{region}" + items, ok := res["items"].(map[string]interface{}) + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + for regionPath, regionDataRaw := range items { + regionData, ok := regionDataRaw.(map[string]interface{}) + if !ok { + continue + } + resourcesRaw, ok := regionData["networkEdgeSecurityServices"] + if !ok { + continue + } + for _, tpRaw := range resourcesRaw.([]interface{}) { + tp := tpRaw.(map[string]interface{}) + name := tp["name"].(string) + if !sweeper.IsSweepableTestResource(name) { nonPrefixCount++ continue } + region := tpgresource.GetResourceNameFromSelfLink(regionPath) + deleteUrl := fmt.Sprintf("%sprojects/%s/regions/%s/networkEdgeSecurityServices/%s", transport_tpg.BaseUrl(Product, config), config.Project, region, name) // Don't wait on operations as we may have a lot to delete - _, err := NewClient(config, config.UserAgent).NetworkEdgeSecurityServices.Delete(config.Project, tpgresource.GetResourceNameFromSelfLink(zone), tp.Name).Do() + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: config.Project, + RawURL: deleteUrl, + UserAgent: config.UserAgent, + }) if err != nil { - log.Printf("[INFO][SWEEPER_LOG] Error deleting %s resource %s : %s", resourceName, tp.Name, err) + log.Printf("[INFO][SWEEPER_LOG] Error deleting %s resource %s : %s", resourceName, name, err) } else { - log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, tp.Name) + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) } } } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_test.go.tmpl index c88c5002ccf1..047686b1c595 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_edge_security_service_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeNetworkEdgeSecurityService_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_group_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_group_test.go index fd4d0954f704..81f73bd92748 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_group_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_group_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeNetworkEndpointGroup_networkEndpointGroup(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_test.go.tmpl index b47804e731d5..291f816207ed 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoint_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_recreate_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_recreate_test.go index 207dcae803d9..ea2e1a4aa94c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_recreate_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_recreate_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_test.go.tmpl index 32a7c05edd94..effcd9688286 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_endpoints_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_packet_mirroring_rule_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_packet_mirroring_rule_test.go.tmpl index 6dcb837d7e29..7988a653358f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_packet_mirroring_rule_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_packet_mirroring_rule_test.go.tmpl @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_rule_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_rule_test.go index bca45c661c3c..f3f22fd2ace2 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_rule_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_rule_test.go @@ -8,6 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeNetworkFirewallPolicyRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_test.go index d7ad8453eb0e..389e0c6d051c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeNetworkFirewallPolicy_GlobalHandWritten(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_with_rules_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_with_rules_test.go index 43488d34c0bc..d257579a5d4f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_with_rules_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_firewall_policy_with_rules_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeNetworkFirewallPolicyWithRules_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_peering.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_peering.go.tmpl index 62dde79499b0..6daca68084c0 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_peering.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_peering.go.tmpl @@ -8,6 +8,7 @@ import ( "time" "reflect" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/api/googleapi" @@ -41,6 +42,10 @@ func ResourceComputeNetworkPeering() *schema.Resource { Delete: schema.DefaultTimeout(4 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -122,6 +127,9 @@ func ResourceComputeNetworkPeering() *schema.Resource { Description: `The update strategy determines the semantics for updates and deletes to the peering connection configuration. The default value is INDEPENDENT. Possible values: ["INDEPENDENT", "CONSENSUS"]`, Default: "INDEPENDENT", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -226,10 +234,20 @@ func resourceComputeNetworkPeeringRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error setting update_strategy: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeNetworkPeeringUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeNetworkPeering) { + return ResourceComputeNetworkPeering().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -270,6 +288,13 @@ func resourceComputeNetworkPeeringUpdate(d *schema.ResourceData, meta interface{ } func resourceComputeNetworkPeeringDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_peering_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_peering_meta.yaml.tmpl index 6416fbf1d956..0e343d87035d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_peering_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_peering_meta.yaml.tmpl @@ -29,3 +29,5 @@ fields: field: 'state_details' - api_field: 'peerings.updateStrategy' field: 'update_strategy' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_network_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_network_test.go.tmpl index d2b9689e8e0b..ea3fbb5118a2 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_network_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_network_test.go.tmpl @@ -6,24 +6,20 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" - compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" - "github.com/hashicorp/terraform-provider-google/google/services/tags" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} + "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeNetwork_explicitAutoSubnet(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-basic-%s", suffixName) @@ -53,7 +49,7 @@ func TestAccComputeNetwork_explicitAutoSubnet(t *testing.T) { func TestAccComputeNetwork_customSubnet(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-custom-sn-%s", suffixName) @@ -83,7 +79,7 @@ func TestAccComputeNetwork_customSubnet(t *testing.T) { func TestAccComputeNetwork_mtuAndUpdate(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-routing-mode-%s", suffixName) @@ -118,7 +114,7 @@ func TestAccComputeNetwork_mtuAndUpdate(t *testing.T) { func TestAccComputeNetwork_routingModeAndUpdate(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-routing-mode-%s", suffixName) @@ -153,7 +149,7 @@ func TestAccComputeNetwork_routingModeAndUpdate(t *testing.T) { func TestAccComputeNetwork_bgpBestPathSelectionModeAndUpdate(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-best-bgp-path-selection-mode-%s", suffixName) @@ -188,7 +184,7 @@ func TestAccComputeNetwork_bgpBestPathSelectionModeAndUpdate(t *testing.T) { func TestAccComputeNetwork_bgpAlwaysCompareMedAndUpdate(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-bgp-always-compare-med-%s", suffixName) @@ -230,7 +226,7 @@ func TestAccComputeNetwork_bgpAlwaysCompareMedAndUpdate(t *testing.T) { func TestAccComputeNetwork_bgpInterRegionCostAndUpdate(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-bgp-inter-region-cost-%s", suffixName) @@ -263,7 +259,7 @@ func TestAccComputeNetwork_bgpInterRegionCostAndUpdate(t *testing.T) { func TestAccComputeNetwork_networkProfile(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-profile-%s", suffixName) projectId := envvar.GetTestProjectFromEnv() @@ -366,7 +362,7 @@ func TestAccComputeNetwork_numericId(t *testing.T) { func TestAccComputeNetwork_default_routing_mode(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-network-default-routes-%s", suffixName) @@ -393,7 +389,7 @@ func TestAccComputeNetwork_default_routing_mode(t *testing.T) { func TestAccComputeNetwork_default_bgp_best_path_selection_mode(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-bgp-best-path-selection-default-routes-%s", suffixName) @@ -419,7 +415,7 @@ func TestAccComputeNetwork_default_bgp_best_path_selection_mode(t *testing.T) { func TestAccComputeNetwork_default_bgp_always_compare_med(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-bgp-always-compare-med-default-routes-%s", suffixName) @@ -445,7 +441,7 @@ func TestAccComputeNetwork_default_bgp_always_compare_med(t *testing.T) { func TestAccComputeNetwork_networkDeleteDefaultRoute(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-network-default-routes-%s", suffixName) @@ -470,8 +466,8 @@ func TestAccComputeNetwork_networkDeleteDefaultRoute(t *testing.T) { func TestAccComputeNetwork_networkFirewallPolicyEnforcementOrderAndUpdate(t *testing.T) { t.Parallel() - var network compute.Network - var updatedNetwork compute.Network + var network map[string]interface{} + var updatedNetwork map[string]interface{} suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-firewall-policy-enforcement-order-%s", suffixName) @@ -523,7 +519,7 @@ func TestAccComputeNetwork_resourceManagerTags(t *testing.T) { t.Parallel() - var network compute.Network + var network map[string]interface{} org := envvar.GetTestOrgFromEnv(t) suffixName := acctest.RandString(t, 10) @@ -553,7 +549,7 @@ func TestAccComputeNetwork_resourceManagerTags(t *testing.T) { }) } -func testAccCheckComputeNetworkExists(t *testing.T, n string, network *compute.Network) resource.TestCheckFunc { +func testAccCheckComputeNetworkExists(t *testing.T, n string, network *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -566,23 +562,30 @@ func testAccCheckComputeNetworkExists(t *testing.T, n string, network *compute.N config := acctest.GoogleProviderConfig(t) - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, rs.Primary.Attributes["name"]).Do() + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, rs.Primary.Attributes["name"]) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.Name != rs.Primary.Attributes["name"] { + if found["name"].(string) != rs.Primary.Attributes["name"] { return fmt.Errorf("Network not found") } - *network = *found + *network = found return nil } } -func testAccCheckComputeNetworkDefaultRoutesDeleted(t *testing.T, n string, network *compute.Network) resource.TestCheckFunc { +func testAccCheckComputeNetworkDefaultRoutesDeleted(t *testing.T, n string, network *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -595,12 +598,26 @@ func testAccCheckComputeNetworkDefaultRoutesDeleted(t *testing.T, n string, netw config := acctest.GoogleProviderConfig(t) - routes, err := compute_tpg.NewClient(config, config.UserAgent).Routes.List(config.Project).Filter(fmt.Sprintf("(network=\"%s\") AND (destRange=\"0.0.0.0/0\")", network.SelfLink)).Do() + selfLink, _ := (*network)["selfLink"].(string) + url := fmt.Sprintf("%sprojects/%s/global/routes", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project) + url, err := transport_tpg.AddQueryParams(url, map[string]string{ + "filter": fmt.Sprintf("(network=\"%s\") AND (destRange=\"0.0.0.0/0\")", selfLink), + }) + if err != nil { + return err + } + routes, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if len(routes.Items) > 0 { + if items, ok := routes["items"].([]interface{}); ok && len(items) > 0 { return fmt.Errorf("Default routes were not deleted") } @@ -608,21 +625,31 @@ func testAccCheckComputeNetworkDefaultRoutesDeleted(t *testing.T, n string, netw } } -func testAccCheckComputeNetworkIsAutoSubnet(t *testing.T, n string, network *compute.Network) resource.TestCheckFunc { +func testAccCheckComputeNetworkIsAutoSubnet(t *testing.T, n string, network *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if !found.AutoCreateSubnetworks { + autoCreate, _ := found["autoCreateSubnetworks"].(bool) + if !autoCreate { return fmt.Errorf("should have AutoCreateSubnetworks = true") } - if found.IPv4Range != "" { + ipv4Range, _ := found["ipv4Range"].(string) + if ipv4Range != "" { return fmt.Errorf("should not have IPv4Range") } @@ -630,21 +657,31 @@ func testAccCheckComputeNetworkIsAutoSubnet(t *testing.T, n string, network *com } } -func testAccCheckComputeNetworkIsCustomSubnet(t *testing.T, n string, network *compute.Network) resource.TestCheckFunc { +func testAccCheckComputeNetworkIsCustomSubnet(t *testing.T, n string, network *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.AutoCreateSubnetworks { + autoCreate, _ := found["autoCreateSubnetworks"].(bool) + if autoCreate { return fmt.Errorf("should have AutoCreateSubnetworks = false") } - if found.IPv4Range != "" { + ipv4Range, _ := found["ipv4Range"].(string) + if ipv4Range != "" { return fmt.Errorf("should not have IPv4Range") } @@ -652,21 +689,31 @@ func testAccCheckComputeNetworkIsCustomSubnet(t *testing.T, n string, network *c } } -func testAccCheckComputeNetworkIsUlaInternalIpv6Enabled(t *testing.T, n string, network *compute.Network, expectEnabled bool) resource.TestCheckFunc { +func testAccCheckComputeNetworkIsUlaInternalIpv6Enabled(t *testing.T, n string, network *map[string]interface{}, expectEnabled bool) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.EnableUlaInternalIpv6 != expectEnabled { + enableUla, _ := found["enableUlaInternalIpv6"].(bool) + if enableUla != expectEnabled { return fmt.Errorf("does not match expected EnableUlaInternalIpv6 value") } - if expectEnabled && found.InternalIpv6Range == "" { + internalIpv6Range, _ := found["internalIpv6Range"].(string) + if expectEnabled && internalIpv6Range == "" { return fmt.Errorf("should have InternalIPv6Range") } @@ -674,7 +721,7 @@ func testAccCheckComputeNetworkIsUlaInternalIpv6Enabled(t *testing.T, n string, } } -func testAccCheckComputeNetworkHasMtu(t *testing.T, n string, network *compute.Network, mtu int32) resource.TestCheckFunc { +func testAccCheckComputeNetworkHasMtu(t *testing.T, n string, network *map[string]interface{}, mtu int32) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) @@ -687,23 +734,31 @@ func testAccCheckComputeNetworkHasMtu(t *testing.T, n string, network *compute.N return fmt.Errorf("Routing mode not found on resource") } - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - foundMtu := found.Mtu + foundMtu, _ := found["mtu"].(float64) - if int64(mtu) != foundMtu { - return fmt.Errorf("Expected mtu %d to match actual routing mode %d", mtu, foundMtu) + if float64(mtu) != foundMtu { + return fmt.Errorf("Expected mtu %d to match actual routing mode %d", mtu, int64(foundMtu)) } return nil } } -func testAccCheckComputeNetworkHasRoutingMode(t *testing.T, n string, network *compute.Network, routingMode string) resource.TestCheckFunc { +func testAccCheckComputeNetworkHasRoutingMode(t *testing.T, n string, network *map[string]interface{}, routingMode string) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) @@ -716,13 +771,22 @@ func testAccCheckComputeNetworkHasRoutingMode(t *testing.T, n string, network *c return fmt.Errorf("Routing mode not found on resource") } - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - foundRoutingMode := found.RoutingConfig.RoutingMode + routingConfig, _ := found["routingConfig"].(map[string]interface{}) + foundRoutingMode, _ := routingConfig["routingMode"].(string) if routingMode != foundRoutingMode { return fmt.Errorf("Expected routing mode %s to match actual routing mode %s", routingMode, foundRoutingMode) @@ -732,7 +796,7 @@ func testAccCheckComputeNetworkHasRoutingMode(t *testing.T, n string, network *c } } -func testAccCheckComputeNetworkHasNetworkProfile(t *testing.T, n string, network *compute.Network, networkProfile string) resource.TestCheckFunc { +func testAccCheckComputeNetworkHasNetworkProfile(t *testing.T, n string, network *map[string]interface{}, networkProfile string) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) @@ -745,13 +809,21 @@ func testAccCheckComputeNetworkHasNetworkProfile(t *testing.T, n string, network return fmt.Errorf("Network profile not found on resource") } - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - foundNetworkProfile := found.NetworkProfile + foundNetworkProfile, _ := found["networkProfile"].(string) if tpgresource.CompareSelfLinkOrResourceName("", foundNetworkProfile, networkProfile, nil) != true { return fmt.Errorf("Expected Network Profile always compare med %s to match actual Network Profile always compare med %s", networkProfile, foundNetworkProfile) @@ -761,7 +833,7 @@ func testAccCheckComputeNetworkHasNetworkProfile(t *testing.T, n string, network } } -func testAccCheckComputeNetworkHasNetworkFirewallPolicyEnforcementOrder(t *testing.T, n string, network *compute.Network, order string) resource.TestCheckFunc { +func testAccCheckComputeNetworkHasNetworkFirewallPolicyEnforcementOrder(t *testing.T, n string, network *map[string]interface{}, order string) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) @@ -774,13 +846,21 @@ func testAccCheckComputeNetworkHasNetworkFirewallPolicyEnforcementOrder(t *testi return fmt.Errorf("Network firewall policy enforcement order not found on resource") } - found, err := compute_tpg.NewClient(config, config.UserAgent).Networks.Get( - config.Project, network.Name).Do() + networkName, _ := (*network)["name"].(string) + url := fmt.Sprintf("%sprojects/%s/global/networks/%s", + transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, networkName) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - foundNetworkFirewallPolicyEnforcementOrder := found.NetworkFirewallPolicyEnforcementOrder + foundNetworkFirewallPolicyEnforcementOrder, _ := found["networkFirewallPolicyEnforcementOrder"].(string) if order != foundNetworkFirewallPolicyEnforcementOrder { return fmt.Errorf("Expected network firewall policy enforcement order %s to match %s", order, foundNetworkFirewallPolicyEnforcementOrder) @@ -790,10 +870,12 @@ func testAccCheckComputeNetworkHasNetworkFirewallPolicyEnforcementOrder(t *testi } } -func testAccCheckComputeNetworkWasUpdated(newNetwork *compute.Network, oldNetwork *compute.Network) resource.TestCheckFunc { +func testAccCheckComputeNetworkWasUpdated(newNetwork *map[string]interface{}, oldNetwork *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if oldNetwork.CreationTimestamp != newNetwork.CreationTimestamp { - return fmt.Errorf("expected compute network to have been updated (had same creation time), instead was recreated - old creation time %s, new creation time %s", oldNetwork.CreationTimestamp, newNetwork.CreationTimestamp) + oldTs, _ := (*oldNetwork)["creationTimestamp"].(string) + newTs, _ := (*newNetwork)["creationTimestamp"].(string) + if oldTs != newTs { + return fmt.Errorf("expected compute network to have been updated (had same creation time), instead was recreated - old creation time %s, new creation time %s", oldTs, newTs) } return nil } @@ -875,8 +957,8 @@ func TestAccComputeNetwork_networkBgpStandardModeDeleteMed(t *testing.T) { func TestAccComputeNetwork_updateEnableUlaInternalIpv6(t *testing.T) { t.Parallel() - var network compute.Network - var updatedNetwork compute.Network + var network, updatedNetwork map[string]interface{} + suffixName := acctest.RandString(t, 10) networkName := fmt.Sprintf("tf-test-network-enable-ula-%s", suffixName) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_node_group_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_node_group_test.go index 444a71c8887d..2b50e25ec71c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_node_group_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_node_group_test.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeNodeGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_association_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_association_test.go index ed0301ea61e3..b8c64fcc3e46 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_association_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_association_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeOrganizationSecurityPolicyAssociation_excludeFields(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_rule_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_rule_test.go.tmpl index a1642c975c6d..2df1b61307db 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_rule_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_rule_test.go.tmpl @@ -3,6 +3,8 @@ package compute_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_test.go index 753136686e95..82ac566eeab4 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_organization_security_policy_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_packet_mirroring_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_packet_mirroring_test.go index d96f3ee53932..6f0b6d11ba80 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_packet_mirroring_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_packet_mirroring_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputePacketMirroring_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_cloud_armor_tier_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_project_cloud_armor_tier_test.go index 6fb11796124a..32931a4112d1 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_cloud_armor_tier_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_cloud_armor_tier_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeProjectCloudArmorTier_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier.go similarity index 67% rename from mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier.go.tmpl rename to mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier.go index a0db629c9a1d..5a12576bae26 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier.go @@ -13,12 +13,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} ) func ResourceComputeProjectDefaultNetworkTier() *schema.Resource { @@ -36,6 +30,7 @@ func ResourceComputeProjectDefaultNetworkTier() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -63,7 +58,7 @@ func ResourceComputeProjectDefaultNetworkTier() *schema.Resource { func resourceComputeProjectDefaultNetworkTierCreateOrUpdate(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -73,20 +68,32 @@ func resourceComputeProjectDefaultNetworkTierCreateOrUpdate(d *schema.ResourceDa return err } - request := &compute.ProjectsSetDefaultNetworkTierRequest{ - NetworkTier: d.Get("network_tier").(string), + request := map[string]interface{}{ + "networkTier": d.Get("network_tier").(string), } - op, err := NewClient(config, userAgent).Projects.SetDefaultNetworkTier(projectID, request).Do() + + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return fmt.Errorf("SetDefaultNetworkTier failed: %s", err) } - - log.Printf("[DEBUG] SetDefaultNetworkTier: %d (%s)", op.Id, op.SelfLink) - err = ComputeOperationWaitTime(config, op, projectID, "SetDefaultNetworkTier", userAgent, d.Timeout(schema.TimeoutCreate)) + url = fmt.Sprintf("%sprojects/%s/setDefaultNetworkTier", url, projectID) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: projectID, + RawURL: url, + UserAgent: userAgent, + Body: request, + }) if err != nil { return fmt.Errorf("SetDefaultNetworkTier failed: %s", err) } + log.Printf("[DEBUG] SetDefaultNetworkTier: %v", res["selfLink"]) + if err = ComputeOperationWaitTime(config, res, projectID, "SetDefaultNetworkTier", userAgent, d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("SetDefaultNetworkTier failed: %s", err) + } + d.SetId(projectID) return resourceComputeProjectDefaultNetworkTierRead(d, meta) @@ -94,20 +101,30 @@ func resourceComputeProjectDefaultNetworkTierCreateOrUpdate(d *schema.ResourceDa func resourceComputeProjectDefaultNetworkTierRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } projectId := d.Id() - project, err := NewClient(config, userAgent).Projects.Get(projectId).Do() + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) + if err != nil { + return err + } + url = fmt.Sprintf("%sprojects/%s", url, projectId) + project, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: projectId, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Project data for project %q", projectId)) } - err = d.Set("network_tier", project.DefaultNetworkTier) - if err != nil { + if err = d.Set("network_tier", project["defaultNetworkTier"].(string)); err != nil { return fmt.Errorf("Error setting default network tier: %s", err) } @@ -119,7 +136,6 @@ func resourceComputeProjectDefaultNetworkTierRead(d *schema.ResourceData, meta i } func resourceComputeProjectDefaultNetworkTierDelete(d *schema.ResourceData, meta interface{}) error { - log.Printf("[WARNING] Default Network Tier will be only removed from Terraform state, but will be left intact on GCP.") return schema.RemoveFromState(d, meta) @@ -127,9 +143,9 @@ func resourceComputeProjectDefaultNetworkTierDelete(d *schema.ResourceData, meta func init() { registry.Schema{ - Name: "google_compute_project_default_network_tier", + Name: "google_compute_project_default_network_tier", ProductName: "compute", - Type: registry.SchemaTypeResource, - Schema: ResourceComputeProjectDefaultNetworkTier(), + Type: registry.SchemaTypeResource, + Schema: ResourceComputeProjectDefaultNetworkTier(), }.Register() } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier_test.go index a07443c691f5..684ec8764770 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_default_network_tier_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeProjectDefaultNetworkTier_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata.go.tmpl index 3919a6ca0dc5..0f1fd7cbe951 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata.go.tmpl @@ -36,6 +36,7 @@ func ResourceComputeProjectMetadata() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -56,12 +57,20 @@ func ResourceComputeProjectMetadata() *schema.Resource { ForceNew: true, Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } } func resourceComputeProjectMetadataCreateOrUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeProjectMetadata) { + return ResourceComputeProjectMetadata().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -118,11 +127,23 @@ func resourceComputeProjectMetadataRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error setting project: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeProjectMetadataDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item.go.tmpl index a2e0cd299f54..b0d1772ce0c6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item.go.tmpl @@ -37,6 +37,7 @@ func ResourceComputeProjectMetadataItem() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -59,6 +60,9 @@ func ResourceComputeProjectMetadataItem() *schema.Resource { ForceNew: true, Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, Timeouts: &schema.ResourceTimeout{ @@ -130,10 +134,20 @@ func resourceComputeProjectMetadataItemRead(d *schema.ResourceData, meta interfa return fmt.Errorf("Error setting value: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeProjectMetadataItemUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeProjectMetadataItem) { + return ResourceComputeProjectMetadataItem().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -158,7 +172,14 @@ func resourceComputeProjectMetadataItemUpdate(d *schema.ResourceData, meta inter } func resourceComputeProjectMetadataItemDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item_meta.yaml.tmpl index 7a537992ce82..090375662550 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_item_meta.yaml.tmpl @@ -13,3 +13,5 @@ fields: - field: 'project' - api_field: 'commonInstanceMetadata.items' field: 'value' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_meta.yaml.tmpl index eb9602ed55c0..9ec11f835f88 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_meta.yaml.tmpl @@ -11,3 +11,5 @@ fields: - api_field: 'commonInstanceMetadata.items' field: 'metadata' - field: 'project' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_test.go index 31504a340d76..40bfd505f863 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_project_metadata_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // Add two key value pairs diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_public_advertised_prefix_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_public_advertised_prefix_test.go index a2bf0ce6fee5..a91d26f37f6e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_public_advertised_prefix_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_public_advertised_prefix_test.go @@ -448,7 +448,7 @@ func testAccCheckComputePublicDelegatedPrefixDestroyProducer(t *testing.T) func( config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/publicDelegatedPrefixes/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(compute.Product, config)+"projects/{{project}}/regions/{{region}}/publicDelegatedPrefixes/{{name}}") if err != nil { return err } @@ -487,7 +487,7 @@ func testAccCheckComputePublicAdvertisedPrefixDestroyProducer(t *testing.T) func config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/global/publicAdvertisedPrefixes/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(compute.Product, config)+"projects/{{project}}/global/publicAdvertisedPrefixes/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_autoscaler_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_autoscaler_test.go.tmpl index 969c83b1bd3c..0b67d3cfb70c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_autoscaler_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_autoscaler_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_ha_policy_manual_leader_update_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_ha_policy_manual_leader_update_test.go index 625a6fb2964e..4eaedd2ad603 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_ha_policy_manual_leader_update_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_ha_policy_manual_leader_update_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionBackendService_regionBackendServiceHaPolicyManualLeader_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_test.go.tmpl index eb953c0b9065..b002db0d3792 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_backend_service_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_composite_health_check_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_composite_health_check_test.go index 42aa75764888..53a45ae059c9 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_composite_health_check_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_composite_health_check_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionCompositeHealthCheck_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_disk_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_disk_test.go.tmpl index 2e6eac1b34da..0af7acb2a114 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_disk_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_disk_test.go.tmpl @@ -14,6 +14,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/plancheck" {{ if eq $.TargetVersionName `ga` }} @@ -369,7 +372,7 @@ func TestAccComputeRegionDisk_createSnapshotBeforeDestroy(t *testing.T) { "disk_name2": fmt.Sprintf("test-%s", acctest.RandString(t, 44)), //this is over the snapshot character creation limit of 48 "disk_name3": fmt.Sprintf("tf-test-disk-%s", acctest.RandString(t, 10)), "snapshot_prefix": fmt.Sprintf("tf-test-snapshot-%s", acctest.RandString(t, 10)), - "kms_key_self_link": acctest.BootstrapKMSKey(t).CryptoKey.Name, + "kms_key_self_link": kms.BootstrapKMSKey(t).CryptoKey.Name, "raw_key": "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=", "rsa_encrypted_key": "ieCx/NcW06PcT7Ep1X6LUTc/hLvUDYyzSZPPVCVPTVEohpeHASqC8uw5TzyO9U+Fka9JFHz0mBibXUInrC/jEk014kCK/NPjYgEMOyssZ4ZINPKxlUh2zn1bV+MCaTICrdmuSBTWlUUiFoDD6PYznLwh8ZNdaheCeZ8ewEXgFQ8V+sDroLaN3Xs3MDTXQEMMoNUXMCZEIpg9Vtp9x2oeQ5lAbtt7bYAAHf5l+gJWw3sUfs0/Glw5fpdjT8Uggrr+RMZezGrltJEF293rvTIjWOEB3z5OHyHwQkvdrPDFcTqsLfh+8Hr8g+mf+7zVPEC8nEbqpdl3GPv3A7AwpFp7MA==", } @@ -476,7 +479,7 @@ func testAccCheckComputeRegionDiskExists(t *testing.T, n string, disk *compute.D config := acctest.GoogleProviderConfig(t) - url := fmt.Sprintf("%sprojects/%s/regions/%s/disks/%s", config.ComputeBasePath, p, rs.Primary.Attributes["region"], rs.Primary.Attributes["name"]) + url := fmt.Sprintf("%sprojects/%s/regions/%s/disks/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), p, rs.Primary.Attributes["region"], rs.Primary.Attributes["name"]) res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", @@ -902,19 +905,19 @@ resource "google_compute_region_disk" "kms-encrypted-name" { func TestAccComputeRegionDisk_fromImageKMS(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) suffix := acctest.RandString(t, 10) diskName := fmt.Sprintf("tf-test-kms-disk-%s", suffix) imageName := fmt.Sprintf("tf-test-kms-image-%s", suffix) context := map[string]interface{}{ "random_suffix": suffix, - "kms_key_self_link": kms.CryptoKey.Name, + "kms_key_self_link": bootstrapped.CryptoKey.Name, "image_name": imageName, "disk_name": diskName, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -1098,19 +1101,19 @@ resource "google_compute_region_disk" "disk_from_rsa_image" { func TestAccComputeRegionDisk_fromImageKMSWithServiceAccount(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) suffix := acctest.RandString(t, 10) diskName := fmt.Sprintf("tf-test-kms-sa-disk-%s", suffix) imageName := fmt.Sprintf("tf-test-kms-sa-image-%s", suffix) context := map[string]interface{}{ "random_suffix": suffix, - "kms_key_self_link": kms.CryptoKey.Name, + "kms_key_self_link": bootstrapped.CryptoKey.Name, "image_name": imageName, "disk_name": diskName, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_health_aggregation_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_health_aggregation_policy_test.go index 8229031696ae..e645af889b6b 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_health_aggregation_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_health_aggregation_policy_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionHealthAggregationPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_health_check_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_health_check_test.go index e005d2cc9ad2..f286c7804c2a 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_health_check_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_health_check_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionHealthCheck_tcp_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_health_source_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_health_source_test.go index 680ce8503875..38d492b671a9 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_health_source_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_health_source_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionHealthSource_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager.go.tmpl index 78a20daeef16..c56fedfd59c4 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager.go.tmpl @@ -38,6 +38,7 @@ func ResourceComputeRegionInstanceGroupManager() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, customdiff.ForceNewIfChange("resource_policies.0.workload_policy", ForceNewResourcePoliciesWorkloadPolicyIfNewIsEmpty), @@ -981,6 +982,9 @@ func ResourceComputeRegionInstanceGroupManager() *schema.Resource { }, }, {{- end }} + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -1275,10 +1279,20 @@ func resourceComputeRegionInstanceGroupManagerRead(d *schema.ResourceData, meta } } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeRegionInstanceGroupManagerUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeRegionInstanceGroupManager) { + return ResourceComputeRegionInstanceGroupManager().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) @@ -1457,7 +1471,14 @@ func resourceComputeRegionInstanceGroupManagerUpdate(d *schema.ResourceData, met } func resourceComputeRegionInstanceGroupManagerDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_meta.yaml.tmpl index cdcaeeab84ed..aaeb4cd5b518 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_meta.yaml.tmpl @@ -181,3 +181,5 @@ fields: provider_only: true - field: 'wait_for_instances_status' provider_only: true + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_test.go.tmpl index c5754a8d8206..9b20d4cf456a 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_group_manager_test.go.tmpl @@ -8,9 +8,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" {{- if ne $.TargetVersionName "ga" }} "github.com/hashicorp/terraform-provider-google/google/envvar" {{- end }} + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -620,7 +622,7 @@ func testAccCheckRegionInstanceGroupManagerDestroyProducer(t *testing.T) func(s continue } url := fmt.Sprintf("%sprojects/%s/regions/%s/instanceGroupManagers/%s", - config.ComputeBasePath, + transport_tpg.BaseUrl(tpgcompute.Product, config), rs.Primary.Attributes["project"], rs.Primary.Attributes["region"], rs.Primary.Attributes["name"]) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl index 33c2b0afea1a..395b165548a6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template.go.tmpl @@ -35,6 +35,7 @@ func ResourceComputeRegionInstanceTemplate() *schema.Resource { }, SchemaVersion: 1, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, resourceComputeInstanceTemplateSourceImageCustomizeDiff, @@ -599,6 +600,32 @@ Google Cloud KMS. Only one of kms_key_self_link, rsa_encrypted_key and raw_key m }, }, + {{ if ne $.TargetVersionName `ga` -}} + "alias_ipv6_range": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `An array of alias IPv6 ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ip_cidr_range": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: IpCidrRangeDiffSuppress, + Description: `The IP CIDR range represented by this alias IPv6 range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces. At the time of writing only a netmask (e.g. /96) may be supplied, with a CIDR format resulting in an API error.`, + }, + "subnetwork_range_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IPv6 range. If left unspecified, the primary range of the subnetwork will be used.`, + }, + }, + }, + }, + {{- end }} + "stack_type": { Type: schema.TypeString, Optional: true, @@ -1274,6 +1301,9 @@ be from 0 to 999,999,999 inclusive.`, ValidateFunc: validation.StringInSlice([]string{"NONE", "STOP", ""}, false), Description: `Action to be taken when a customer's encryption key is revoked. Supports "STOP" and "NONE", with "NONE" being the default.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -1336,39 +1366,128 @@ func resourceComputeRegionInstanceTemplateCreate(d *schema.ResourceData, meta in } resourcePolicies := expandInstanceTemplateResourcePolicies(d, "resource_policies") - instanceProperties := &compute.InstanceProperties{ - CanIpForward: d.Get("can_ip_forward").(bool), - Description: d.Get("instance_description").(string), - GuestAccelerators: expandInstanceTemplateGuestAccelerators(d, config), - MachineType: d.Get("machine_type").(string), - MinCpuPlatform: d.Get("min_cpu_platform").(string), - Disks: disks, - Metadata: metadata, - {{- if ne $.TargetVersionName "ga" }} - PartnerMetadata: PartnerMetadata, - {{- end }} - NetworkInterfaces: networks, - NetworkPerformanceConfig: networkPerformanceConfig, - Scheduling: scheduling, - ServiceAccounts: expandServiceAccounts(d.Get("service_account").([]interface{})), - Tags: resourceInstanceTags(d), - ConfidentialInstanceConfig: expandConfidentialInstanceConfig(d), - ShieldedInstanceConfig: expandShieldedVmConfigs(d), - AdvancedMachineFeatures: expandAdvancedMachineFeatures(d), -{{- if ne $.TargetVersionName "ga" }} - DisplayDevice: expandDisplayDevice(d), -{{- end }} - ResourcePolicies: resourcePolicies, - ReservationAffinity: reservationAffinity, - KeyRevocationActionType: d.Get("key_revocation_action_type").(string), + // Convert network interfaces (still typed) via JSON roundtrip + networksJSON, err := json.Marshal(networks) + if err != nil { + return fmt.Errorf("Error marshaling network interfaces: %s", err) + } + var networksIface interface{} + if err := json.Unmarshal(networksJSON, &networksIface); err != nil { + return fmt.Errorf("Error unmarshaling network interfaces: %s", err) } - if _, ok := d.GetOk("effective_labels"); ok { - instanceProperties.Labels = tpgresource.ExpandEffectiveLabels(d) + // Convert service accounts (still typed) via JSON roundtrip + saJSON, err := json.Marshal(expandServiceAccounts(d.Get("service_account").([]interface{}))) + if err != nil { + return fmt.Errorf("Error marshaling service accounts: %s", err) + } + var serviceAccountsIface interface{} + if err := json.Unmarshal(saJSON, &serviceAccountsIface); err != nil { + return fmt.Errorf("Error unmarshaling service accounts: %s", err) } + instanceProperties := map[string]interface{}{ + "machineType": d.Get("machine_type").(string), + "disks": disks, + "networkInterfaces": networksIface, + "scheduling": scheduling, + } + if d.Get("can_ip_forward").(bool) { + instanceProperties["canIpForward"] = true + } + if v := d.Get("instance_description").(string); v != "" { + instanceProperties["description"] = v + } + if ga := expandInstanceTemplateGuestAccelerators(d, config); len(ga) > 0 { + instanceProperties["guestAccelerators"] = ga + } + if sa, ok := serviceAccountsIface.([]interface{}); ok && len(sa) > 0 { + instanceProperties["serviceAccounts"] = serviceAccountsIface + } + if len(resourcePolicies) > 0 { + instanceProperties["resourcePolicies"] = resourcePolicies + } + if v := d.Get("min_cpu_platform").(string); v != "" { + instanceProperties["minCpuPlatform"] = v + } + if v := d.Get("key_revocation_action_type").(string); v != "" { + instanceProperties["keyRevocationActionType"] = v + } + if metadata != nil { + metadataMap, err := tpgresource.ConvertToMap(metadata) + if err != nil { + return fmt.Errorf("Error converting metadata: %s", err) + } + instanceProperties["metadata"] = metadataMap + } + if networkPerformanceConfig != nil { + npcMap, err := tpgresource.ConvertToMap(networkPerformanceConfig) + if err != nil { + return fmt.Errorf("Error converting networkPerformanceConfig: %s", err) + } + instanceProperties["networkPerformanceConfig"] = npcMap + } + if tags := resourceInstanceTags(d); tags != nil { + tagsMap, err := tpgresource.ConvertToMap(tags) + if err != nil { + return fmt.Errorf("Error converting tags: %s", err) + } + instanceProperties["tags"] = tagsMap + } + if cic := expandConfidentialInstanceConfig(d); cic != nil { + cicMap, err := tpgresource.ConvertToMap(cic) + if err != nil { + return fmt.Errorf("Error converting confidentialInstanceConfig: %s", err) + } + instanceProperties["confidentialInstanceConfig"] = cicMap + } + if sic := expandShieldedVmConfigs(d); sic != nil { + // Build manually to preserve false boolean values (ForceSendFields workaround) + instanceProperties["shieldedInstanceConfig"] = map[string]interface{}{ + "enableSecureBoot": sic.EnableSecureBoot, + "enableVtpm": sic.EnableVtpm, + "enableIntegrityMonitoring": sic.EnableIntegrityMonitoring, + } + } + if amf := expandAdvancedMachineFeatures(d); amf != nil { + amfMap, err := tpgresource.ConvertToMap(amf) + if err != nil { + return fmt.Errorf("Error converting advancedMachineFeatures: %s", err) + } + instanceProperties["advancedMachineFeatures"] = amfMap + } + if reservationAffinity != nil { + raMap, err := tpgresource.ConvertToMap(reservationAffinity) + if err != nil { + return fmt.Errorf("Error converting reservationAffinity: %s", err) + } + instanceProperties["reservationAffinity"] = raMap + } + {{- if ne $.TargetVersionName "ga" }} + if len(PartnerMetadata) > 0 { + pmJSON, err := json.Marshal(PartnerMetadata) + if err != nil { + return fmt.Errorf("Error marshaling partner metadata: %s", err) + } + var pmIface interface{} + if err := json.Unmarshal(pmJSON, &pmIface); err != nil { + return fmt.Errorf("Error unmarshaling partner metadata: %s", err) + } + instanceProperties["partnerMetadata"] = pmIface + } + if dd := expandDisplayDevice(d); dd != nil { + ddMap, err := tpgresource.ConvertToMap(dd) + if err != nil { + return fmt.Errorf("Error converting displayDevice: %s", err) + } + instanceProperties["displayDevice"] = ddMap + } + {{- end }} + if _, ok := d.GetOk("effective_labels"); ok { + instanceProperties["labels"] = tpgresource.ExpandEffectiveLabels(d) + } if _, ok := d.GetOk("resource_manager_tags"); ok { - instanceProperties.ResourceManagerTags = tpgresource.ExpandStringMap(d, "resource_manager_tags") + instanceProperties["resourceManagerTags"] = tpgresource.ExpandStringMap(d, "resource_manager_tags") } var itName string @@ -1385,10 +1504,13 @@ func resourceComputeRegionInstanceTemplateCreate(d *schema.ResourceData, meta in itName = id.UniqueId() } - instanceTemplate := make(map[string]interface{}) - instanceTemplate["description"] = d.Get("description").(string) - instanceTemplate["properties"] = instanceProperties - instanceTemplate["name"] = itName + instanceTemplate := map[string]interface{}{ + "properties": instanceProperties, + "name": itName, + } + if v := d.Get("description").(string); v != "" { + instanceTemplate["description"] = v + } url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/instanceTemplates") if err != nil { @@ -1420,7 +1542,7 @@ func resourceComputeRegionInstanceTemplateCreate(d *schema.ResourceData, meta in } func resourceComputeRegionInstanceTemplateUpdate(d *schema.ResourceData, meta interface{}) error { - // Only the field "labels" and "terraform_labels" is mutable + // Only the field "deletion_policy", "labels" and "terraform_labels" is mutable return resourceComputeRegionInstanceTemplateRead(d, meta) } @@ -1451,7 +1573,7 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte } {{- end }} - instanceTemplate, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", Project: project, @@ -1462,28 +1584,36 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ComputeRegionInstanceTemplate %q", d.Id())) } - instancePropertiesMap := instanceTemplate["properties"] + // Extract id (uint64) and selfLink before JSON roundtrip. + var numericId string + switch v := res["id"].(type) { + case string: + numericId = v + case float64: + numericId = fmt.Sprintf("%.0f", v) + default: + numericId = fmt.Sprintf("%v", v) + } + selfLink, _ := res["selfLink"].(string) + delete(res, "id") - instancePropertiesObj, err := json.Marshal(instancePropertiesMap) + resBytes, err := json.Marshal(res) if err != nil { - fmt.Println(err) - return err + return fmt.Errorf("Error marshaling instance template response: %s", err) } - - instanceProperties := compute.InstanceProperties{} - - if err := json.Unmarshal(instancePropertiesObj, &instanceProperties); err != nil { - fmt.Println(err) - return err + var instanceTemplate compute.InstanceTemplate + if err := json.Unmarshal(resBytes, &instanceTemplate); err != nil { + return fmt.Errorf("Error parsing instance template response: %s", err) } + instanceTemplate.SelfLink = selfLink // Set the metadata fingerprint if there is one. - if instanceProperties.Metadata != nil { - if err = d.Set("metadata_fingerprint", instanceProperties.Metadata.Fingerprint); err != nil { + if instanceTemplate.Properties.Metadata != nil { + if err = d.Set("metadata_fingerprint", instanceTemplate.Properties.Metadata.Fingerprint); err != nil { return fmt.Errorf("Error setting metadata_fingerprint: %s", err) } - md := instanceProperties.Metadata + md := instanceTemplate.Properties.Metadata _md := flattenMetadataBeta(md) @@ -1500,13 +1630,13 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte } } - if err = d.Set("numeric_id", instanceTemplate["id"]); err != nil { + if err = d.Set("numeric_id", numericId); err != nil { return fmt.Errorf("Error setting numeric_id: %s", err) } {{ if ne $.TargetVersionName `ga` -}} - if instanceProperties.PartnerMetadata != nil { - partnerMetadata, err := flattenPartnerMetadata(convertPartnerMetadataFromCompute(instanceProperties.PartnerMetadata)) + if instanceTemplate.Properties.PartnerMetadata != nil { + partnerMetadata, err := flattenPartnerMetadata(convertPartnerMetadataFromCompute(instanceTemplate.Properties.PartnerMetadata)) if err != nil { return fmt.Errorf("Error parsing partner metadata: %s", err) } @@ -1517,8 +1647,8 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte {{- end }} // Set the tags fingerprint if there is one. - if instanceProperties.Tags != nil { - if err = d.Set("tags_fingerprint", instanceProperties.Tags.Fingerprint); err != nil { + if instanceTemplate.Properties.Tags != nil { + if err = d.Set("tags_fingerprint", instanceTemplate.Properties.Tags.Fingerprint); err != nil { return fmt.Errorf("Error setting tags_fingerprint: %s", err) } } else { @@ -1526,28 +1656,28 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte return fmt.Errorf("Error setting tags_fingerprint: %s", err) } } - if instanceProperties.Labels != nil { - if err := tpgresource.SetLabels(instanceProperties.Labels, d, "labels"); err != nil { + if instanceTemplate.Properties.Labels != nil { + if err := tpgresource.SetLabels(instanceTemplate.Properties.Labels, d, "labels"); err != nil { return fmt.Errorf("Error setting labels: %s", err) } } - if err := tpgresource.SetLabels(instanceProperties.Labels, d, "terraform_labels"); err != nil { + if err := tpgresource.SetLabels(instanceTemplate.Properties.Labels, d, "terraform_labels"); err != nil { return fmt.Errorf("Error setting terraform_labels: %s", err) } - if err := d.Set("effective_labels", instanceProperties.Labels); err != nil { + if err := d.Set("effective_labels", instanceTemplate.Properties.Labels); err != nil { return fmt.Errorf("Error setting effective_labels: %s", err) } - if err = d.Set("self_link", instanceTemplate["selfLink"]); err != nil { + if err = d.Set("self_link", instanceTemplate.SelfLink); err != nil { return fmt.Errorf("Error setting self_link: %s", err) } - if err := d.Set("creation_timestamp", instanceTemplate["creationTimestamp"]); err != nil { + if err := d.Set("creation_timestamp", instanceTemplate.CreationTimestamp); err != nil { return fmt.Errorf("Error setting creation_timestamp: %s", err) } - if err = d.Set("name", instanceTemplate["name"]); err != nil { + if err = d.Set("name", instanceTemplate.Name); err != nil { return fmt.Errorf("Error setting name: %s", err) } - if instanceProperties.Disks != nil { - disks, err := flattenDisks(instanceProperties.Disks, d, project) + if instanceTemplate.Properties.Disks != nil { + disks, err := flattenDisks(instanceTemplate.Properties.Disks, d, project) if err != nil { return fmt.Errorf("error flattening disks: %s", err) } @@ -1555,34 +1685,34 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte return fmt.Errorf("Error setting disk: %s", err) } } - if err = d.Set("description", instanceTemplate["description"]); err != nil { + if err = d.Set("description", instanceTemplate.Description); err != nil { return fmt.Errorf("Error setting description: %s", err) } - if err = d.Set("machine_type", instanceProperties.MachineType); err != nil { + if err = d.Set("machine_type", instanceTemplate.Properties.MachineType); err != nil { return fmt.Errorf("Error setting machine_type: %s", err) } - if err = d.Set("min_cpu_platform", instanceProperties.MinCpuPlatform); err != nil { + if err = d.Set("min_cpu_platform", instanceTemplate.Properties.MinCpuPlatform); err != nil { return fmt.Errorf("Error setting min_cpu_platform: %s", err) } - if err = d.Set("can_ip_forward", instanceProperties.CanIpForward); err != nil { + if err = d.Set("can_ip_forward", instanceTemplate.Properties.CanIpForward); err != nil { return fmt.Errorf("Error setting can_ip_forward: %s", err) } - if err = d.Set("instance_description", instanceProperties.Description); err != nil { + if err = d.Set("instance_description", instanceTemplate.Properties.Description); err != nil { return fmt.Errorf("Error setting instance_description: %s", err) } - if err = d.Set("key_revocation_action_type", instanceProperties.KeyRevocationActionType); err != nil { + if err = d.Set("key_revocation_action_type", instanceTemplate.Properties.KeyRevocationActionType); err != nil { return fmt.Errorf("Error setting key_revocation_action_type: %s", err) } if err = d.Set("project", project); err != nil { return fmt.Errorf("Error setting project: %s", err) } - if err := d.Set("network_performance_config", flattenNetworkPerformanceConfig(instanceProperties.NetworkPerformanceConfig)); err != nil { + if err := d.Set("network_performance_config", flattenNetworkPerformanceConfig(instanceTemplate.Properties.NetworkPerformanceConfig)); err != nil { return err } - if instanceProperties.NetworkInterfaces != nil { - networkInterfaces, region, _, _, err := flattenNetworkInterfaces(d, config, instanceProperties.NetworkInterfaces) + if instanceTemplate.Properties.NetworkInterfaces != nil { + networkInterfaces, region, _, _, err := flattenNetworkInterfaces(d, config, instanceTemplate.Properties.NetworkInterfaces) if err != nil { return err } @@ -1596,8 +1726,8 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte } } } - if instanceProperties.Scheduling != nil { - scheduling := flattenScheduling(instanceProperties.Scheduling) + if instanceTemplate.Properties.Scheduling != nil { + scheduling := flattenScheduling(instanceTemplate.Properties.Scheduling) {{ if ne $.TargetVersionName `ga` }} // Workaroud: API doesn't update the scheduling.graceful_shutdown.max_duration.nanos field. // To avoid diff, we need to set the value from the state not from API response. @@ -1614,8 +1744,8 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte return fmt.Errorf("Error setting scheduling: %s", err) } } - if instanceProperties.Tags != nil { - if err = d.Set("tags", instanceProperties.Tags.Items); err != nil { + if instanceTemplate.Properties.Tags != nil { + if err = d.Set("tags", instanceTemplate.Properties.Tags.Items); err != nil { return fmt.Errorf("Error setting tags: %s", err) } } else { @@ -1623,57 +1753,69 @@ func resourceComputeRegionInstanceTemplateRead(d *schema.ResourceData, meta inte return fmt.Errorf("Error setting empty tags: %s", err) } } - if instanceProperties.ServiceAccounts != nil { - if err = d.Set("service_account", flattenServiceAccounts(instanceProperties.ServiceAccounts)); err != nil { + if instanceTemplate.Properties.ServiceAccounts != nil { + if err = d.Set("service_account", flattenServiceAccounts(instanceTemplate.Properties.ServiceAccounts)); err != nil { return fmt.Errorf("Error setting service_account: %s", err) } } - if instanceProperties.GuestAccelerators != nil { - if err = d.Set("guest_accelerator", flattenGuestAccelerators(instanceProperties.GuestAccelerators)); err != nil { + if instanceTemplate.Properties.GuestAccelerators != nil { + if err = d.Set("guest_accelerator", flattenGuestAccelerators(instanceTemplate.Properties.GuestAccelerators)); err != nil { return fmt.Errorf("Error setting guest_accelerator: %s", err) } } - if instanceProperties.ShieldedInstanceConfig != nil { - if err = d.Set("shielded_instance_config", flattenShieldedVmConfig(instanceProperties.ShieldedInstanceConfig)); err != nil { + if instanceTemplate.Properties.ShieldedInstanceConfig != nil { + if err = d.Set("shielded_instance_config", flattenShieldedVmConfig(instanceTemplate.Properties.ShieldedInstanceConfig)); err != nil { return fmt.Errorf("Error setting shielded_instance_config: %s", err) } } - if instanceProperties.ConfidentialInstanceConfig != nil { - if err = d.Set("confidential_instance_config", flattenConfidentialInstanceConfig(instanceProperties.ConfidentialInstanceConfig)); err != nil { + if instanceTemplate.Properties.ConfidentialInstanceConfig != nil { + if err = d.Set("confidential_instance_config", flattenConfidentialInstanceConfig(instanceTemplate.Properties.ConfidentialInstanceConfig)); err != nil { return fmt.Errorf("Error setting confidential_instance_config: %s", err) } } - if instanceProperties.AdvancedMachineFeatures != nil { - if err = d.Set("advanced_machine_features", flattenAdvancedMachineFeatures(instanceProperties.AdvancedMachineFeatures)); err != nil { + if instanceTemplate.Properties.AdvancedMachineFeatures != nil { + if err = d.Set("advanced_machine_features", flattenAdvancedMachineFeatures(instanceTemplate.Properties.AdvancedMachineFeatures)); err != nil { return fmt.Errorf("Error setting advanced_machine_features: %s", err) } } {{- if ne $.TargetVersionName "ga" }} - if instanceProperties.DisplayDevice != nil { - if err = d.Set("enable_display", flattenEnableDisplay(instanceProperties.DisplayDevice)); err != nil { + if instanceTemplate.Properties.DisplayDevice != nil { + if err = d.Set("enable_display", flattenEnableDisplay(instanceTemplate.Properties.DisplayDevice)); err != nil { return fmt.Errorf("Error setting enable_display: %s", err) } } {{- end }} - if instanceProperties.ResourcePolicies != nil { - if err = d.Set("resource_policies", instanceProperties.ResourcePolicies); err != nil { + if instanceTemplate.Properties.ResourcePolicies != nil { + if err = d.Set("resource_policies", instanceTemplate.Properties.ResourcePolicies); err != nil { return fmt.Errorf("Error setting resource_policies: %s", err) } } - if reservationAffinity := instanceProperties.ReservationAffinity; reservationAffinity != nil { + if reservationAffinity := instanceTemplate.Properties.ReservationAffinity; reservationAffinity != nil { if err = d.Set("reservation_affinity", flattenReservationAffinity(reservationAffinity)); err != nil { return fmt.Errorf("Error setting reservation_affinity: %s", err) } } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeRegionInstanceTemplateDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_meta.yaml.tmpl index 609bf832d441..d88dca520810 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_meta.yaml.tmpl @@ -129,6 +129,12 @@ fields: api_field: 'properties.networkInterfaces.aliasIpRanges.ipCidrRange' - field: 'network_interface.alias_ip_range.subnetwork_range_name' api_field: 'properties.networkInterfaces.aliasIpRanges.subnetworkRangeName' +{{- if ne $.TargetVersionName "ga" }} + - field: 'network_interface.alias_ipv6_range.ip_cidr_range' + api_field: 'properties.networkInterfaces.aliasIpv6Ranges.ipCidrRange' + - field: 'network_interface.alias_ipv6_range.subnetwork_range_name' + api_field: 'properties.networkInterfaces.aliasIpv6Ranges.subnetworkRangeName' +{{- end }} - field: 'network_interface.internal_ipv6_prefix_length' api_field: 'properties.networkInterfaces.internalIpv6PrefixLength' - field: 'network_interface.ipv6_access_config.external_ipv6' @@ -262,3 +268,5 @@ fields: api_field: 'properties.tags.fingerprint' - field: 'terraform_labels' provider_only: true + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_test.go.tmpl index 6e75493232ea..421c4dc4cdd5 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instance_template_test.go.tmpl @@ -2,7 +2,9 @@ package compute_test import ( +{{- if ne $.TargetVersionName `ga` }} "encoding/json" +{{- end }} "fmt" "reflect" "regexp" @@ -13,25 +15,20 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} -{{- if ne $.TargetVersionName "ga" }} - "google.golang.org/api/googleapi" -{{- end }} ) func TestAccComputeRegionInstanceTemplate_basic(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -63,7 +60,7 @@ func TestAccComputeRegionInstanceTemplate_basic(t *testing.T) { func TestAccComputeRegionInstanceTemplate_imageShorthand(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} context := map[string]interface{}{ "template": "tf-test-instance-template-" + acctest.RandString(t, 10), @@ -97,7 +94,7 @@ func TestAccComputeRegionInstanceTemplate_imageShorthand(t *testing.T) { func TestAccComputeRegionInstanceTemplate_metadataGceContainerDeclaration(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -126,7 +123,7 @@ func TestAccComputeRegionInstanceTemplate_metadataGceContainerDeclaration(t *tes func TestAccComputeRegionInstanceTemplate_preemptible(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -154,7 +151,7 @@ func TestAccComputeRegionInstanceTemplate_preemptible(t *testing.T) { func TestAccComputeRegionInstanceTemplate_IP(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -181,7 +178,7 @@ func TestAccComputeRegionInstanceTemplate_IP(t *testing.T) { func TestAccComputeRegionInstanceTemplate_IPv6(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -204,6 +201,35 @@ func TestAccComputeRegionInstanceTemplate_IPv6(t *testing.T) { }) } +{{ if ne $.TargetVersionName `ga` -}} +func TestAccComputeRegionInstanceTemplate_aliasIpv6Range(t *testing.T) { + t.Parallel() + + var instanceTemplate map[string]interface{} + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeRegionInstanceTemplateDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeRegionInstanceTemplate_aliasIpv6Range(acctest.RandString(t, 10)), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeRegionInstanceTemplateExists( + t, "google_compute_region_instance_template.foobar", &instanceTemplate), + testAccCheckComputeRegionInstanceTemplateHasAliasIpv6Range(&instanceTemplate, "/96"), + ), + }, + { + ResourceName: "google_compute_region_instance_template.foobar", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} +{{- end }} + func TestAccComputeRegionInstanceTemplate_networkTier(t *testing.T) { t.Parallel() @@ -227,7 +253,7 @@ func TestAccComputeRegionInstanceTemplate_networkTier(t *testing.T) { func TestAccComputeRegionInstanceTemplate_networkIP(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} networkIP := "10.128.0.2" acctest.VcrTest(t, resource.TestCase{ @@ -257,7 +283,7 @@ func TestAccComputeRegionInstanceTemplate_networkIP(t *testing.T) { func TestAccComputeRegionInstanceTemplate_networkIPAddress(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} ipAddress := "10.128.0.2" acctest.VcrTest(t, resource.TestCase{ @@ -363,7 +389,7 @@ func TestAccComputeRegionInstanceTemplate_diskIopsThroughput(t *testing.T) { func TestAccComputeRegionInstanceTemplate_subnet_auto(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} network := "tf-test-network-" + acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ @@ -391,7 +417,7 @@ func TestAccComputeRegionInstanceTemplate_subnet_auto(t *testing.T) { func TestAccComputeRegionInstanceTemplate_subnet_custom(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -420,7 +446,7 @@ func TestAccComputeRegionInstanceTemplate_subnet_xpn(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} org := envvar.GetTestOrgFromEnv(t) billingId := envvar.GetTestBillingAccountFromEnv(t) projectName := fmt.Sprintf("tf-testxpn-%d", time.Now().Unix()) @@ -449,7 +475,7 @@ func TestAccComputeRegionInstanceTemplate_subnet_xpn(t *testing.T) { func TestAccComputeRegionInstanceTemplate_metadata_startup_script(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -471,7 +497,7 @@ func TestAccComputeRegionInstanceTemplate_metadata_startup_script(t *testing.T) func TestAccComputeRegionInstanceTemplate_primaryAliasIpRange(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -497,7 +523,7 @@ func TestAccComputeRegionInstanceTemplate_primaryAliasIpRange(t *testing.T) { func TestAccComputeRegionInstanceTemplate_secondaryAliasIpRange(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -523,7 +549,7 @@ func TestAccComputeRegionInstanceTemplate_secondaryAliasIpRange(t *testing.T) { func TestAccComputeRegionInstanceTemplate_guestAccelerator(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -550,7 +576,7 @@ func TestAccComputeRegionInstanceTemplate_guestAccelerator(t *testing.T) { func TestAccComputeRegionInstanceTemplate_guestAcceleratorSkip(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -572,7 +598,7 @@ func TestAccComputeRegionInstanceTemplate_guestAcceleratorSkip(t *testing.T) { func TestAccComputeRegionInstanceTemplate_minCpuPlatform(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -618,7 +644,7 @@ func TestAccComputeRegionInstanceTemplate_soleTenantNodeAffinities(t *testing.T) func TestAccComputeRegionInstanceTemplate_instanceResourcePolicies(t *testing.T) { t.Parallel() - var template compute.InstanceTemplate + var template map[string]interface{} var policyName = "tf-test-policy-" + acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ @@ -645,7 +671,7 @@ func TestAccComputeRegionInstanceTemplate_instanceResourcePolicies(t *testing.T) func TestAccComputeRegionInstanceTemplate_instanceResourcePoliciesSpread(t *testing.T) { t.Parallel() - var template compute.InstanceTemplate + var template map[string]interface{} var policyName = "tf-test-policy-" + acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ @@ -673,7 +699,7 @@ func TestAccComputeRegionInstanceTemplate_instanceResourcePoliciesSpread(t *test func TestAccComputeRegionInstanceTemplate_reservationAffinities(t *testing.T) { t.Parallel() - var template compute.InstanceTemplate + var template map[string]interface{} var templateName = acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ @@ -724,7 +750,7 @@ func TestAccComputeRegionInstanceTemplate_reservationAffinities(t *testing.T) { func TestAccComputeRegionInstanceTemplate_shieldedVmConfig1(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -750,7 +776,7 @@ func TestAccComputeRegionInstanceTemplate_shieldedVmConfig1(t *testing.T) { func TestAccComputeRegionInstanceTemplate_shieldedVmConfig2(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -776,8 +802,8 @@ func TestAccComputeRegionInstanceTemplate_shieldedVmConfig2(t *testing.T) { func TestAccComputeRegionInstanceTemplate_ConfidentialInstanceConfigMain(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - var instanceTemplate2 compute.InstanceTemplate + var instanceTemplate map[string]interface{} + var instanceTemplate2 map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -816,7 +842,7 @@ func TestAccComputeRegionInstanceTemplate_ConfidentialInstanceConfigMain(t *test func TestAccComputeRegionInstanceTemplate_AdvancedMachineFeatures(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -836,7 +862,7 @@ func TestAccComputeRegionInstanceTemplate_AdvancedMachineFeatures(t *testing.T) func TestAccComputeRegionInstanceTemplate_performanceMonitoringUnit(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-instance-template-%s", acctest.RandString(t, 10)), "performance_monitoring_unit": "STANDARD", @@ -882,7 +908,7 @@ func TestAccComputeRegionInstanceTemplate_performanceMonitoringUnit(t *testing.T func TestAccComputeRegionInstanceTemplate_enableUefiNetworking(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-instance-template-%s", acctest.RandString(t, 10)), "enable_uefi_networking": "false", @@ -948,7 +974,7 @@ func TestAccComputeRegionInstanceTemplate_enableDisplay(t *testing.T) { func TestAccComputeRegionInstanceTemplate_maintenance_interval(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1076,7 +1102,7 @@ func TestAccComputeRegionInstanceTemplate_imageResourceTest(t *testing.T) { func TestAccComputeRegionInstanceTemplate_diskResourcePolicies(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} policyName := "tf-test-policy-" + acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ @@ -1104,7 +1130,7 @@ func TestAccComputeRegionInstanceTemplate_diskResourcePolicies(t *testing.T) { func TestAccComputeRegionInstanceTemplate_nictype_update(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} var instanceTemplateName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1133,7 +1159,7 @@ func TestAccComputeRegionInstanceTemplate_nictype_update(t *testing.T) { func TestAccComputeRegionInstanceTemplate_queueCount(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} var instanceTemplateName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1155,7 +1181,7 @@ func TestAccComputeRegionInstanceTemplate_queueCount(t *testing.T) { func TestAccComputeRegionInstanceTemplate_managedEnvoy(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1182,7 +1208,7 @@ func TestAccComputeRegionInstanceTemplate_managedEnvoy(t *testing.T) { func TestAccComputeRegionInstanceTemplate_spot(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -1210,11 +1236,11 @@ func TestAccComputeRegionInstanceTemplate_spot(t *testing.T) { func TestAccComputeRegionInstanceTemplate_spot_maxRunDuration(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - var expectedMaxRunDuration = compute.Duration{} - // Define in testAccComputeRegionInstanceTemplate_spot_maxRunDuration - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + var instanceTemplate map[string]interface{} + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "60", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1245,11 +1271,11 @@ func TestAccComputeRegionInstanceTemplate_spot_maxRunDuration(t *testing.T) { func TestAccComputeRegionInstanceTemplate_maxRunDuration_onInstanceStopAction(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - var expectedMaxRunDuration = compute.Duration{} - // Define in testAccComputeRegionInstanceTemplate_spot - expectedMaxRunDuration.Nanos = 123 - expectedMaxRunDuration.Seconds = 60 + var instanceTemplate map[string]interface{} + expectedMaxRunDuration := map[string]interface{}{ + "nanos": float64(123), + "seconds": "60", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1280,7 +1306,7 @@ func TestAccComputeRegionInstanceTemplate_instanceTerminationAction_terminationT acctest.SkipIfVcr(t) t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} now := time.Now().UTC() terminationTime := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 9999, now.Location()).Format(time.RFC3339) var instanceTerminationAction = "STOP" @@ -1311,11 +1337,11 @@ func TestAccComputeRegionInstanceTemplate_instanceTerminationAction_terminationT func TestAccComputeRegionInstanceTemplate_localSsdRecoveryTimeout(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - var expectedLocalSsdRecoveryTimeout = compute.Duration{} - // Define in testAccComputeRegionInstanceTemplate_spot - expectedLocalSsdRecoveryTimeout.Nanos = 0 - expectedLocalSsdRecoveryTimeout.Seconds = 3600 + var instanceTemplate map[string]interface{} + expectedLocalSsdRecoveryTimeout := map[string]interface{}{ + "nanos": float64(0), + "seconds": "3600", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1343,11 +1369,10 @@ func TestAccComputeRegionInstanceTemplate_localSsdRecoveryTimeout(t *testing.T) func TestAccComputeRegionalInstanceTemplate_partnerMetadata(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} var namespace = "test.compute.googleapis.com" - expectedPartnerMetadata := make(map[string]compute.StructuredEntries) - expectedPartnerMetadata[namespace] = compute.StructuredEntries{ - Entries: googleapi.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), + expectedPartnerMetadata := map[string]json.RawMessage{ + namespace: json.RawMessage(`{"key1": "value1", "key2": 2,"key3": {"key31":"value31"}}`), } acctest.VcrTest(t, resource.TestCase{ @@ -1378,8 +1403,8 @@ func TestAccComputeRegionalInstanceTemplate_partnerMetadata(t *testing.T) { func TestAccComputeRegionInstanceTemplate_diskEncryptionKey(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + var instanceTemplate map[string]interface{} + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "kms_key_self_link": kmsKey.CryptoKey.Name, "template_name": fmt.Sprintf("tf-test-instance-template-%s", acctest.RandString(t, 10)), @@ -1404,8 +1429,8 @@ func TestAccComputeRegionInstanceTemplate_diskEncryptionKey(t *testing.T) { func TestAccComputeRegionInstanceTemplate_sourceSnapshotEncryptionKey(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + var instanceTemplate map[string]interface{} + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "kms_ring_name": tpgresource.GetResourceNameFromSelfLink(kmsKey.KeyRing.Name), @@ -1467,8 +1492,8 @@ func TestAccComputeRegionInstanceTemplate_sourceSnapshotEncryptionKey(t *testing func TestAccComputeRegionInstanceTemplate_sourceImageEncryptionKey(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate - kmsKey := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + var instanceTemplate map[string]interface{} + kmsKey := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "kms_ring_name": tpgresource.GetResourceNameFromSelfLink(kmsKey.KeyRing.Name), @@ -1529,7 +1554,7 @@ func TestAccComputeRegionInstanceTemplate_sourceImageEncryptionKey(t *testing.T) func TestAccComputeRegionInstanceTemplate_resourceManagerTags(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} var instanceTemplateName = fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) context := map[string]interface{}{ "project": envvar.GetTestProjectFromEnv(), @@ -1555,7 +1580,7 @@ func TestAccComputeRegionInstanceTemplate_resourceManagerTags(t *testing.T) { func TestAccComputeRegionInstanceTemplate_keyRevocationActionType(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} context_1 := map[string]interface{}{ "instance_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "key_revocation_action_type": `"NONE"`, @@ -1606,7 +1631,7 @@ func TestAccComputeRegionInstanceTemplate_keyRevocationActionType(t *testing.T) func TestAccComputeRegionInstanceTemplate_gracefulShutdown(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) acceptableByApi_1 := map[string]interface{}{ @@ -1677,7 +1702,7 @@ func TestAccComputeRegionInstanceTemplate_gracefulShutdown(t *testing.T) { func TestAccComputeRegionInstanceTemplate_schedulingSkipGuestOSShutdown(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) variant_1 := map[string]interface{}{ @@ -1711,7 +1736,7 @@ func TestAccComputeRegionInstanceTemplate_schedulingSkipGuestOSShutdown(t *testi func TestAccComputeRegionInstanceTemplate_schedulingPreemptionNoticeDuration(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} instanceName := fmt.Sprintf("tf-test-instance-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -1741,7 +1766,7 @@ func TestAccComputeRegionInstanceTemplate_schedulingPreemptionNoticeDuration(t * func TestAccComputeRegionInstanceTemplate_GuestOsFeatures(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} context := map[string]interface{}{ "template_name": fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)), "guest_os_features": `["UEFI_COMPATIBLE", "VIRTIO_SCSI_MULTIQUEUE", "GVNIC", "IDPF"]`, @@ -1771,11 +1796,11 @@ func TestAccComputeRegionInstanceTemplate_GuestOsFeatures(t *testing.T) { func TestAccComputeRegionInstanceTemplate_networkAttachment(t *testing.T) { t.Parallel() - network := acctest.BootstrapSharedTestNetwork(t, "attachment-network") - subnet := acctest.BootstrapSubnet(t, "tf-test-subnet", network) + network := tpgcompute.BootstrapSharedTestNetwork(t, "attachment-network") + subnet := tpgcompute.BootstrapSubnet(t, "tf-test-subnet", network) region := envvar.GetTestRegionFromEnv() - networkAttachmentShortname := acctest.BootstrapNetworkAttachment(t, "tf-test-attachment", subnet) + networkAttachmentShortname := tpgcompute.BootstrapNetworkAttachment(t, "tf-test-attachment", subnet) networkAttachment := fmt.Sprintf("projects/%s/regions/%s/networkAttachments/%s", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), networkAttachmentShortname) context := map[string]interface{}{ @@ -1958,7 +1983,7 @@ func testAccCheckComputeRegionInstanceTemplateDestroyProducer(t *testing.T) func func TestAccComputeRegionInstanceTemplate_storagePool(t *testing.T) { t.Parallel() - var instanceTemplate compute.InstanceTemplate + var instanceTemplate map[string]interface{} suffix := acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ @@ -2026,10 +2051,10 @@ func testAccCheckComputeRegionInstanceTemplateExists(t *testing.T, n string, ins panic("Attempted to check existence of Instance template that was nil.") } - return testAccCheckComputeRegionInstanceTemplateExistsInProject(t, n, envvar.GetTestProjectFromEnv(), instanceTemplate.(*compute.InstanceTemplate)) + return testAccCheckComputeRegionInstanceTemplateExistsInProject(t, n, envvar.GetTestProjectFromEnv(), instanceTemplate.(*map[string]interface{})) } -func testAccCheckComputeRegionInstanceTemplateExistsInProject(t *testing.T, n, p string, instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateExistsInProject(t *testing.T, n, p string, instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -2046,6 +2071,9 @@ func testAccCheckComputeRegionInstanceTemplateExistsInProject(t *testing.T, n, p templateName := splits[len(splits)-1] url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/instanceTemplates/"+templateName) + if err != nil { + return err + } billingProject := "" @@ -2070,58 +2098,82 @@ func testAccCheckComputeRegionInstanceTemplateExistsInProject(t *testing.T, n, p return err } - foundObj, err := json.Marshal(found) - if err != nil { - fmt.Println(err) - return err + foundName, _ := found["name"].(string) + if foundName != templateName { + return fmt.Errorf("Instance template not found") } - instanceTemplateFound := compute.InstanceTemplate{} + *instanceTemplate = found - if err := json.Unmarshal(foundObj, &instanceTemplateFound); err != nil { - fmt.Println(err) - return err - } - - if instanceTemplateFound.Name != templateName { - return fmt.Errorf("Instance template not found") - } + return nil + } +} - *instanceTemplate = instanceTemplateFound +func instanceTemplateProperties(instanceTemplate *map[string]interface{}) map[string]interface{} { + if instanceTemplate == nil { + return nil + } + props, _ := (*instanceTemplate)["properties"].(map[string]interface{}) + return props +} +func instanceTemplateNetworkInterfaces(instanceTemplate *map[string]interface{}) []interface{} { + props := instanceTemplateProperties(instanceTemplate) + if props == nil { return nil } + nics, _ := props["networkInterfaces"].([]interface{}) + return nics } func testAccCheckComputeRegionInstanceTemplateMetadata( - instanceTemplate *compute.InstanceTemplate, + instanceTemplate *map[string]interface{}, k string, v string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Metadata == nil { + props := instanceTemplateProperties(instanceTemplate) + metadata, ok := props["metadata"].(map[string]interface{}) + if !ok { return fmt.Errorf("no metadata") } + items, _ := metadata["items"].([]interface{}) - for _, item := range instanceTemplate.Properties.Metadata.Items { - if k != item.Key { + for _, rawItem := range items { + item, ok := rawItem.(map[string]interface{}) + if !ok { + continue + } + key, _ := item["key"].(string) + if k != key { continue } - if item.Value != nil && v == *item.Value { + value, hasValue := item["value"].(string) + if hasValue && v == value { return nil } - return fmt.Errorf("bad value for %s: %s", k, *item.Value) + return fmt.Errorf("bad value for %s: %s", k, value) } return fmt.Errorf("metadata not found: %s", k) } } -func testAccCheckComputeRegionInstanceTemplateNetwork(instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateNetwork(instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instanceTemplate.Properties.NetworkInterfaces { - for _, c := range i.AccessConfigs { - if c.NatIP == "" { + for _, rawNic := range instanceTemplateNetworkInterfaces(instanceTemplate) { + nic, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + accessConfigs, _ := nic["accessConfigs"].([]interface{}) + for _, rawAc := range accessConfigs { + ac, ok := rawAc.(map[string]interface{}) + if !ok { + continue + } + natIP, _ := ac["natIP"].(string) + if natIP == "" { return fmt.Errorf("no NAT IP") } } @@ -2131,11 +2183,16 @@ func testAccCheckComputeRegionInstanceTemplateNetwork(instanceTemplate *compute. } } -func testAccCheckComputeRegionInstanceTemplateNetworkName(instanceTemplate *compute.InstanceTemplate, network string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateNetworkName(instanceTemplate *map[string]interface{}, network string) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instanceTemplate.Properties.NetworkInterfaces { - if !strings.Contains(i.Network, network) { - return fmt.Errorf("Network doesn't match expected value, Expected: %s Actual: %s", network, i.Network[strings.LastIndex("/", i.Network)+1:]) + for _, rawNic := range instanceTemplateNetworkInterfaces(instanceTemplate) { + nic, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + netVal, _ := nic["network"].(string) + if !strings.Contains(netVal, network) { + return fmt.Errorf("Network doesn't match expected value, Expected: %s Actual: %s", network, netVal[strings.LastIndex("/", netVal)+1:]) } } @@ -2143,10 +2200,15 @@ func testAccCheckComputeRegionInstanceTemplateNetworkName(instanceTemplate *comp } } -func testAccCheckComputeRegionInstanceTemplateSubnetwork(instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateSubnetwork(instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, i := range instanceTemplate.Properties.NetworkInterfaces { - if i.Subnetwork == "" { + for _, rawNic := range instanceTemplateNetworkInterfaces(instanceTemplate) { + nic, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + subnet, _ := nic["subnetwork"].(string) + if subnet == "" { return fmt.Errorf("no subnet") } } @@ -2156,23 +2218,30 @@ func testAccCheckComputeRegionInstanceTemplateSubnetwork(instanceTemplate *compu } {{ if ne $.TargetVersionName `ga` -}} -func testAccCheckComputeRegionInstanceTemplateMaintenanceInterval(instanceTemplate *compute.InstanceTemplate, maintenance_interval string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateMaintenanceInterval(instanceTemplate *map[string]interface{}, maintenance_interval string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Scheduling.MaintenanceInterval != maintenance_interval { - return fmt.Errorf("Expected maintenance interval value %v, got %v", maintenance_interval, instanceTemplate.Properties.Scheduling.MaintenanceInterval) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actual, _ := scheduling["maintenanceInterval"].(string) + if actual != maintenance_interval { + return fmt.Errorf("Expected maintenance interval value %v, got %v", maintenance_interval, actual) } return nil } } {{- end }} -func testAccCheckComputeRegionInstanceTemplateTag(instanceTemplate *compute.InstanceTemplate, n string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateTag(instanceTemplate *map[string]interface{}, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Tags == nil { + props := instanceTemplateProperties(instanceTemplate) + tags, ok := props["tags"].(map[string]interface{}) + if !ok { return fmt.Errorf("no tags") } + items, _ := tags["items"].([]interface{}) - for _, k := range instanceTemplate.Properties.Tags.Items { + for _, rawItem := range items { + k, _ := rawItem.(string) if k == n { return nil } @@ -2182,56 +2251,74 @@ func testAccCheckComputeRegionInstanceTemplateTag(instanceTemplate *compute.Inst } } -func testAccCheckComputeRegionInstanceTemplatePreemptible(instanceTemplate *compute.InstanceTemplate, preemptible bool) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplatePreemptible(instanceTemplate *map[string]interface{}, preemptible bool) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Scheduling.Preemptible != preemptible { - return fmt.Errorf("Expected preemptible value %v, got %v", preemptible, instanceTemplate.Properties.Scheduling.Preemptible) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actual, _ := scheduling["preemptible"].(bool) + if actual != preemptible { + return fmt.Errorf("Expected preemptible value %v, got %v", preemptible, actual) } return nil } } -func testAccCheckComputeRegionInstanceTemplateProvisioningModel(instanceTemplate *compute.InstanceTemplate, provisioning_model string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateProvisioningModel(instanceTemplate *map[string]interface{}, provisioning_model string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Scheduling.ProvisioningModel != provisioning_model { - return fmt.Errorf("Expected provisioning_model %v, got %v", provisioning_model, instanceTemplate.Properties.Scheduling.ProvisioningModel) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actual, _ := scheduling["provisioningModel"].(string) + if actual != provisioning_model { + return fmt.Errorf("Expected provisioning_model %v, got %v", provisioning_model, actual) } return nil } } -func testAccCheckComputeRegionInstanceTemplateInstanceTerminationAction(instanceTemplate *compute.InstanceTemplate, instance_termination_action string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateInstanceTerminationAction(instanceTemplate *map[string]interface{}, instance_termination_action string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Scheduling.InstanceTerminationAction != instance_termination_action { - return fmt.Errorf("Expected instance_termination_action %v, got %v", instance_termination_action, instanceTemplate.Properties.Scheduling.InstanceTerminationAction) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actual, _ := scheduling["instanceTerminationAction"].(string) + if actual != instance_termination_action { + return fmt.Errorf("Expected instance_termination_action %v, got %v", instance_termination_action, actual) } return nil } } -func testAccCheckComputeRegionInstanceTemplateInstanceTerminationTime(instanceTemplate *compute.InstanceTemplate, termination_time string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateInstanceTerminationTime(instanceTemplate *map[string]interface{}, termination_time string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Scheduling.TerminationTime != termination_time { - return fmt.Errorf("Expected instance_termination_time %v, got %v", termination_time, instanceTemplate.Properties.Scheduling.TerminationTime) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actual, _ := scheduling["terminationTime"].(string) + if actual != termination_time { + return fmt.Errorf("Expected instance_termination_time %v, got %v", termination_time, actual) } return nil } } -func testAccCheckComputeRegionInstanceTemplateMaxRunDuration(instanceTemplate *compute.InstanceTemplate, instance_max_run_duration_want compute.Duration) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateMaxRunDuration(instanceTemplate *map[string]interface{}, instance_max_run_duration_want map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if !reflect.DeepEqual(*instanceTemplate.Properties.Scheduling.MaxRunDuration, instance_max_run_duration_want) { - return fmt.Errorf("gExpected instance_termination_action: %#v; got %#v", instance_max_run_duration_want, instanceTemplate.Properties.Scheduling.MaxRunDuration) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + maxRun, _ := scheduling["maxRunDuration"].(map[string]interface{}) + if !reflect.DeepEqual(maxRun, instance_max_run_duration_want) { + return fmt.Errorf("gExpected instance_termination_action: %#v; got %#v", instance_max_run_duration_want, maxRun) } return nil } } -func testAccCheckComputeRegionInstanceTemplateLocalSsdRecoveryTimeout(instanceTemplate *compute.InstanceTemplate, instance_local_ssd_recovery_timeout_want compute.Duration) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateLocalSsdRecoveryTimeout(instanceTemplate *map[string]interface{}, instance_local_ssd_recovery_timeout_want map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if !reflect.DeepEqual(*instanceTemplate.Properties.Scheduling.LocalSsdRecoveryTimeout, instance_local_ssd_recovery_timeout_want) { - return fmt.Errorf("gExpected local_ssd_recovery_timeout: %#v; got %#v", instance_local_ssd_recovery_timeout_want, instanceTemplate.Properties.Scheduling.LocalSsdRecoveryTimeout) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actual, _ := scheduling["localSsdRecoveryTimeout"].(map[string]interface{}) + if !reflect.DeepEqual(actual, instance_local_ssd_recovery_timeout_want) { + return fmt.Errorf("gExpected local_ssd_recovery_timeout: %#v; got %#v", instance_local_ssd_recovery_timeout_want, actual) } return nil @@ -2239,24 +2326,28 @@ func testAccCheckComputeRegionInstanceTemplateLocalSsdRecoveryTimeout(instanceTe } {{ if ne $.TargetVersionName `ga` -}} -func testAccCheckComputeRegionalInstanceTemplatePartnerMetadata(instanceTemplate *compute.InstanceTemplate, expectedPartnerMetadata map[string]compute.StructuredEntries) resource.TestCheckFunc { +func testAccCheckComputeRegionalInstanceTemplatePartnerMetadata(instanceTemplate *map[string]interface{}, expectedPartnerMetadata map[string]json.RawMessage) resource.TestCheckFunc { return func(s *terraform.State) error { if instanceTemplate == nil { return fmt.Errorf("instance template is nil") } - if instanceTemplate.Properties.PartnerMetadata == nil { + props := instanceTemplateProperties(instanceTemplate) + partnerMetadata, ok := props["partnerMetadata"].(map[string]interface{}) + if !ok { return fmt.Errorf("no partner metadata") } expectedPartnerMetadataMap := make(map[string]interface{}) acutalPartnerMetadataMap := make(map[string]interface{}) - for key, value := range instanceTemplate.Properties.PartnerMetadata { - var jsonMap map[string]interface{} - json.Unmarshal(value.Entries, jsonMap) - acutalPartnerMetadataMap[key] = jsonMap + for key, value := range partnerMetadata { + entry, _ := value.(map[string]interface{}) + entries, _ := entry["entries"] + acutalPartnerMetadataMap[key] = entries } for key, value := range expectedPartnerMetadata { var jsonMap map[string]interface{} - json.Unmarshal(value.Entries, jsonMap) + if err := json.Unmarshal(value, &jsonMap); err != nil { + return fmt.Errorf("error unmarshaling expected partner metadata for key %s: %s", key, err) + } expectedPartnerMetadataMap[key] = jsonMap } if !reflect.DeepEqual(acutalPartnerMetadataMap, expectedPartnerMetadataMap) { @@ -2268,47 +2359,63 @@ func testAccCheckComputeRegionalInstanceTemplatePartnerMetadata(instanceTemplate } {{- end }} -func testAccCheckComputeRegionInstanceTemplateAutomaticRestart(instanceTemplate *compute.InstanceTemplate, automaticRestart bool) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateAutomaticRestart(instanceTemplate *map[string]interface{}, automaticRestart bool) resource.TestCheckFunc { return func(s *terraform.State) error { - ar := instanceTemplate.Properties.Scheduling.AutomaticRestart - if ar == nil { + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + ar, ok := scheduling["automaticRestart"].(bool) + if !ok { return fmt.Errorf("Expected to see a value for AutomaticRestart, but got nil") } - if *ar != automaticRestart { + if ar != automaticRestart { return fmt.Errorf("Expected automatic restart value %v, got %v", automaticRestart, ar) } return nil } } -func testAccCheckComputeRegionInstanceTemplateStartupScript(instanceTemplate *compute.InstanceTemplate, n string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateStartupScript(instanceTemplate *map[string]interface{}, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.Metadata == nil && n == "" { + props := instanceTemplateProperties(instanceTemplate) + metadata, hasMetadata := props["metadata"].(map[string]interface{}) + if !hasMetadata && n == "" { return nil - } else if instanceTemplate.Properties.Metadata == nil && n != "" { + } else if !hasMetadata && n != "" { return fmt.Errorf("Expected metadata.startup-script to be '%s', metadata wasn't set at all", n) } - for _, item := range instanceTemplate.Properties.Metadata.Items { - if item.Key != "startup-script" { + items, _ := metadata["items"].([]interface{}) + for _, rawItem := range items { + item, ok := rawItem.(map[string]interface{}) + if !ok { + continue + } + key, _ := item["key"].(string) + if key != "startup-script" { continue } - if item.Value != nil && *item.Value == n { + value, hasValue := item["value"].(string) + if hasValue && value == n { return nil - } else if item.Value == nil && n == "" { + } else if !hasValue && n == "" { return nil - } else if item.Value == nil && n != "" { + } else if !hasValue && n != "" { return fmt.Errorf("Expected metadata.startup-script to be '%s', wasn't set", n) - } else if *item.Value != n { - return fmt.Errorf("Expected metadata.startup-script to be '%s', got '%s'", n, *item.Value) + } else if value != n { + return fmt.Errorf("Expected metadata.startup-script to be '%s', got '%s'", n, value) } } return fmt.Errorf("This should never be reached.") } } -func testAccCheckComputeRegionInstanceTemplateNetworkIP(n, networkIP string, instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateNetworkIP(n, networkIP string, instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - ip := instanceTemplate.Properties.NetworkInterfaces[0].NetworkIP + nics := instanceTemplateNetworkInterfaces(instanceTemplate) + if len(nics) == 0 { + return fmt.Errorf("no network interfaces") + } + nic, _ := nics[0].(map[string]interface{}) + ip, _ := nic["networkIP"].(string) err := resource.TestCheckResourceAttr(n, "network_interface.0.network_ip", ip)(s) if err != nil { return err @@ -2317,9 +2424,14 @@ func testAccCheckComputeRegionInstanceTemplateNetworkIP(n, networkIP string, ins } } -func testAccCheckComputeRegionInstanceTemplateNetworkIPAddress(n, ipAddress string, instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateNetworkIPAddress(n, ipAddress string, instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - ip := instanceTemplate.Properties.NetworkInterfaces[0].NetworkIP + nics := instanceTemplateNetworkInterfaces(instanceTemplate) + if len(nics) == 0 { + return fmt.Errorf("no network interfaces") + } + nic, _ := nics[0].(map[string]interface{}) + ip, _ := nic["networkIP"].(string) err := resource.TestCheckResourceAttr(n, "network_interface.0.network_ip", ip)(s) if err != nil { return err @@ -2328,24 +2440,63 @@ func testAccCheckComputeRegionInstanceTemplateNetworkIPAddress(n, ipAddress stri } } -func testAccCheckComputeRegionInstanceTemplateContainsLabel(instanceTemplate *compute.InstanceTemplate, key string, value string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateContainsLabel(instanceTemplate *map[string]interface{}, key string, value string) resource.TestCheckFunc { return func(s *terraform.State) error { - v, ok := instanceTemplate.Properties.Labels[key] + props := instanceTemplateProperties(instanceTemplate) + labels, _ := props["labels"].(map[string]interface{}) + v, ok := labels[key] if !ok { return fmt.Errorf("Expected label with key '%s' not found", key) } - if v != value { - return fmt.Errorf("Incorrect label value for key '%s': expected '%s' but found '%s'", key, value, v) + vStr, _ := v.(string) + if vStr != value { + return fmt.Errorf("Incorrect label value for key '%s': expected '%s' but found '%s'", key, value, vStr) } return nil } } +{{- if ne $.TargetVersionName `ga` }} +func testAccCheckComputeRegionInstanceTemplateHasAliasIpv6Range(instanceTemplate *map[string]interface{}, iPCidrRange string) resource.TestCheckFunc { + return func(s *terraform.State) error { + for _, rawNic := range instanceTemplateNetworkInterfaces(instanceTemplate) { + nic, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + aliasRanges, _ := nic["aliasIpv6Ranges"].([]interface{}) + for _, rawRange := range aliasRanges { + aliasIpRange, ok := rawRange.(map[string]interface{}) + if !ok { + continue + } + ipRange, _ := aliasIpRange["ipCidrRange"].(string) + if ipRange == iPCidrRange || tpgcompute.IpCidrRangeDiffSuppress("ip_cidr_range", ipRange, iPCidrRange, nil) { + return nil + } + } + } + + return fmt.Errorf("Alias ipv6 range with cidr %s not present", iPCidrRange) + } +} +{{- end }} -func testAccCheckComputeRegionInstanceTemplateHasAliasIpRange(instanceTemplate *compute.InstanceTemplate, subnetworkRangeName, iPCidrRange string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasAliasIpRange(instanceTemplate *map[string]interface{}, subnetworkRangeName, iPCidrRange string) resource.TestCheckFunc { return func(s *terraform.State) error { - for _, networkInterface := range instanceTemplate.Properties.NetworkInterfaces { - for _, aliasIpRange := range networkInterface.AliasIpRanges { - if aliasIpRange.SubnetworkRangeName == subnetworkRangeName && (aliasIpRange.IpCidrRange == iPCidrRange || tpgcompute.IpCidrRangeDiffSuppress("ip_cidr_range", aliasIpRange.IpCidrRange, iPCidrRange, nil)) { + for _, rawNic := range instanceTemplateNetworkInterfaces(instanceTemplate) { + nic, ok := rawNic.(map[string]interface{}) + if !ok { + continue + } + aliasRanges, _ := nic["aliasIpRanges"].([]interface{}) + for _, rawRange := range aliasRanges { + aliasIpRange, ok := rawRange.(map[string]interface{}) + if !ok { + continue + } + rangeName, _ := aliasIpRange["subnetworkRangeName"].(string) + ipRange, _ := aliasIpRange["ipCidrRange"].(string) + if rangeName == subnetworkRangeName && (ipRange == iPCidrRange || tpgcompute.IpCidrRangeDiffSuppress("ip_cidr_range", ipRange, iPCidrRange, nil)) { return nil } } @@ -2355,27 +2506,33 @@ func testAccCheckComputeRegionInstanceTemplateHasAliasIpRange(instanceTemplate * } } -func testAccCheckComputeRegionInstanceTemplateHasGuestAccelerator(instanceTemplate *compute.InstanceTemplate, acceleratorType string, acceleratorCount int64) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasGuestAccelerator(instanceTemplate *map[string]interface{}, acceleratorType string, acceleratorCount int64) resource.TestCheckFunc { return func(s *terraform.State) error { - if len(instanceTemplate.Properties.GuestAccelerators) != 1 { + props := instanceTemplateProperties(instanceTemplate) + accelerators, _ := props["guestAccelerators"].([]interface{}) + if len(accelerators) != 1 { return fmt.Errorf("Expected only one guest accelerator") } - - if !strings.HasSuffix(instanceTemplate.Properties.GuestAccelerators[0].AcceleratorType, acceleratorType) { - return fmt.Errorf("Wrong accelerator type: expected %v, got %v", acceleratorType, instanceTemplate.Properties.GuestAccelerators[0].AcceleratorType) + accel, _ := accelerators[0].(map[string]interface{}) + accelType, _ := accel["acceleratorType"].(string) + if !strings.HasSuffix(accelType, acceleratorType) { + return fmt.Errorf("Wrong accelerator type: expected %v, got %v", acceleratorType, accelType) } - if instanceTemplate.Properties.GuestAccelerators[0].AcceleratorCount != acceleratorCount { - return fmt.Errorf("Wrong accelerator acceleratorCount: expected %d, got %d", acceleratorCount, instanceTemplate.Properties.GuestAccelerators[0].AcceleratorCount) + accelCountVal, _ := accel["acceleratorCount"].(float64) + if int64(accelCountVal) != acceleratorCount { + return fmt.Errorf("Wrong accelerator acceleratorCount: expected %d, got %d", acceleratorCount, int64(accelCountVal)) } return nil } } -func testAccCheckComputeRegionInstanceTemplateLacksGuestAccelerator(instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateLacksGuestAccelerator(instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if len(instanceTemplate.Properties.GuestAccelerators) > 0 { + props := instanceTemplateProperties(instanceTemplate) + accelerators, _ := props["guestAccelerators"].([]interface{}) + if len(accelerators) > 0 { return fmt.Errorf("Expected no guest accelerators") } @@ -2383,19 +2540,26 @@ func testAccCheckComputeRegionInstanceTemplateLacksGuestAccelerator(instanceTemp } } -func testAccCheckComputeRegionInstanceTemplateHasMinCpuPlatform(instanceTemplate *compute.InstanceTemplate, minCpuPlatform string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasMinCpuPlatform(instanceTemplate *map[string]interface{}, minCpuPlatform string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.MinCpuPlatform != minCpuPlatform { - return fmt.Errorf("Wrong minimum CPU platform: expected %s, got %s", minCpuPlatform, instanceTemplate.Properties.MinCpuPlatform) + props := instanceTemplateProperties(instanceTemplate) + actual, _ := props["minCpuPlatform"].(string) + if actual != minCpuPlatform { + return fmt.Errorf("Wrong minimum CPU platform: expected %s, got %s", minCpuPlatform, actual) } return nil } } -func testAccCheckComputeRegionInstanceTemplateHasInstanceResourcePolicies(instanceTemplate *compute.InstanceTemplate, resourcePolicy string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasInstanceResourcePolicies(instanceTemplate *map[string]interface{}, resourcePolicy string) resource.TestCheckFunc { return func(s *terraform.State) error { - resourcePolicyActual := instanceTemplate.Properties.ResourcePolicies[0] + props := instanceTemplateProperties(instanceTemplate) + policies, _ := props["resourcePolicies"].([]interface{}) + if len(policies) == 0 { + return fmt.Errorf("no instance resource policies") + } + resourcePolicyActual, _ := policies[0].(string) if resourcePolicyActual != resourcePolicy { return fmt.Errorf("Wrong instance resource policy: expected %s, got %s", resourcePolicy, resourcePolicyActual) } @@ -2405,36 +2569,49 @@ func testAccCheckComputeRegionInstanceTemplateHasInstanceResourcePolicies(instan } -func testAccCheckComputeRegionInstanceTemplateHasAvailabilityDomain(instanceTemplate *compute.InstanceTemplate, availabilityDomain int64) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasAvailabilityDomain(instanceTemplate *map[string]interface{}, availabilityDomain int64) resource.TestCheckFunc { return func (s *terraform.State) error { - if instanceTemplate.Properties.Scheduling.AvailabilityDomain != availabilityDomain { - return fmt.Errorf("Expected availability_domain %d, got %d", availabilityDomain, instanceTemplate.Properties.Scheduling.AvailabilityDomain) + props := instanceTemplateProperties(instanceTemplate) + scheduling, _ := props["scheduling"].(map[string]interface{}) + actualVal, _ := scheduling["availabilityDomain"].(float64) + if int64(actualVal) != availabilityDomain { + return fmt.Errorf("Expected availability_domain %d, got %d", availabilityDomain, int64(actualVal)) } return nil } } -func testAccCheckComputeRegionInstanceTemplateHasReservationAffinity(instanceTemplate *compute.InstanceTemplate, consumeReservationType string, specificReservationNames ...string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasReservationAffinity(instanceTemplate *map[string]interface{}, consumeReservationType string, specificReservationNames ...string) resource.TestCheckFunc { if len(specificReservationNames) > 1 { panic("too many specificReservationNames in test") } return func(*terraform.State) error { - if instanceTemplate.Properties.ReservationAffinity == nil { + props := instanceTemplateProperties(instanceTemplate) + reservationAffinity, ok := props["reservationAffinity"].(map[string]interface{}) + if !ok { return fmt.Errorf("expected template to have reservation affinity, but it was nil") } - if actualReservationType := instanceTemplate.Properties.ReservationAffinity.ConsumeReservationType; actualReservationType != consumeReservationType { + actualReservationType, _ := reservationAffinity["consumeReservationType"].(string) + if actualReservationType != consumeReservationType { return fmt.Errorf("Wrong reservationAffinity consumeReservationType: expected %s, got, %s", consumeReservationType, actualReservationType) } if len(specificReservationNames) > 0 { const reservationNameKey = "compute.googleapis.com/reservation-name" - if actualKey := instanceTemplate.Properties.ReservationAffinity.Key; actualKey != reservationNameKey { + actualKey, _ := reservationAffinity["key"].(string) + if actualKey != reservationNameKey { return fmt.Errorf("Wrong reservationAffinity key: expected %s, got, %s", reservationNameKey, actualKey) } - reservationAffinityValues := instanceTemplate.Properties.ReservationAffinity.Values + rawValues, _ := reservationAffinity["values"].([]interface{}) + reservationAffinityValues := make([]string, 0, len(rawValues)) + for _, rv := range rawValues { + if v, ok := rv.(string); ok { + reservationAffinityValues = append(reservationAffinityValues, v) + } + } if len(reservationAffinityValues) != 1 || reservationAffinityValues[0] != specificReservationNames[0] { return fmt.Errorf("Wrong reservationAffinity values: expected %s, got, %s", specificReservationNames, reservationAffinityValues) } @@ -2444,41 +2621,51 @@ func testAccCheckComputeRegionInstanceTemplateHasReservationAffinity(instanceTem } } -func testAccCheckComputeRegionInstanceTemplateHasShieldedVmConfig(instanceTemplate *compute.InstanceTemplate, enableSecureBoot bool, enableVtpm bool, enableIntegrityMonitoring bool) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasShieldedVmConfig(instanceTemplate *map[string]interface{}, enableSecureBoot bool, enableVtpm bool, enableIntegrityMonitoring bool) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.ShieldedInstanceConfig.EnableSecureBoot != enableSecureBoot { - return fmt.Errorf("Wrong shieldedVmConfig enableSecureBoot: expected %t, got, %t", enableSecureBoot, instanceTemplate.Properties.ShieldedInstanceConfig.EnableSecureBoot) + props := instanceTemplateProperties(instanceTemplate) + shielded, _ := props["shieldedInstanceConfig"].(map[string]interface{}) + actualSecureBoot, _ := shielded["enableSecureBoot"].(bool) + if actualSecureBoot != enableSecureBoot { + return fmt.Errorf("Wrong shieldedVmConfig enableSecureBoot: expected %t, got, %t", enableSecureBoot, actualSecureBoot) } - if instanceTemplate.Properties.ShieldedInstanceConfig.EnableVtpm != enableVtpm { - return fmt.Errorf("Wrong shieldedVmConfig enableVtpm: expected %t, got, %t", enableVtpm, instanceTemplate.Properties.ShieldedInstanceConfig.EnableVtpm) + actualVtpm, _ := shielded["enableVtpm"].(bool) + if actualVtpm != enableVtpm { + return fmt.Errorf("Wrong shieldedVmConfig enableVtpm: expected %t, got, %t", enableVtpm, actualVtpm) } - if instanceTemplate.Properties.ShieldedInstanceConfig.EnableIntegrityMonitoring != enableIntegrityMonitoring { - return fmt.Errorf("Wrong shieldedVmConfig enableIntegrityMonitoring: expected %t, got, %t", enableIntegrityMonitoring, instanceTemplate.Properties.ShieldedInstanceConfig.EnableIntegrityMonitoring) + actualIntegrity, _ := shielded["enableIntegrityMonitoring"].(bool) + if actualIntegrity != enableIntegrityMonitoring { + return fmt.Errorf("Wrong shieldedVmConfig enableIntegrityMonitoring: expected %t, got, %t", enableIntegrityMonitoring, actualIntegrity) } return nil } } -func testAccCheckComputeRegionInstanceTemplateHasConfidentialInstanceConfig(instanceTemplate *compute.InstanceTemplate, EnableConfidentialCompute bool, ConfidentialInstanceType string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasConfidentialInstanceConfig(instanceTemplate *map[string]interface{}, EnableConfidentialCompute bool, ConfidentialInstanceType string) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.ConfidentialInstanceConfig.EnableConfidentialCompute != EnableConfidentialCompute { - return fmt.Errorf("Wrong ConfidentialInstanceConfig EnableConfidentialCompute: expected %t, got, %t", EnableConfidentialCompute, instanceTemplate.Properties.ConfidentialInstanceConfig.EnableConfidentialCompute) + props := instanceTemplateProperties(instanceTemplate) + confidential, _ := props["confidentialInstanceConfig"].(map[string]interface{}) + actualEnable, _ := confidential["enableConfidentialCompute"].(bool) + if actualEnable != EnableConfidentialCompute { + return fmt.Errorf("Wrong ConfidentialInstanceConfig EnableConfidentialCompute: expected %t, got, %t", EnableConfidentialCompute, actualEnable) } - if instanceTemplate.Properties.ConfidentialInstanceConfig.ConfidentialInstanceType != ConfidentialInstanceType { - return fmt.Errorf("Wrong ConfidentialInstanceConfig ConfidentialInstanceType: expected %s, got, %s", ConfidentialInstanceType, instanceTemplate.Properties.ConfidentialInstanceConfig.ConfidentialInstanceType) + actualType, _ := confidential["confidentialInstanceType"].(string) + if actualType != ConfidentialInstanceType { + return fmt.Errorf("Wrong ConfidentialInstanceConfig ConfidentialInstanceType: expected %s, got, %s", ConfidentialInstanceType, actualType) } return nil } } -func testAccCheckComputeRegionInstanceTemplateLacksShieldedVmConfig(instanceTemplate *compute.InstanceTemplate) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateLacksShieldedVmConfig(instanceTemplate *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if instanceTemplate.Properties.ShieldedInstanceConfig != nil { + props := instanceTemplateProperties(instanceTemplate) + if _, ok := props["shieldedInstanceConfig"].(map[string]interface{}); ok { return fmt.Errorf("Expected no shielded vm config") } @@ -2486,9 +2673,20 @@ func testAccCheckComputeRegionInstanceTemplateLacksShieldedVmConfig(instanceTemp } } -func testAccCheckComputeRegionInstanceTemplateHasDiskResourcePolicy(instanceTemplate *compute.InstanceTemplate, resourcePolicy string) resource.TestCheckFunc { +func testAccCheckComputeRegionInstanceTemplateHasDiskResourcePolicy(instanceTemplate *map[string]interface{}, resourcePolicy string) resource.TestCheckFunc { return func(s *terraform.State) error { - resourcePolicyActual := instanceTemplate.Properties.Disks[0].InitializeParams.ResourcePolicies[0] + props := instanceTemplateProperties(instanceTemplate) + disks, _ := props["disks"].([]interface{}) + if len(disks) == 0 { + return fmt.Errorf("no disks") + } + disk, _ := disks[0].(map[string]interface{}) + initParams, _ := disk["initializeParams"].(map[string]interface{}) + policies, _ := initParams["resourcePolicies"].([]interface{}) + if len(policies) == 0 { + return fmt.Errorf("no disk resource policies") + } + resourcePolicyActual, _ := policies[0].(string) if resourcePolicyActual != resourcePolicy { return fmt.Errorf("Wrong disk resource policy: expected %s, got %s", resourcePolicy, resourcePolicyActual) } @@ -5130,4 +5328,47 @@ resource "google_compute_region_instance_template" "foobar" { } `, suffix) } + +func testAccComputeRegionInstanceTemplate_aliasIpv6Range(suffix string) string { + return fmt.Sprintf(` +resource "google_compute_network" "custom-test" { + name = "tf-test-network-%s" + auto_create_subnetworks = false + enable_ula_internal_ipv6 = true +} + +resource "google_compute_subnetwork" "custom-test" { + name = "tf-test-subnetwork-%s" + region = "us-central1" + network = google_compute_network.custom-test.id + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } +} + +resource "google_compute_region_instance_template" "foobar" { + name = "tf-test-template-%s" + machine_type = "e2-medium" + region = "us-central1" + + disk { + source_image = "debian-cloud/debian-11" + auto_delete = true + boot = true + } + + network_interface { + subnetwork = google_compute_subnetwork.custom-test.name + stack_type = "IPV6_ONLY" + alias_ipv6_range { + ip_cidr_range = "/96" + } + } +} +`, suffix, suffix, suffix) +} {{- end }} diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_instant_snapshot_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_instant_snapshot_test.go index 19b23e92e20f..324752d1d6bc 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_instant_snapshot_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_instant_snapshot_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_group_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_group_test.go.tmpl index 10bdf7edf45d..b7505ad5c42e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_group_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_group_test.go.tmpl @@ -4,6 +4,8 @@ package compute_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/apigateway" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_test.go.tmpl index 9e0f4988ec75..955065db495b 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_endpoint_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_rule_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_rule_test.go index f416cff53491..0bbcffa7f48f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_rule_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_rule_test.go @@ -8,6 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeRegionNetworkFirewallPolicyRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_test.go index 1d787254172c..9b25fd98678d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRegionNetworkFirewallPolicy_RegionalHandWritten(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_with_rules_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_with_rules_test.go index e6a8b8702e96..5ac1a1742e1f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_with_rules_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_network_firewall_policy_with_rules_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccComputeRegionNetworkFirewallPolicyWithRules_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_per_instance_config_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_per_instance_config_test.go index 2a98a49462f2..01a58cd39a7d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_per_instance_config_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_per_instance_config_test.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_rule_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_rule_test.go.tmpl index 9dbb09eae0e1..8aeb58e159cb 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_rule_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_rule_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_test.go.tmpl index 2a0f04229c4e..0c3469db6d6e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_security_policy_test.go.tmpl @@ -3,6 +3,8 @@ package compute_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/helper/resource" {{- if ne $.TargetVersionName "ga" }} diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_ssl_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_ssl_policy_test.go index 8d152a72d8de..31dd25a8b45d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_ssl_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_ssl_policy_test.go @@ -7,13 +7,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccComputeRegionSslPolicy_regionInherit(t *testing.T) { t.Parallel() - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -44,7 +45,7 @@ func TestAccComputeRegionSslPolicy_update(t *testing.T) { t.Parallel() var sslPolicy map[string]interface{} - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -123,7 +124,7 @@ func TestAccComputeRegionSslPolicy_update_to_custom(t *testing.T) { t.Parallel() var sslPolicy map[string]interface{} - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -170,7 +171,7 @@ func TestAccComputeRegionSslPolicy_update_from_custom(t *testing.T) { t.Parallel() var sslPolicy map[string]interface{} - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -213,6 +214,81 @@ func TestAccComputeRegionSslPolicy_update_from_custom(t *testing.T) { }) } +func TestAccComputeRegionSslPolicy_postQuantumKeyExchange(t *testing.T) { + t.Parallel() + + var sslPolicy map[string]interface{} + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeSslPolicyDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeRegionSslPostQuantum(sslPolicyName, ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeRegionSslPolicyExists( + t, "google_compute_region_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_region_ssl_policy.post_quantum_key_exchange", "profile", "MODERN"), + resource.TestCheckResourceAttr( + "google_compute_region_ssl_policy.post_quantum_key_exchange", "min_tls_version", "TLS_1_2"), + resource.TestCheckResourceAttr( + "google_compute_region_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", ""), + ), + }, + { + ResourceName: "google_compute_region_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeRegionSslPostQuantum(sslPolicyName, "ENABLED"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeRegionSslPolicyExists( + t, "google_compute_region_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_region_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", "ENABLED"), + ), + }, + { + ResourceName: "google_compute_region_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeRegionSslPostQuantum(sslPolicyName, "DEFERRED"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeRegionSslPolicyExists( + t, "google_compute_region_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_region_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", "DEFERRED"), + ), + }, + { + ResourceName: "google_compute_region_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeRegionSslPostQuantum(sslPolicyName, "DEFAULT"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeRegionSslPolicyExists( + t, "google_compute_region_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_region_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", "DEFAULT"), + ), + }, + { + ResourceName: "google_compute_region_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckComputeRegionSslPolicyExists(t *testing.T, n string, sslPolicy *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -233,7 +309,7 @@ func testAccCheckComputeRegionSslPolicyExists(t *testing.T, n string, sslPolicy name := rs.Primary.Attributes["name"] - url := fmt.Sprintf("%sprojects/%s/regions/us-central1/sslPolicies/%s", config.ComputeBasePath, project, name) + url := fmt.Sprintf("%sprojects/%s/regions/us-central1/sslPolicies/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), project, name) found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", @@ -337,3 +413,15 @@ resource "google_compute_region_ssl_policy" "foobar" { } `, resourceName) } + +func testAccComputeRegionSslPostQuantum(resourceName string, pqke string) string { + return fmt.Sprintf(` +resource "google_compute_region_ssl_policy" "post_quantum_key_exchange" { + name = "%s" + profile = "MODERN" + min_tls_version = "TLS_1_2" + region = "us-central1" + post_quantum_key_exchange = "%s" +} +`, resourceName, pqke) +} diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_target_http_proxy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_target_http_proxy_test.go index e2b982856093..6b8b9e769dc6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_target_http_proxy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_target_http_proxy_test.go @@ -3,6 +3,7 @@ package compute_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_target_https_proxy_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_region_target_https_proxy_test.go.tmpl index 218a4298d0ba..6b1e9f720163 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_target_https_proxy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_target_https_proxy_test.go.tmpl @@ -4,6 +4,9 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_region_url_map_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_region_url_map_test.go index 2273ce70b284..62e45866875a 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_region_url_map_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_region_url_map_test.go @@ -3,6 +3,7 @@ package compute_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_reservation_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_reservation_test.go index e7a98248d138..fe3b134bd11d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_reservation_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_reservation_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeReservation_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_rollout_plan_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_rollout_plan_test.go.tmpl index 2a619ec25587..c87c04826313 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_rollout_plan_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_rollout_plan_test.go.tmpl @@ -6,6 +6,7 @@ import ( "fmt" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_route_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_route_test.go index b5f7d565fc10..fdcb4f24c8bb 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_route_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_route_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_bgp_peer_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_bgp_peer_test.go.tmpl index 4a6eec202641..6bdee3c09483 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_bgp_peer_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_bgp_peer_test.go.tmpl @@ -4,12 +4,13 @@ import ( "fmt" "regexp" "testing" - "regexp" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccComputeRouterPeer_basic(t *testing.T) { @@ -502,8 +503,6 @@ func testAccCheckComputeRouterPeerDestroyProducer(t *testing.T) func(s *terrafor return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) - routersService := compute.NewClient(config, config.UserAgent).Routers - for _, rs := range s.RootModule().Resources { if rs.Type != "google_compute_router" { continue @@ -519,9 +518,16 @@ func testAccCheckComputeRouterPeerDestroyProducer(t *testing.T) func(s *terrafor return err } - routerName := rs.Primary.Attributes["router"] + routerName := rs.Primary.Attributes["name"] - _, err = routersService.Get(project, region, routerName).Do() + url := fmt.Sprintf("%sprojects/%s/regions/%s/routers/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), project, region, routerName) + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err == nil { return fmt.Errorf("Error, Router %s in region %s still exists", @@ -537,8 +543,6 @@ func testAccCheckComputeRouterPeerDelete(t *testing.T, n string) resource.TestCh return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) - routersService := compute.NewClient(config, config.UserAgent).Routers - for _, rs := range s.RootModule().Resources { if rs.Type != "google_compute_router_peer" { continue @@ -557,17 +561,30 @@ func testAccCheckComputeRouterPeerDelete(t *testing.T, n string) resource.TestCh name := rs.Primary.Attributes["name"] routerName := rs.Primary.Attributes["router"] - router, err := routersService.Get(project, region, routerName).Do() + url := fmt.Sprintf("%sprojects/%s/regions/%s/routers/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), project, region, routerName) + router, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return fmt.Errorf("Error Reading Router %s: %s", routerName, err) } - peers := router.BgpPeers - for _, peer := range peers { - - if peer.Name == name { - return fmt.Errorf("Peer %s still exists on router %s/%s", name, region, router.Name) + routerResName, _ := router["name"].(string) + if rawPeers, ok := router["bgpPeers"].([]interface{}); ok { + for _, rawPeer := range rawPeers { + peer, ok := rawPeer.(map[string]interface{}) + if !ok { + continue + } + peerName, _ := peer["name"].(string) + if peerName == name { + return fmt.Errorf("Peer %s still exists on router %s/%s", name, region, routerResName) + } } } } @@ -602,21 +619,34 @@ func testAccCheckComputeRouterPeerExists(t *testing.T, n string) resource.TestCh name := rs.Primary.Attributes["name"] routerName := rs.Primary.Attributes["router"] - routersService := compute.NewClient(config, config.UserAgent).Routers - router, err := routersService.Get(project, region, routerName).Do() + url := fmt.Sprintf("%sprojects/%s/regions/%s/routers/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), project, region, routerName) + router, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return fmt.Errorf("Error Reading Router %s: %s", routerName, err) } - for _, peer := range router.BgpPeers { - - if peer.Name == name { - return nil + routerResName, _ := router["name"].(string) + if rawPeers, ok := router["bgpPeers"].([]interface{}); ok { + for _, rawPeer := range rawPeers { + peer, ok := rawPeer.(map[string]interface{}) + if !ok { + continue + } + peerName, _ := peer["name"].(string) + if peerName == name { + return nil + } } } - return fmt.Errorf("Peer %s not found for router %s", name, router.Name) + return fmt.Errorf("Peer %s not found for router %s", name, routerResName) } } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_interface.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_interface.go.tmpl index dd77dff98249..ae79933d3a16 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_interface.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_interface.go.tmpl @@ -27,6 +27,7 @@ func ResourceComputeRouterInterface() *schema.Resource { return &schema.Resource{ Create: resourceComputeRouterInterfaceCreate, Read: resourceComputeRouterInterfaceRead, + Update: resourceComputeRouterInterfaceUpdate, Delete: resourceComputeRouterInterfaceDelete, Importer: &schema.ResourceImporter{ State: resourceComputeRouterInterfaceImportState, @@ -38,6 +39,7 @@ func ResourceComputeRouterInterface() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, ), @@ -126,6 +128,9 @@ func ResourceComputeRouterInterface() *schema.Resource { ForceNew: true, Description: `The name of the interface that is redundant to this interface. Changing this forces a new interface to be created.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -300,6 +305,11 @@ func resourceComputeRouterInterfaceRead(d *schema.ResourceData, meta interface{} if err := d.Set("redundant_interface", iface.RedundantInterface); err != nil { return fmt.Errorf("Error setting redundant interface: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } } @@ -309,8 +319,22 @@ func resourceComputeRouterInterfaceRead(d *schema.ResourceData, meta interface{} return nil } +//UDP update start +func resourceComputeRouterInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceComputeRouterInterfaceRead(d, meta) +} +//UDP update end + func resourceComputeRouterInterfaceDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_interface_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_interface_meta.yaml.tmpl index 622a2b99028a..78eef05fe15d 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_interface_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_interface_meta.yaml.tmpl @@ -26,3 +26,5 @@ fields: field: 'subnetwork' - api_field: 'interfaces.linkedVpnTunnel' field: 'vpn_tunnel' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_named_set_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_named_set_test.go.tmpl index ab3eabf12ad0..aee76fc2ee95 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_named_set_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_named_set_test.go.tmpl @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_nat_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_router_nat_test.go index 09741df61875..13d3561cd5ba 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_nat_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_nat_test.go @@ -11,6 +11,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" ) func TestAccComputeRouterNat_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_peer.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_peer.go.tmpl index 41ec680b5462..94079ce7e53c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_peer.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_peer.go.tmpl @@ -50,6 +50,7 @@ func ResourceComputeRouterBgpPeer() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -372,6 +373,9 @@ Must be unique within a router. Must be referenced by exactly one bgpPeer. Must }, }, }, +//UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -768,11 +772,21 @@ func resourceComputeRouterBgpPeerRead(d *schema.ResourceData, meta interface{}) if err := d.Set("md5_authentication_key", flattenNestedComputeRouterBgpPeerMd5AuthenticationKey(res["md5AuthenticationKeyName"], d, config)); err != nil { return fmt.Errorf("Error reading RouterBgpPeer: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeRouterBgpPeerUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeRouterBgpPeer) { + return ResourceComputeRouterBgpPeer().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1003,6 +1017,13 @@ func resourceComputeRouterBgpPeerUpdate(d *schema.ResourceData, meta interface{} } func resourceComputeRouterBgpPeerDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_meta.yaml.tmpl index 3ef534b50ba3..c34929973c1c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_meta.yaml.tmpl @@ -76,3 +76,5 @@ fields: provider_only: true - field: 'zero_custom_learned_route_priority' provider_only: true + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_test.go.tmpl index b87b76f27601..4a1477dea8d4 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_peer_test.go.tmpl @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_route_policy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_router_route_policy_test.go index 104bab62a947..5edab7b94683 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_route_policy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_route_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeRouterRoutePolicy_PriorityZero(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_router_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_router_test.go index 7227091bd229..32222a30304e 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_router_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_router_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy.go.tmpl index 5657fad7eb40..d46cb89be225 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy.go.tmpl @@ -65,6 +65,7 @@ func ResourceComputeSecurityPolicy() *schema.Resource { State: resourceSecurityPolicyStateImporter, }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.SetLabelsDiff, rulesCustomizeDiff, @@ -731,6 +732,9 @@ Please refer to the field 'effective_labels' for all of the labels present on th Computed: true, Description: `The unique fingerprint of the labels.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), +//UDP schema end }, UseJSONNumber: true, } @@ -949,10 +953,20 @@ func resourceComputeSecurityPolicyRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error setting label_fingerprint: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeSecurityPolicy) { + return ResourceComputeSecurityPolicy().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1154,7 +1168,14 @@ func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{ } func resourceComputeSecurityPolicyDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_meta.yaml.tmpl index 83a9bda86085..fac884a84881 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_meta.yaml.tmpl @@ -135,4 +135,6 @@ fields: - api_field: 'selfLink' - field: 'terraform_labels' provider_only: true - - api_field: 'type' \ No newline at end of file + - api_field: 'type' + - field: 'deletion_policy' + provider_only: true \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_rule_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_rule_test.go index 0ffabde438ca..e64cce823f63 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_rule_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_rule_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_test.go.tmpl index 24f506920c90..47bb67c62e2f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_security_policy_test.go.tmpl @@ -9,8 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/recaptchaenterprise" "github.com/hashicorp/terraform-provider-google/google/envvar" - "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccComputeSecurityPolicy_basic(t *testing.T) { @@ -967,7 +969,23 @@ func testAccCheckComputeSecurityPolicyDestroyProducer(t *testing.T) func(s *terr pol := rs.Primary.Attributes["name"] - _, err := compute.NewClient(config, config.UserAgent).SecurityPolicies.Get(config.Project, pol).Do() + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/global/securityPolicies/{{"{{"}}name{{"}}"}}") + if err != nil { + return err + } + + billingProject := "" + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, + }) if err == nil { return fmt.Errorf("Security policy %q still exists", pol) } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_test.go index 77ff01be698f..60d747638d53 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccComputeServiceAttachment_serviceAttachmentBasicExampleUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_tunneling_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_tunneling_test.go.tmpl index fd8e148922b9..26f8c39daad7 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_tunneling_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_service_attachment_tunneling_test.go.tmpl @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeServiceAttachment_tunnelingConfigUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_shared_reservation_update_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_shared_reservation_update_test.go index f73bf0d6aa0b..3604e5750b86 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_shared_reservation_update_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_shared_reservation_update_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/orgpolicy" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeSharedReservation_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project.go b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project.go index 9768140966b4..fa5b2cf423b1 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project.go @@ -5,6 +5,7 @@ import ( "log" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -15,6 +16,7 @@ func ResourceComputeSharedVpcHostProject() *schema.Resource { return &schema.Resource{ Create: resourceComputeSharedVpcHostProjectCreate, Read: resourceComputeSharedVpcHostProjectRead, + Update: resourceComputeSharedVpcHostProjectUpdate, Delete: resourceComputeSharedVpcHostProjectDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, @@ -25,6 +27,10 @@ func ResourceComputeSharedVpcHostProject() *schema.Resource { Delete: schema.DefaultTimeout(4 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "project": { Type: schema.TypeString, @@ -32,6 +38,9 @@ func ResourceComputeSharedVpcHostProject() *schema.Resource { ForceNew: true, Description: `The ID of the project that will serve as a Shared VPC host project`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -84,10 +93,29 @@ func resourceComputeSharedVpcHostProjectRead(d *schema.ResourceData, meta interf return fmt.Errorf("Error setting project: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceComputeSharedVpcHostProjectUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceComputeSharedVpcHostProjectRead(d, meta) +} + +//UDP update end + func resourceComputeSharedVpcHostProjectDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project_meta.yaml.tmpl index a5a2ad7ab3be..60ea13165497 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_host_project_meta.yaml.tmpl @@ -9,3 +9,5 @@ api_version: 'v1' api_resource_type_kind: 'Project' fields: - field: 'project' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_service_project.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_service_project.go similarity index 70% rename from mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_service_project.go.tmpl rename to mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_service_project.go index 287e14fbc45e..5c46da561b4a 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_service_project.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_service_project.go @@ -2,9 +2,9 @@ package compute import ( "fmt" + "log" "strings" "time" - "log" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -14,12 +14,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "google.golang.org/api/googleapi" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} ) func ResourceComputeSharedVpcServiceProject() *schema.Resource { @@ -55,7 +49,7 @@ func ResourceComputeSharedVpcServiceProject() *schema.Resource { Description: `The ID of the project that will serve as a Shared VPC service project.`, }, "deletion_policy": { - Type: schema.TypeString, + Type: schema.TypeString, Optional: true, ForceNew: false, Description: `The deletion policy for the shared VPC service. Setting ABANDON allows the resource @@ -69,7 +63,7 @@ func ResourceComputeSharedVpcServiceProject() *schema.Resource { func resourceComputeSharedVpcServiceProjectCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -77,17 +71,24 @@ func resourceComputeSharedVpcServiceProjectCreate(d *schema.ResourceData, meta i hostProject := d.Get("host_project").(string) serviceProject := d.Get("service_project").(string) - req := &compute.ProjectsEnableXpnResourceRequest{ - XpnResource: &compute.XpnResourceId{ - Id: serviceProject, - Type: "PROJECT", + url := fmt.Sprintf("%sprojects/%s/enableXpnResource", transport_tpg.BaseUrl(Product, config), hostProject) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: hostProject, + RawURL: url, + UserAgent: userAgent, + Body: map[string]interface{}{ + "xpnResource": map[string]interface{}{ + "id": serviceProject, + "type": "PROJECT", + }, }, - } - op, err := NewClient(config, userAgent).Projects.EnableXpnResource(hostProject, req).Do() + }) if err != nil { return err } - err = ComputeOperationWaitTime(config, op, hostProject, "Enabling Shared VPC Resource", userAgent, d.Timeout(schema.TimeoutCreate)) + err = ComputeOperationWaitTime(config, res, hostProject, "Enabling Shared VPC Resource", userAgent, d.Timeout(schema.TimeoutCreate)) if err != nil { return err } @@ -99,7 +100,7 @@ func resourceComputeSharedVpcServiceProjectCreate(d *schema.ResourceData, meta i func resourceComputeSharedVpcServiceProjectRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -111,7 +112,14 @@ func resourceComputeSharedVpcServiceProjectRead(d *schema.ResourceData, meta int hostProject := split[0] serviceProject := split[1] - associatedHostProject, err := NewClient(config, userAgent).Projects.GetXpnHost(serviceProject).Do() + url := fmt.Sprintf("%sprojects/%s/getXpnHost", transport_tpg.BaseUrl(Product, config), serviceProject) + associatedHostProject, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: serviceProject, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { log.Printf("[WARN] Removing shared VPC service. The service project is not associated with any host") @@ -119,8 +127,8 @@ func resourceComputeSharedVpcServiceProjectRead(d *schema.ResourceData, meta int return nil } - if hostProject != associatedHostProject.Name { - log.Printf("[WARN] Removing shared VPC service. Expected associated host project to be '%s', got '%s'", hostProject, associatedHostProject.Name) + if hostProject != associatedHostProject["name"].(string) { + log.Printf("[WARN] Removing shared VPC service. Expected associated host project to be '%s', got '%s'", hostProject, associatedHostProject["name"].(string)) d.SetId("") return nil } @@ -139,7 +147,7 @@ func resourceComputeSharedVpcServiceProjectDelete(d *schema.ResourceData, meta i config := meta.(*transport_tpg.Config) hostProject := d.Get("host_project").(string) serviceProject := d.Get("service_project").(string) - + if deletionPolicy := d.Get("deletion_policy"); deletionPolicy == "ABANDON" { log.Printf("[WARN] Shared VPC service project %q deletion_policy is set to 'ABANDON', skip disabling shared VPC service project", d.Id()) d.SetId("") @@ -157,22 +165,29 @@ func resourceComputeSharedVpcServiceProjectDelete(d *schema.ResourceData, meta i } func disableXpnResource(d *schema.ResourceData, config *transport_tpg.Config, hostProject, project string) error { - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - req := &compute.ProjectsDisableXpnResourceRequest{ - XpnResource: &compute.XpnResourceId{ - Id: project, - Type: "PROJECT", + url := fmt.Sprintf("%sprojects/%s/disableXpnResource", transport_tpg.BaseUrl(Product, config), hostProject) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: hostProject, + RawURL: url, + UserAgent: userAgent, + Body: map[string]interface{}{ + "xpnResource": map[string]interface{}{ + "id": project, + "type": "PROJECT", + }, }, - } - op, err := NewClient(config, userAgent).Projects.DisableXpnResource(hostProject, req).Do() + }) if err != nil { return err } - err = ComputeOperationWaitTime(config, op, hostProject, "Disabling Shared VPC Resource", userAgent, d.Timeout(schema.TimeoutDelete)) + err = ComputeOperationWaitTime(config, res, hostProject, "Disabling Shared VPC Resource", userAgent, d.Timeout(schema.TimeoutDelete)) if err != nil { return err } @@ -188,7 +203,7 @@ func isDisabledXpnResourceError(err error) bool { return false } -func resourceComputeSharedVpcServiceProjectUpdate(d *schema.ResourceData, meta interface{}) error{ +func resourceComputeSharedVpcServiceProjectUpdate(d *schema.ResourceData, meta interface{}) error { // This update method is no-op because the only updatable fields // are state/config-only, i.e. they aren't sent in requests to the API. return nil @@ -196,9 +211,9 @@ func resourceComputeSharedVpcServiceProjectUpdate(d *schema.ResourceData, meta i func init() { registry.Schema{ - Name: "google_compute_shared_vpc_service_project", + Name: "google_compute_shared_vpc_service_project", ProductName: "compute", - Type: registry.SchemaTypeResource, - Schema: ResourceComputeSharedVpcServiceProject(), + Type: registry.SchemaTypeResource, + Schema: ResourceComputeSharedVpcServiceProject(), }.Register() } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_test.go index dad043eda3fa..7e5878657cec 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_shared_vpc_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeSharedVpc_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_settings_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_settings_test.go index 93c9c5ca4e15..eb12e2a70804 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_settings_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_settings_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeSnapshotSettings_snapshotSettings_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_test.go index f675d2eee7e0..43bbb119f1a4 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_snapshot_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccComputeSnapshot_encryption(t *testing.T) { @@ -39,7 +42,7 @@ func TestAccComputeSnapshot_encryptionCMEK(t *testing.T) { snapshotName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) diskName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - kmsKeyName := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-compute-snapshot-key1").CryptoKey.Name + kmsKeyName := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-compute-snapshot-key1").CryptoKey.Name acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_ssl_policy_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_ssl_policy_test.go similarity index 63% rename from mmv1/third_party/terraform/services/compute/resource_compute_ssl_policy_test.go.tmpl rename to mmv1/third_party/terraform/services/compute/resource_compute_ssl_policy_test.go index ecf73fe01a6a..797d46e84102 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_ssl_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_ssl_policy_test.go @@ -3,24 +3,19 @@ package compute_test import ( "fmt" "testing" - "github.com/hashicorp/terraform-provider-google/google/acctest" - compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} + "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccComputeSslPolicy_update(t *testing.T) { t.Parallel() - var sslPolicy compute.SslPolicy - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + var sslPolicy map[string]interface{} + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -36,6 +31,8 @@ func TestAccComputeSslPolicy_update(t *testing.T) { "google_compute_ssl_policy.update", "profile", "MODERN"), resource.TestCheckResourceAttr( "google_compute_ssl_policy.update", "min_tls_version", "TLS_1_0"), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.update", "post_quantum_key_exchange", ""), ), }, { @@ -52,6 +49,8 @@ func TestAccComputeSslPolicy_update(t *testing.T) { "google_compute_ssl_policy.update", "profile", "RESTRICTED"), resource.TestCheckResourceAttr( "google_compute_ssl_policy.update", "min_tls_version", "TLS_1_2"), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.update", "post_quantum_key_exchange", ""), ), }, { @@ -68,6 +67,8 @@ func TestAccComputeSslPolicy_update(t *testing.T) { "google_compute_ssl_policy.update", "profile", "FIPS_202205"), resource.TestCheckResourceAttr( "google_compute_ssl_policy.update", "min_tls_version", "TLS_1_2"), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.update", "post_quantum_key_exchange", ""), ), }, { @@ -84,6 +85,8 @@ func TestAccComputeSslPolicy_update(t *testing.T) { "google_compute_ssl_policy.update", "profile", "RESTRICTED"), resource.TestCheckResourceAttr( "google_compute_ssl_policy.update", "min_tls_version", "TLS_1_3"), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.update", "post_quantum_key_exchange", ""), ), }, { @@ -98,8 +101,8 @@ func TestAccComputeSslPolicy_update(t *testing.T) { func TestAccComputeSslPolicy_update_to_custom(t *testing.T) { t.Parallel() - var sslPolicy compute.SslPolicy - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + var sslPolicy map[string]interface{} + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -145,8 +148,8 @@ func TestAccComputeSslPolicy_update_to_custom(t *testing.T) { func TestAccComputeSslPolicy_update_from_custom(t *testing.T) { t.Parallel() - var sslPolicy compute.SslPolicy - sslPolicyName := fmt.Sprintf("test-ssl-policy-%s", acctest.RandString(t, 10)) + var sslPolicy map[string]interface{} + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -189,7 +192,82 @@ func TestAccComputeSslPolicy_update_from_custom(t *testing.T) { }) } -func testAccCheckComputeSslPolicyExists(t *testing.T, n string, sslPolicy *compute.SslPolicy) resource.TestCheckFunc { +func TestAccComputeSslPolicy_postQuantumKeyExchange(t *testing.T) { + t.Parallel() + + var sslPolicy map[string]interface{} + sslPolicyName := fmt.Sprintf("tf-test-ssl-policy-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckComputeSslPolicyDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccComputeSslPostQuantum(sslPolicyName, ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSslPolicyExists( + t, "google_compute_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.post_quantum_key_exchange", "profile", "MODERN"), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.post_quantum_key_exchange", "min_tls_version", "TLS_1_2"), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", ""), + ), + }, + { + ResourceName: "google_compute_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeSslPostQuantum(sslPolicyName, "DEFAULT"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSslPolicyExists( + t, "google_compute_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", "DEFAULT"), + ), + }, + { + ResourceName: "google_compute_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeSslPostQuantum(sslPolicyName, "ENABLED"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSslPolicyExists( + t, "google_compute_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", "ENABLED"), + ), + }, + { + ResourceName: "google_compute_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccComputeSslPostQuantum(sslPolicyName, "DEFERRED"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSslPolicyExists( + t, "google_compute_ssl_policy.post_quantum_key_exchange", &sslPolicy), + resource.TestCheckResourceAttr( + "google_compute_ssl_policy.post_quantum_key_exchange", "post_quantum_key_exchange", "DEFERRED"), + ), + }, + { + ResourceName: "google_compute_ssl_policy.post_quantum_key_exchange", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckComputeSslPolicyExists(t *testing.T, n string, sslPolicy *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -209,17 +287,23 @@ func testAccCheckComputeSslPolicyExists(t *testing.T, n string, sslPolicy *compu name := rs.Primary.Attributes["name"] - found, err := compute_tpg.NewClient(config, config.UserAgent).SslPolicies.Get( - project, name).Do() + url := fmt.Sprintf("%sprojects/%s/global/sslPolicies/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), project, name) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return fmt.Errorf("Error Reading SSL Policy %s: %s", name, err) } - if found.Name != name { + if found["name"].(string) != name { return fmt.Errorf("SSL Policy not found") } - *sslPolicy = *found + *sslPolicy = found return nil } @@ -280,3 +364,14 @@ resource "google_compute_ssl_policy" "update" { } `, resourceName) } + +func testAccComputeSslPostQuantum(resourceName, pqke string) string { + return fmt.Sprintf(` +resource "google_compute_ssl_policy" "post_quantum_key_exchange" { + name = "%s" + profile = "MODERN" + min_tls_version = "TLS_1_2" + post_quantum_key_exchange = "%s" +} +`, resourceName, pqke) +} diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_storage_pool_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_storage_pool_test.go index ea439a8e5016..06593b674b5f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_storage_pool_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_storage_pool_test.go @@ -11,6 +11,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -195,7 +197,7 @@ func testAccCheckComputeStoragePoolDestroyProducer(t *testing.T) func(s *terrafo config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/storagePools/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(compute.Product, config)+"projects/{{project}}/zones/{{zone}}/storagePools/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_internal_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_internal_test.go.tmpl new file mode 100644 index 000000000000..32c6b8381aa1 --- /dev/null +++ b/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_internal_test.go.tmpl @@ -0,0 +1,262 @@ +package compute +{{ if ne $.TargetVersionName `ga` -}} +import ( + "testing" + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" +) + +func TestUnitComputeSubnetworkSecondaryIpRange_customizeDiff(t *testing.T) { + t.Parallel() + + cases := map[string]struct { + KeysPrefix []string + OldCount int + NewCount int + Before map[string]interface{} + After map[string]interface{} + RawConfig cty.Value + ExpectClear bool + }{ + "no changes": { + KeysPrefix: []string{}, + ExpectClear: false, + }, + "exact match with multiple ipv4 secondary ranges": { + KeysPrefix: []string{"secondary_ip_range"}, + OldCount: 2, + NewCount: 2, + Before: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "tf-test-ipv4-range-1", + "ip_cidr_range": "10.2.0.0/16", + }, + "secondary_ip_range.1": map[string]interface{}{ + "range_name": "tf-test-ipv4-range-2", + "ip_cidr_range": "10.3.0.0/16", + }, + }, + After: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "tf-test-ipv4-range-1", + "ip_cidr_range": "10.2.0.0/16", + }, + "secondary_ip_range.1": map[string]interface{}{ + "range_name": "tf-test-ipv4-range-2", + "ip_cidr_range": "", + }, + }, + RawConfig: cty.ObjectVal(map[string]cty.Value{ + "secondary_ip_range": cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("tf-test-ipv4-range-1"), + "ip_cidr_range": cty.StringVal("10.2.0.0/16"), + }), + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("tf-test-ipv4-range-2"), + "ip_cidr_range": cty.StringVal(""), + }), + }), + }), + ExpectClear: true, + }, + "exact match with ipv6 cidr compression": { + KeysPrefix: []string{"secondary_ip_range"}, + OldCount: 1, + NewCount: 1, + Before: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-auto", + "ip_cidr_range": "2001:db8:abcd:1::/64", + "ip_version": "IPV6", + }, + }, + After: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-auto", + "ip_cidr_range": "2001:db8:abcd:1:0:0:0:0/64", + "ip_version": "IPV6", + }, + }, + RawConfig: cty.ObjectVal(map[string]cty.Value{ + "secondary_ip_range": cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("v6-byoip-auto"), + "ip_cidr_range": cty.StringVal("2001:db8:abcd:1::/64"), + }), + }), + }), + ExpectClear: true, + }, + "multi-range match with ula inheritance, url normalization, and cidr compression": { + KeysPrefix: []string{"secondary_ip_range"}, + OldCount: 3, + NewCount: 3, + Before: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-url", + "ip_cidr_range": "2001:db8:abcd:1::/64", + "ip_version": "IPV6", + "ip_collection": "https://www.googleapis.com/compute/v1/projects/my-proj/regions/us-central1/publicDelegatedPrefixes/my-pdp", + }, + "secondary_ip_range.1": map[string]interface{}{ + "range_name": "v6-ula", + "ip_cidr_range": "2001:db8:abcd:2:0:0:0:0/64", + "ip_version": "IPV6", + }, + "secondary_ip_range.2": map[string]interface{}{ + "range_name": "v6-byoip-compress", + "ip_cidr_range": "2001:db8:abcd:3:0:0:0:0/64", + "ip_version": "IPV6", + }, + }, + After: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-url", + "ip_cidr_range": "2001:db8:abcd:1::/64", + "ip_version": "IPV6", + "ip_collection": "projects/my-proj/regions/us-central1/publicDelegatedPrefixes/my-pdp", + }, + "secondary_ip_range.1": map[string]interface{}{ + "range_name": "v6-ula", + "ip_cidr_range": "", + "ip_version": "IPV6", + }, + "secondary_ip_range.2": map[string]interface{}{ + "range_name": "v6-byoip-compress", + "ip_cidr_range": "2001:db8:abcd:3::/64", + "ip_version": "IPV6", + }, + }, + RawConfig: cty.ObjectVal(map[string]cty.Value{ + "secondary_ip_range": cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("v6-byoip-url"), + "ip_cidr_range": cty.StringVal("2001:db8:abcd:1::/64"), + }), + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("v6-ula"), + "ip_cidr_range": cty.StringVal(""), + }), + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("v6-byoip-compress"), + "ip_cidr_range": cty.StringVal("2001:db8:abcd:3::/64"), + }), + }), + }), + ExpectClear: true, + }, + "real mismatch with differing ip_cidr_range": { + KeysPrefix: []string{"secondary_ip_range"}, + OldCount: 1, + NewCount: 1, + Before: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-auto", + "ip_cidr_range": "2001:db8:abcd:1::/64", + }, + }, + After: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-auto", + "ip_cidr_range": "2001:db8:abcd:9999::/64", + }, + }, + RawConfig: cty.ObjectVal(map[string]cty.Value{ + "secondary_ip_range": cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("v6-byoip-auto"), + "ip_cidr_range": cty.StringVal("2001:db8:abcd:9999::/64"), + }), + }), + }), + ExpectClear: false, + }, + "real mismatch with differing range_name": { + KeysPrefix: []string{"secondary_ip_range"}, + OldCount: 1, + NewCount: 1, + Before: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "old-range-name", + "ip_cidr_range": "10.2.0.0/16", + }, + }, + After: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "new-range-name", + "ip_cidr_range": "10.2.0.0/16", + }, + }, + RawConfig: cty.ObjectVal(map[string]cty.Value{ + "secondary_ip_range": cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("new-range-name"), + "ip_cidr_range": cty.StringVal("10.2.0.0/16"), + }), + }), + }), + ExpectClear: false, + }, + "real mismatch with differing ip_collection": { + KeysPrefix: []string{"secondary_ip_range"}, + OldCount: 1, + NewCount: 1, + Before: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-auto", + "ip_cidr_range": "2001:db8:abcd:1::/64", + "ip_collection": "https://www.googleapis.com/compute/v1/projects/my-proj/regions/us-central1/publicDelegatedPrefixes/my-pdp-1", + }, + }, + After: map[string]interface{}{ + "secondary_ip_range.0": map[string]interface{}{ + "range_name": "v6-byoip-auto", + "ip_cidr_range": "2001:db8:abcd:1::/64", + "ip_collection": "projects/my-proj/regions/us-central1/publicDelegatedPrefixes/my-pdp-2", + }, + }, + RawConfig: cty.ObjectVal(map[string]cty.Value{ + "secondary_ip_range": cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "range_name": cty.StringVal("v6-byoip-auto"), + "ip_cidr_range": cty.StringVal("2001:db8:abcd:1::/64"), + }), + }), + }), + ExpectClear: false, + }, + } + + for tn, tc := range cases { + t.Run(tn, func(t *testing.T) { + d := &tpgresource.ResourceDiffMock{ + Before: tc.Before, + After: tc.After, + KeysPrefix: tc.KeysPrefix, + RawConfig: tc.RawConfig, + } + if tc.OldCount > 0 || tc.NewCount > 0 { + if d.Before == nil { + d.Before = make(map[string]interface{}) + } + if d.After == nil { + d.After = make(map[string]interface{}) + } + d.Before["secondary_ip_range.#"] = tc.OldCount + d.After["secondary_ip_range.#"] = tc.NewCount + } + + err := resourceComputeSubnetworkSecondaryIpRangeCustomDiffFunc(d) + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + + cleared := d.Cleared != nil && d.Cleared["secondary_ip_range"] != nil + if cleared != tc.ExpectClear { + t.Errorf("expected diff clear to be %v, but was %v", tc.ExpectClear, cleared) + } + }) + } +} +{{- end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_test.go.tmpl index 6b85851a81df..f7c66fbcb164 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_subnetwork_test.go.tmpl @@ -448,6 +448,65 @@ func TestAccComputeSubnetwork_secondaryIpRanges_sendEmpty(t *testing.T) { }) } +{{ if ne $.TargetVersionName `ga` -}} +func TestAccComputeSubnetwork_secondaryIpv6Ranges(t *testing.T) { + t.Parallel() + + var subnetwork compute.Subnetwork + cnName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + subnetworkName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + papName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + pdpName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + subPdpName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + CheckDestroy: testAccCheckComputeSubnetworkDestroyProducer(t), + Steps: []resource.TestStep{ + { + // Step 1: Create a normal custom subnet + Config: testAccComputeSubnetwork_secondaryIpv6RangesBase(cnName, subnetworkName, papName, pdpName, subPdpName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSubnetworkExists(t, "google_compute_subnetwork.ipv6-secondary-ranges", &subnetwork), + ), + }, + { + // Step 2: Add 3 secondary ranges to the subnet: 1 ULA, 2 BYOGUA (1 auto, 1 manual) + Config: testAccComputeSubnetwork_secondaryIpv6RangesAdd(cnName, subnetworkName, papName, pdpName, subPdpName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSubnetworkExists(t, "google_compute_subnetwork.ipv6-secondary-ranges", &subnetwork), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-ula", "IPV6", ""), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-byoip-auto", "IPV6", ""), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-byoip-manual", "IPV6", ""), + ), + }, + { + // Step 3: Change the order of the secondary ranges (Verifies no-op/no re-creation) + Config: testAccComputeSubnetwork_secondaryIpv6RangesReorder(cnName, subnetworkName, papName, pdpName, subPdpName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSubnetworkExists(t, "google_compute_subnetwork.ipv6-secondary-ranges", &subnetwork), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-ula", "IPV6", ""), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-byoip-auto", "IPV6", ""), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-byoip-manual", "IPV6", ""), + ), + }, + { + // Step 4: Remove 2 ranges (ULA and Manual), leave 1 (Auto) + Config: testAccComputeSubnetwork_secondaryIpv6RangesRemove(cnName, subnetworkName, papName, pdpName, subPdpName), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeSubnetworkExists(t, "google_compute_subnetwork.ipv6-secondary-ranges", &subnetwork), + testAccCheckComputeSubnetworkHasSecondaryIpv6Range(&subnetwork, "v6-byoip-auto", "IPV6", ""), + testAccCheckComputeSubnetworkHasNotSecondaryIpRange(&subnetwork, "v6-ula", ""), + testAccCheckComputeSubnetworkHasNotSecondaryIpRange(&subnetwork, "v6-byoip-manual", ""), + ), + }, + }, + }) +} +{{- end }} + + func TestAccComputeSubnetwork_flowLogs(t *testing.T) { t.Parallel() @@ -800,6 +859,25 @@ func testAccCheckComputeSubnetworkHasSecondaryIpRange(subnetwork *compute.Subnet } } +{{- if ne $.TargetVersionName "ga" }} +func testAccCheckComputeSubnetworkHasSecondaryIpv6Range(subnetwork *compute.Subnetwork, rangeName, ipVersion, ipCollection string) resource.TestCheckFunc { + return func(s *terraform.State) error { + for _, secondaryRange := range subnetwork.SecondaryIpRanges { + if secondaryRange.RangeName == rangeName { + if secondaryRange.IpVersion != ipVersion { + return fmt.Errorf("Secondary range %s has wrong ipVersion. Expected %s, got %s", rangeName, ipVersion, secondaryRange.IpVersion) + } + if ipCollection != "" && secondaryRange.IpCollection != ipCollection { + return fmt.Errorf("Secondary range %s has wrong ipCollection. Expected %s, got %s", rangeName, ipCollection, secondaryRange.IpCollection) + } + return nil + } + } + return fmt.Errorf("Secondary IPv6 range %s not found", rangeName) + } +} +{{- end }} + func testAccCheckComputeSubnetworkHasNotSecondaryIpRange(subnetwork *compute.Subnetwork, rangeName, ipCidrRange string) resource.TestCheckFunc { return func(s *terraform.State) error { for _, secondaryRange := range subnetwork.SecondaryIpRanges { @@ -1445,3 +1523,147 @@ resource "google_compute_subnetwork" "test_subnet" { } `, context) } + +// Shared base config for secondary IPv6 ranges (Network, PAP, PDP) +{{ if ne $.TargetVersionName "ga" -}} +func testAccComputeSubnetwork_secondaryIpv6RangesShared(cnName, papName, pdpName, subPdpName string) string { + return fmt.Sprintf(` +resource "google_compute_network" "custom-test" { + provider = google-beta + name = "%s" + auto_create_subnetworks = false + enable_ula_internal_ipv6 = true +} + +resource "google_compute_public_advertised_prefix" "ipv6_pap" { + provider = google-beta + name = "%s" + ip_cidr_range = "2001:db8::/32" + pdp_scope = "REGIONAL" + ipv6_access_type = "INTERNAL" + description = "GOOGLE_INTERNAL_TEST_PREFIX" +} + +resource "google_compute_public_delegated_prefix" "ipv6_pdp" { + provider = google-beta + name = "%s" + region = "us-central1" + ip_cidr_range = "2001:db8:abcd::/48" + parent_prefix = google_compute_public_advertised_prefix.ipv6_pap.id + mode = "DELEGATION" +} + +resource "google_compute_public_delegated_prefix" "ipv6_sub_pdp" { + provider = google-beta + name = "%s" + region = "us-central1" + ip_cidr_range = "2001:db8:abcd::/56" + parent_prefix = google_compute_public_delegated_prefix.ipv6_pdp.id + mode = "INTERNAL_IPV6_SUBNETWORK_CREATION" +} +`, cnName, papName, pdpName, subPdpName) +} +{{- end }} + +{{ if ne $.TargetVersionName "ga" -}} +func testAccComputeSubnetwork_secondaryIpv6RangesBase(cnName, subnetworkName, papName, pdpName, subPdpName string) string { + return fmt.Sprintf(` +%s +resource "google_compute_subnetwork" "ipv6-secondary-ranges" { + provider = google-beta + name = "%s" + region = "us-central1" + network = google_compute_network.custom-test.self_link + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" +} +`, testAccComputeSubnetwork_secondaryIpv6RangesShared(cnName, papName, pdpName, subPdpName), subnetworkName) +} +{{- end }} + +{{ if ne $.TargetVersionName "ga" -}} +func testAccComputeSubnetwork_secondaryIpv6RangesAdd(cnName, subnetworkName, papName, pdpName, subPdpName string) string { + return fmt.Sprintf(` +%s +resource "google_compute_subnetwork" "ipv6-secondary-ranges" { + provider = google-beta + name = "%s" + network = google_compute_network.custom-test.self_link + region = "us-central1" + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } + secondary_ip_range { + range_name = "v6-byoip-auto" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + } + secondary_ip_range { + range_name = "v6-byoip-manual" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + ip_cidr_range = "2001:db8:abcd:2::/64" + } +} +`, testAccComputeSubnetwork_secondaryIpv6RangesShared(cnName, papName, pdpName, subPdpName), subnetworkName) +} +{{- end }} + +{{ if ne $.TargetVersionName "ga" -}} +func testAccComputeSubnetwork_secondaryIpv6RangesReorder(cnName, subnetworkName, papName, pdpName, subPdpName string) string { + return fmt.Sprintf(` +%s +resource "google_compute_subnetwork" "ipv6-secondary-ranges" { + provider = google-beta + name = "%s" + region = "us-central1" + network = google_compute_network.custom-test.self_link + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + # Reordered: Manual -> Auto -> ULA + secondary_ip_range { + range_name = "v6-byoip-manual" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + ip_cidr_range = "2001:db8:abcd:2::/64" + } + secondary_ip_range { + range_name = "v6-byoip-auto" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + } + secondary_ip_range { + range_name = "v6-ula" + ip_version = "IPV6" + } +} +`, testAccComputeSubnetwork_secondaryIpv6RangesShared(cnName, papName, pdpName, subPdpName), subnetworkName) +} +{{- end }} + +{{ if ne $.TargetVersionName "ga" -}} +func testAccComputeSubnetwork_secondaryIpv6RangesRemove(cnName, subnetworkName, papName, pdpName, subPdpName string) string { + return fmt.Sprintf(` +%s +resource "google_compute_subnetwork" "ipv6-secondary-ranges" { + provider = google-beta + name = "%s" + region = "us-central1" + network = google_compute_network.custom-test.self_link + stack_type = "IPV6_ONLY" + ipv6_access_type = "INTERNAL" + + secondary_ip_range { + range_name = "v6-byoip-auto" + ip_version = "IPV6" + ip_collection = google_compute_public_delegated_prefix.ipv6_sub_pdp.self_link + } +} +`, testAccComputeSubnetwork_secondaryIpv6RangesShared(cnName, papName, pdpName, subPdpName), subnetworkName) +} +{{- end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_grpc_proxy_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_target_grpc_proxy_test.go index deaefbbfbc65..deb8e7d96031 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_grpc_proxy_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_grpc_proxy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeTargetGrpcProxy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_https_proxy_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_target_https_proxy_test.go.tmpl index aa95ec20591f..941a5df3d7a9 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_https_proxy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_https_proxy_test.go.tmpl @@ -4,6 +4,8 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_instance_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_target_instance_test.go.tmpl index ab65f0eaa39f..e814d92db423 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_instance_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeTargetInstance_withSecurityPolicy(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_pool.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_target_pool.go.tmpl index 9b0a736e5b8d..6af376accc22 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_pool.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_pool.go.tmpl @@ -14,12 +14,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/api/googleapi" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} ) var instancesSelfLinkPattern = regexp.MustCompile(fmt.Sprintf(tpgresource.ZonalLinkBasePattern, "instances")) @@ -41,6 +35,7 @@ func ResourceComputeTargetPool() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.DefaultProviderRegion, ), @@ -140,6 +135,9 @@ func ResourceComputeTargetPool() *schema.Resource { Description: `The resource URL for the security policy associated with this target pool.`, }, {{- end }} + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -209,11 +207,6 @@ func resourceComputeTargetPoolCreate(d *schema.ResourceData, meta interface{}) e return err } - region, err := tpgresource.GetRegion(d, config) - if err != nil { - return err - } - project, err := tpgresource.GetProject(d, config) if err != nil { return err @@ -230,20 +223,34 @@ func resourceComputeTargetPoolCreate(d *schema.ResourceData, meta interface{}) e } // Build the parameter - tpool := &compute.TargetPool{ - BackupPool: d.Get("backup_pool").(string), - Description: d.Get("description").(string), - HealthChecks: hchkUrls, - Instances: instanceUrls, - Name: d.Get("name").(string), - SessionAffinity: d.Get("session_affinity").(string), + tpool := map[string]interface{}{ + "description": d.Get("description").(string), + "healthChecks": hchkUrls, + "name": d.Get("name").(string), + "sessionAffinity": d.Get("session_affinity").(string), } - if d.Get("failover_ratio") != nil { - tpool.FailoverRatio = d.Get("failover_ratio").(float64) + if len(instanceUrls) > 0 { + tpool["instances"] = instanceUrls + } + if v := d.Get("backup_pool").(string); v != "" { + tpool["backupPool"] = v + } + if v, ok := d.GetOk("failover_ratio"); ok { + tpool["failoverRatio"] = v.(float64) } log.Printf("[DEBUG] TargetPool insert request: %#v", tpool) - op, err := NewClient(config, userAgent).TargetPools.Insert( - project, region, tpool).Do() + insertUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools") + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: insertUrl, + UserAgent: userAgent, + Body: tpool, + }) if err != nil { if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 && strings.Contains(gerr.Message, "httpHealthChecks") { return fmt.Errorf("Health check %s is not a valid HTTP health check", d.Get("health_checks").([]interface{})[0]) @@ -258,7 +265,7 @@ func resourceComputeTargetPoolCreate(d *schema.ResourceData, meta interface{}) e } d.SetId(id) - err = ComputeOperationWaitTime(config, op, project, "Creating Target Pool", userAgent, d.Timeout(schema.TimeoutCreate)) + err = ComputeOperationWaitTime(config, res, project, "Creating Target Pool", userAgent, d.Timeout(schema.TimeoutCreate)) if err != nil { return err } @@ -304,24 +311,22 @@ func resourceComputeTargetPoolCreate(d *schema.ResourceData, meta interface{}) e } func resourceComputeTargetPoolUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceComputeTargetPool) { + return ResourceComputeTargetPool().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - region, err := tpgresource.GetRegion(d, config) - if err != nil { - return err - } - project, err := tpgresource.GetProject(d, config) if err != nil { return err } - name := d.Get("name").(string) - d.Partial(true) if d.HasChange("health_checks") { @@ -337,35 +342,57 @@ func resourceComputeTargetPoolUpdate(d *schema.ResourceData, meta interface{}) e } add, remove := tpgresource.CalcAddRemove(fromUrls, toUrls) - removeReq := &compute.TargetPoolsRemoveHealthCheckRequest{ - HealthChecks: make([]*compute.HealthCheckReference, len(remove)), - } + removeHCs := make([]interface{}, len(remove)) for i, v := range remove { - removeReq.HealthChecks[i] = &compute.HealthCheckReference{HealthCheck: v} + removeHCs[i] = map[string]interface{}{"healthCheck": v} + } + removeReq := map[string]interface{}{ + "healthChecks": removeHCs, } - op, err := NewClient(config, userAgent).TargetPools.RemoveHealthCheck( - project, region, name, removeReq).Do() + removeHCUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}/removeHealthCheck") + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: removeHCUrl, + UserAgent: userAgent, + Body: removeReq, + }) if err != nil { return fmt.Errorf("Error updating health_check: %s", err) } - err = ComputeOperationWaitTime(config, op, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) + err = ComputeOperationWaitTime(config, res, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) if err != nil { return err } - addReq := &compute.TargetPoolsAddHealthCheckRequest{ - HealthChecks: make([]*compute.HealthCheckReference, len(add)), - } + addHCs := make([]interface{}, len(add)) for i, v := range add { - addReq.HealthChecks[i] = &compute.HealthCheckReference{HealthCheck: v} + addHCs[i] = map[string]interface{}{"healthCheck": v} + } + addReq := map[string]interface{}{ + "healthChecks": addHCs, } - op, err = NewClient(config, userAgent).TargetPools.AddHealthCheck( - project, region, name, addReq).Do() + addHCUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}/addHealthCheck") + if err != nil { + return err + } + res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: addHCUrl, + UserAgent: userAgent, + Body: addReq, + }) if err != nil { return fmt.Errorf("Error updating health_check: %s", err) } - err = ComputeOperationWaitTime(config, op, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) + err = ComputeOperationWaitTime(config, res, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) if err != nil { return err } @@ -386,34 +413,56 @@ func resourceComputeTargetPoolUpdate(d *schema.ResourceData, meta interface{}) e return err } - addReq := &compute.TargetPoolsAddInstanceRequest{ - Instances: make([]*compute.InstanceReference, len(addUrls)), - } + addInstanceRefs := make([]interface{}, len(addUrls)) for i, v := range addUrls { - addReq.Instances[i] = &compute.InstanceReference{Instance: v} + addInstanceRefs[i] = map[string]interface{}{"instance": v} } - op, err := NewClient(config, userAgent).TargetPools.AddInstance( - project, region, name, addReq).Do() + addReq := map[string]interface{}{ + "instances": addInstanceRefs, + } + addInstanceUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}/addInstance") + if err != nil { + return err + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: addInstanceUrl, + UserAgent: userAgent, + Body: addReq, + }) if err != nil { return fmt.Errorf("Error updating instances: %s", err) } - err = ComputeOperationWaitTime(config, op, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) + err = ComputeOperationWaitTime(config, res, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) if err != nil { return err } - removeReq := &compute.TargetPoolsRemoveInstanceRequest{ - Instances: make([]*compute.InstanceReference, len(removeUrls)), - } + removeInstanceRefs := make([]interface{}, len(removeUrls)) for i, v := range removeUrls { - removeReq.Instances[i] = &compute.InstanceReference{Instance: v} + removeInstanceRefs[i] = map[string]interface{}{"instance": v} + } + removeReq := map[string]interface{}{ + "instances": removeInstanceRefs, } - op, err = NewClient(config, userAgent).TargetPools.RemoveInstance( - project, region, name, removeReq).Do() + removeInstanceUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}/removeInstance") + if err != nil { + return err + } + res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: removeInstanceUrl, + UserAgent: userAgent, + Body: removeReq, + }) if err != nil { return fmt.Errorf("Error updating instances: %s", err) } - err = ComputeOperationWaitTime(config, op, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) + err = ComputeOperationWaitTime(config, res, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) if err != nil { return err } @@ -421,16 +470,26 @@ func resourceComputeTargetPoolUpdate(d *schema.ResourceData, meta interface{}) e if d.HasChange("backup_pool") { bpool_name := d.Get("backup_pool").(string) - tref := &compute.TargetReference{ - Target: bpool_name, + tref := map[string]interface{}{ + "target": bpool_name, + } + setBackupUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}/setBackup") + if err != nil { + return err } - op, err := NewClient(config, userAgent).TargetPools.SetBackup( - project, region, name, tref).Do() + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: setBackupUrl, + UserAgent: userAgent, + Body: tref, + }) if err != nil { return fmt.Errorf("Error updating backup_pool: %s", err) } - err = ComputeOperationWaitTime(config, op, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) + err = ComputeOperationWaitTime(config, res, project, "Updating Target Pool", userAgent, d.Timeout(schema.TimeoutUpdate)) if err != nil { return err } @@ -495,39 +554,47 @@ func resourceComputeTargetPoolRead(d *schema.ResourceData, meta interface{}) err return err } - region, err := tpgresource.GetRegion(d, config) + project, err := tpgresource.GetProject(d, config) if err != nil { return err } - project, err := tpgresource.GetProject(d, config) + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}") if err != nil { return err } - - tpool, err := NewClient(config, userAgent).TargetPools.Get( - project, region, d.Get("name").(string)).Do() + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Target Pool %q", d.Get("name").(string))) } - if err := d.Set("self_link", tpool.SelfLink); err != nil { + if err := d.Set("self_link", res["selfLink"]); err != nil { return fmt.Errorf("Error setting self_link: %s", err) } - if err := d.Set("backup_pool", tpool.BackupPool); err != nil { + if err := d.Set("backup_pool", res["backupPool"]); err != nil { return fmt.Errorf("Error setting backup_pool: %s", err) } - if err := d.Set("description", tpool.Description); err != nil { + if err := d.Set("description", res["description"]); err != nil { return fmt.Errorf("Error setting description: %s", err) } - if err := d.Set("failover_ratio", tpool.FailoverRatio); err != nil { + if err := d.Set("failover_ratio", res["failoverRatio"]); err != nil { return fmt.Errorf("Error setting failover_ratio: %s", err) } - if err := d.Set("health_checks", tpool.HealthChecks); err != nil { + if err := d.Set("health_checks", res["healthChecks"]); err != nil { return fmt.Errorf("Error setting health_checks: %s", err) } - if tpool.Instances != nil { - if err := d.Set("instances", convertInstancesFromUrls(tpool.Instances)); err != nil { + if rawInstances, ok := res["instances"].([]interface{}); ok { + instanceUrls := make([]string, len(rawInstances)) + for i, ri := range rawInstances { + instanceUrls[i] = ri.(string) + } + if err := d.Set("instances", convertInstancesFromUrls(instanceUrls)); err != nil { return fmt.Errorf("Error setting instances: %s", err) } } else { @@ -535,51 +602,69 @@ func resourceComputeTargetPoolRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error setting instances: %s", err) } } - if err := d.Set("name", tpool.Name); err != nil { + if err := d.Set("name", res["name"]); err != nil { return fmt.Errorf("Error setting name: %s", err) } - if err := d.Set("region", tpgresource.GetResourceNameFromSelfLink(tpool.Region)); err != nil { - return fmt.Errorf("Error setting region: %s", err) + if regionStr, ok := res["region"].(string); ok { + if err := d.Set("region", tpgresource.GetResourceNameFromSelfLink(regionStr)); err != nil { + return fmt.Errorf("Error setting region: %s", err) + } } - if err := d.Set("session_affinity", tpool.SessionAffinity); err != nil { + if err := d.Set("session_affinity", res["sessionAffinity"]); err != nil { return fmt.Errorf("Error setting session_affinity: %s", err) } if err := d.Set("project", project); err != nil { return fmt.Errorf("Error setting project: %s", err) } {{- if ne $.TargetVersionName "ga" }} - if err := d.Set("security_policy", tpool.SecurityPolicy); err != nil { + if err := d.Set("security_policy", res["securityPolicy"]); err != nil { return fmt.Errorf("Error setting security_policy: %s", err) } {{- end }} + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceComputeTargetPoolDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - region, err := tpgresource.GetRegion(d, config) + project, err := tpgresource.GetProject(d, config) if err != nil { return err } - project, err := tpgresource.GetProject(d, config) + // Delete the TargetPool + deleteUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/regions/{{"{{"}}region{{"}}"}}/targetPools/{{"{{"}}name{{"}}"}}") if err != nil { return err } - - // Delete the TargetPool - op, err := NewClient(config, userAgent).TargetPools.Delete( - project, region, d.Get("name").(string)).Do() + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: project, + RawURL: deleteUrl, + UserAgent: userAgent, + }) if err != nil { return fmt.Errorf("Error deleting TargetPool: %s", err) } - err = ComputeOperationWaitTime(config, op, project, "Deleting Target Pool", userAgent, d.Timeout(schema.TimeoutDelete)) + err = ComputeOperationWaitTime(config, res, project, "Deleting Target Pool", userAgent, d.Timeout(schema.TimeoutDelete)) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_meta.yaml.tmpl index 81b695c08317..cea78c62a803 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_meta.yaml.tmpl @@ -21,3 +21,5 @@ fields: {{- end }} - api_field: 'selfLink' - api_field: 'sessionAffinity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_test.go.tmpl index 5d8f110d6c4f..84209ac0e2af 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_pool_test.go.tmpl @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/tpgresource" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -148,7 +149,7 @@ func testAccCheckComputeTargetPoolDestroyProducer(t *testing.T) func(s *terrafor continue } - url := fmt.Sprintf("%sprojects/%s/regions/%s/targetPools/%s", config.ComputeBasePath, config.Project, config.Region, rs.Primary.Attributes["name"]) + url := fmt.Sprintf("%sprojects/%s/regions/%s/targetPools/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, config.Region, rs.Primary.Attributes["name"]) _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", @@ -178,7 +179,7 @@ func testAccCheckComputeTargetPoolExists(t *testing.T, n string) resource.TestCh config := acctest.GoogleProviderConfig(t) - url := fmt.Sprintf("%sprojects/%s/regions/%s/targetPools/%s", config.ComputeBasePath, config.Project, config.Region, rs.Primary.Attributes["name"]) + url := fmt.Sprintf("%sprojects/%s/regions/%s/targetPools/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, config.Region, rs.Primary.Attributes["name"]) found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ Config: config, Method: "GET", diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_target_ssl_proxy_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_target_ssl_proxy_test.go similarity index 86% rename from mmv1/third_party/terraform/services/compute/resource_compute_target_ssl_proxy_test.go.tmpl rename to mmv1/third_party/terraform/services/compute/resource_compute_target_ssl_proxy_test.go index f4b55d000523..da8902f7d804 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_target_ssl_proxy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_target_ssl_proxy_test.go @@ -5,17 +5,13 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" - compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} ) func TestAccComputeTargetSslProxy_update(t *testing.T) { @@ -28,7 +24,7 @@ func TestAccComputeTargetSslProxy_update(t *testing.T) { hc := fmt.Sprintf("tf-test-tssl-%s", acctest.RandString(t, 10)) resourceSuffix := acctest.RandString(t, 10) - var proxy compute.TargetSslProxy + var proxy map[string]interface{} acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -73,7 +69,7 @@ func TestAccComputeTargetSslProxy_update(t *testing.T) { }) } -func testAccCheckComputeTargetSslProxyExists(t *testing.T, n string, proxy *compute.TargetSslProxy) resource.TestCheckFunc { +func testAccCheckComputeTargetSslProxyExists(t *testing.T, n string, proxy *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -87,38 +83,53 @@ func testAccCheckComputeTargetSslProxyExists(t *testing.T, n string, proxy *comp config := acctest.GoogleProviderConfig(t) name := rs.Primary.Attributes["name"] - found, err := compute_tpg.NewClient(config, config.UserAgent).TargetSslProxies.Get( - config.Project, name).Do() + url := fmt.Sprintf("%sprojects/%s/global/targetSslProxies/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, name) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.Name != name { + if res["name"] != name { return fmt.Errorf("TargetSslProxy not found") } - *proxy = *found + *proxy = res return nil } } -func testAccCheckComputeTargetSslProxyHeader(t *testing.T, proxyHeader string, proxy *compute.TargetSslProxy) resource.TestCheckFunc { +func testAccCheckComputeTargetSslProxyHeader(t *testing.T, proxyHeader string, proxy *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if proxy.ProxyHeader != proxyHeader { - return fmt.Errorf("Wrong proxy header. Expected '%s', got '%s'", proxyHeader, proxy.ProxyHeader) + if (*proxy)["proxyHeader"] != proxyHeader { + return fmt.Errorf("Wrong proxy header. Expected '%s', got '%s'", proxyHeader, (*proxy)["proxyHeader"]) } return nil } } -func testAccCheckComputeTargetSslProxyHasSslCertificate(t *testing.T, cert string, proxy *compute.TargetSslProxy) resource.TestCheckFunc { +func testAccCheckComputeTargetSslProxyHasSslCertificate(t *testing.T, cert string, proxy *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) certURL := fmt.Sprintf(canonicalSslCertificateTemplate, config.Project, cert) - for _, sslCertificate := range proxy.SslCertificates { - if tpgresource.ConvertSelfLinkToV1(sslCertificate) == certURL { + sslCertificates, ok := (*proxy)["sslCertificates"].([]interface{}) + if !ok { + return fmt.Errorf("Ssl certificates not found in TargetSslProxy") + } + + for _, sslCertificate := range sslCertificates { + sslCertificateStr, ok := sslCertificate.(string) + if !ok { + return fmt.Errorf("Ssl certificate has unexpected type") + } + if tpgresource.ConvertSelfLinkToV1(sslCertificateStr) == certURL { return nil } } @@ -127,11 +138,15 @@ func testAccCheckComputeTargetSslProxyHasSslCertificate(t *testing.T, cert strin } } -func testAccCheckComputeTargetSslProxyHasCertificateMap(t *testing.T, certificateMap string, proxy *compute.TargetSslProxy) resource.TestCheckFunc { +func testAccCheckComputeTargetSslProxyHasCertificateMap(t *testing.T, certificateMap string, proxy *map[string]interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { config := acctest.GoogleProviderConfig(t) wantCertMapURL := fmt.Sprintf(canonicalCertificateMapTemplate, config.Project, certificateMap) - gotCertMapURL := tpgresource.ConvertSelfLinkToV1(proxy.CertificateMap) + certificateMapLink, ok := (*proxy)["certificateMap"].(string) + if !ok { + return fmt.Errorf("certificate map not found in TargetSslProxy") + } + gotCertMapURL := tpgresource.ConvertSelfLinkToV1(certificateMapLink) if wantCertMapURL != gotCertMapURL { return fmt.Errorf("certificate map not found: got %q, want %q", gotCertMapURL, wantCertMapURL) } diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_url_map_test.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_compute_url_map_test.go.tmpl index a9751722f4e1..1187af9c2e96 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_url_map_test.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_compute_url_map_test.go.tmpl @@ -3,8 +3,11 @@ package compute_test import ( "fmt" "testing" + "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" @@ -164,13 +167,19 @@ func testAccCheckComputeUrlMapExists(t *testing.T, n string) resource.TestCheckF config := acctest.GoogleProviderConfig(t) name := rs.Primary.Attributes["name"] - found, err := compute.NewClient(config, config.UserAgent).UrlMaps.Get( - config.Project, name).Do() + url := fmt.Sprintf("%sprojects/%s/global/urlMaps/%s", transport_tpg.BaseUrl(tpgcompute.Product, config), config.Project, name) + found, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: url, + UserAgent: config.UserAgent, + }) if err != nil { return err } - if found.Name != name { + if found["name"] != name { return fmt.Errorf("Url map not found") } return nil @@ -2520,4 +2529,4 @@ resource "google_compute_health_check" "default" { } } `, suffix, suffix, suffix) -} \ No newline at end of file +} diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_vpn_tunnel_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_vpn_tunnel_test.go index df53b21822b4..3b394eac50a6 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_vpn_tunnel_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_vpn_tunnel_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/compute/resource_compute_wire_group_test.go b/mmv1/third_party/terraform/services/compute/resource_compute_wire_group_test.go index 23e2f59c95c6..52dca2b14f1f 100644 --- a/mmv1/third_party/terraform/services/compute/resource_compute_wire_group_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_compute_wire_group_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccComputeWireGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket.go.tmpl b/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket.go.tmpl index 93e9e8a06025..fc40991e6391 100644 --- a/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket.go.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket.go.tmpl @@ -11,18 +11,13 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - -{{ if eq $.TargetVersionName `ga` }} - "google.golang.org/api/compute/v1" -{{- else }} - compute "google.golang.org/api/compute/v0.beta" -{{- end }} ) func ResourceProjectUsageBucket() *schema.Resource { return &schema.Resource{ Create: resourceProjectUsageBucketCreate, Read: resourceProjectUsageBucketRead, + Update: resourceProjectUsageBucketUpdate, Delete: resourceProjectUsageBucketDelete, Importer: &schema.ResourceImporter{ State: resourceProjectUsageBucketImportState, @@ -35,6 +30,7 @@ func ResourceProjectUsageBucket() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -57,6 +53,9 @@ func ResourceProjectUsageBucket() *schema.Resource { ForceNew: true, Description: `The project to set the export bucket on. If it is not provided, the provider project is used.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -64,7 +63,7 @@ func ResourceProjectUsageBucket() *schema.Resource { func resourceProjectUsageBucketRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -74,12 +73,24 @@ func resourceProjectUsageBucketRead(d *schema.ResourceData, meta interface{}) er return err } - p, err := NewClient(config, userAgent).Projects.Get(project).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}") + if err != nil { + return err + } + url = fmt.Sprintf("%sprojects/%s", url, project) + p, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: userAgent, + }) if err != nil { return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Project data for project %s", project)) } - if p.UsageExportLocation == nil { + usageExportLocation, ok := p["usageExportLocation"].(map[string]interface{}) + if !ok || usageExportLocation == nil { log.Printf("[WARN] Removing usage export location resource %s because it's not enabled server-side.", project) d.SetId("") return nil @@ -88,18 +99,23 @@ func resourceProjectUsageBucketRead(d *schema.ResourceData, meta interface{}) er if err := d.Set("project", project); err != nil { return fmt.Errorf("Error setting project: %s", err) } - if err := d.Set("prefix", p.UsageExportLocation.ReportNamePrefix); err != nil { + if err := d.Set("prefix", usageExportLocation["reportNamePrefix"]); err != nil { return fmt.Errorf("Error setting prefix: %s", err) } - if err := d.Set("bucket_name", p.UsageExportLocation.BucketName); err != nil { + if err := d.Set("bucket_name", usageExportLocation["bucketName"]); err != nil { return fmt.Errorf("Error setting bucket_name: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceProjectUsageBucketCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -109,10 +125,25 @@ func resourceProjectUsageBucketCreate(d *schema.ResourceData, meta interface{}) return err } - op, err := NewClient(config, userAgent).Projects.SetUsageExportBucket(project, &compute.UsageExportLocation{ - ReportNamePrefix: d.Get("prefix").(string), - BucketName: d.Get("bucket_name").(string), - }).Do() + body := map[string]interface{}{ + "reportNamePrefix": d.Get("prefix").(string), + "bucketName": d.Get("bucket_name").(string), + } + + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}") + if err != nil { + return err + } + url = fmt.Sprintf("%sprojects/%s/setUsageExportBucket", url, project) + op, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: body, + Timeout: d.Timeout(schema.TimeoutCreate), + }) if err != nil { return err } @@ -130,9 +161,23 @@ func resourceProjectUsageBucketCreate(d *schema.ResourceData, meta interface{}) return resourceProjectUsageBucketRead(d, meta) } +//UDP update start +func resourceProjectUsageBucketUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceProjectUsageBucketRead(d, meta) +} +//UDP update end + func resourceProjectUsageBucketDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } @@ -142,7 +187,19 @@ func resourceProjectUsageBucketDelete(d *schema.ResourceData, meta interface{}) return err } - op, err := NewClient(config, userAgent).Projects.SetUsageExportBucket(project, nil).Do() + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}") + if err != nil { + return err + } + url = fmt.Sprintf("%sprojects/%s/setUsageExportBucket", url, project) + op, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: userAgent, + Timeout: d.Timeout(schema.TimeoutDelete), + }) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_meta.yaml.tmpl b/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_meta.yaml.tmpl index 9d229708fa20..c1bf06bc340c 100644 --- a/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_meta.yaml.tmpl @@ -13,3 +13,5 @@ fields: - api_field: 'usageExportLocation.reportNamePrefix' field: 'prefix' - field: 'project' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_test.go b/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_test.go index 9f498bbb9efb..b3e8ab9ac121 100644 --- a/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_test.go +++ b/mmv1/third_party/terraform/services/compute/resource_project_usage_export_bucket_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccComputeResourceUsageExportBucket(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/compute/stateful_mig_polling.go b/mmv1/third_party/terraform/services/compute/stateful_mig_polling.go index fa22c2ec1d00..7163fea2b937 100644 --- a/mmv1/third_party/terraform/services/compute/stateful_mig_polling.go +++ b/mmv1/third_party/terraform/services/compute/stateful_mig_polling.go @@ -18,7 +18,7 @@ func resourceComputePerInstanceConfigPollRead(d *schema.ResourceData, meta inter return nil, err } - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/instanceGroupManagers/{{instance_group_manager}}/listPerInstanceConfigs") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/zones/{{zone}}/instanceGroupManagers/{{instance_group_manager}}/listPerInstanceConfigs") if err != nil { return nil, err } @@ -56,7 +56,7 @@ func resourceComputePerInstanceConfigInstancePollRead(d *schema.ResourceData, me return nil, err } - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/zones/{{zone}}/instanceGroupManagers/{{instance_group_manager}}/listManagedInstances") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/zones/{{zone}}/instanceGroupManagers/{{instance_group_manager}}/listManagedInstances") if err != nil { return nil, err } @@ -108,7 +108,7 @@ func resourceComputeRegionPerInstanceConfigPollRead(d *schema.ResourceData, meta return nil, err } - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/instanceGroupManagers/{{region_instance_group_manager}}/listPerInstanceConfigs") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/regions/{{region}}/instanceGroupManagers/{{region_instance_group_manager}}/listPerInstanceConfigs") if err != nil { return nil, err } @@ -146,7 +146,7 @@ func resourceComputeRegionPerInstanceConfigInstancePollRead(d *schema.ResourceDa return nil, err } - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/instanceGroupManagers/{{region_instance_group_manager}}/listManagedInstances") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/regions/{{region}}/instanceGroupManagers/{{region_instance_group_manager}}/listManagedInstances") if err != nil { return nil, err } @@ -192,7 +192,7 @@ func resourceComputeRegionPerInstanceConfigInstancePollRead(d *schema.ResourceDa // Returns an instance name in the form zones/{zone}/instances/{instance} for the managed // instance matching the name of a PerInstanceConfig func findInstanceName(d *schema.ResourceData, config *transport_tpg.Config) (string, error) { - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/instanceGroupManagers/{{region_instance_group_manager}}/listManagedInstances") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/regions/{{region}}/instanceGroupManagers/{{region_instance_group_manager}}/listManagedInstances") if err != nil { return "", err } diff --git a/mmv1/third_party/terraform/services/config/resource_config_deployment_test.go b/mmv1/third_party/terraform/services/config/resource_config_deployment_test.go new file mode 100644 index 000000000000..b33f2ba735c9 --- /dev/null +++ b/mmv1/third_party/terraform/services/config/resource_config_deployment_test.go @@ -0,0 +1,314 @@ +package config_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudbuild" + _ "github.com/hashicorp/terraform-provider-google/google/services/config" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "google.golang.org/api/googleapi" +) + +func TestAccConfigDeployment_basic(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "project": envvar.GetTestProjectFromEnv(), + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckConfigDeploymentDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccConfigDeployment_basic(context), + }, + { + ResourceName: "google_config_deployment.basic", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "force_destroy", "labels", "annotations"}, + }, + { + Config: testAccConfigDeployment_update(context), + }, + { + ResourceName: "google_config_deployment.basic", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "force_destroy", "labels", "annotations"}, + }, + }, + }) +} + +func testAccConfigDeployment_basic(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_service_account" "sa" { + account_id = "im-basic-test-sa-%{random_suffix}" + display_name = "Infra Manager Basic Test SA" +} + +resource "google_project_iam_member" "binding" { + project = "%{project}" + role = "roles/config.agent" + member = "serviceAccount:${google_service_account.sa.email}" +} + +resource "google_project_iam_member" "network_admin" { + project = "%{project}" + role = "roles/compute.networkAdmin" + member = "serviceAccount:${google_service_account.sa.email}" +} + +resource "google_config_deployment" "basic" { + name = "tf-test-basic-deployment-%{random_suffix}" + location = "us-central1" + service_account = "projects/%{project}/serviceAccounts/${google_service_account.sa.email}" + force_destroy = true + + terraform_blueprint { + git_source { + repo = "https://github.com/terraform-google-modules/terraform-google-network" + directory = "modules/vpc" + ref = "main" + } + + input_values { + variable_name = "project_id" + input_value = jsonencode("%{project}") + } + input_values { + variable_name = "network_name" + input_value = jsonencode("test-network-%{random_suffix}") + } + } + + depends_on = [ + google_project_iam_member.binding, + google_project_iam_member.network_admin + ] +} +`, context) +} + +func testAccConfigDeployment_update(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_service_account" "sa" { + account_id = "im-basic-test-sa-%{random_suffix}" + display_name = "Infra Manager Basic Test SA" +} + +resource "google_project_iam_member" "binding" { + project = "%{project}" + role = "roles/config.agent" + member = "serviceAccount:${google_service_account.sa.email}" +} + +resource "google_project_iam_member" "network_admin" { + project = "%{project}" + role = "roles/compute.networkAdmin" + member = "serviceAccount:${google_service_account.sa.email}" +} + +resource "google_cloudbuild_worker_pool" "pool" { + name = "tf-test-wp-%{random_suffix}" + location = "us-central1" + worker_config { + disk_size_gb = 100 + machine_type = "e2-standard-8" + no_external_ip = false + } +} + +resource "google_config_deployment" "basic" { + name = "tf-test-basic-deployment-%{random_suffix}" + location = "us-central1" + service_account = "projects/%{project}/serviceAccounts/${google_service_account.sa.email}" + force_destroy = true + + labels = { + env = "test" + } + + quota_validation = "ENABLED" + import_existing_resources = true + tf_version_constraint = "=1.5.7" + worker_pool = google_cloudbuild_worker_pool.pool.id + + terraform_blueprint { + git_source { + repo = "https://github.com/terraform-google-modules/terraform-google-network" + directory = "modules/vpc" + ref = "main" + } + + input_values { + variable_name = "project_id" + input_value = jsonencode("%{project}") + } + input_values { + variable_name = "network_name" + input_value = jsonencode("test-network-%{random_suffix}") + } + } + + depends_on = [ + google_project_iam_member.binding, + google_project_iam_member.network_admin + ] +} +`, context) +} + +func TestAccConfigDeployment_full(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "project": envvar.GetTestProjectFromEnv(), + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckConfigDeploymentDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccConfigDeployment_full(context), + }, + { + ResourceName: "google_config_deployment.full", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "force_destroy", "labels", "annotations"}, + }, + }, + }) +} + +func testAccConfigDeployment_full(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_service_account" "sa" { + account_id = "im-full-test-sa-%{random_suffix}" + display_name = "Infra Manager Full Test SA" +} + +resource "google_project_iam_member" "binding" { + project = "%{project}" + role = "roles/config.agent" + member = "serviceAccount:${google_service_account.sa.email}" +} + +resource "google_project_iam_member" "storage_viewer" { + project = "%{project}" + role = "roles/storage.objectViewer" + member = "serviceAccount:${google_service_account.sa.email}" +} + +resource "google_storage_bucket" "blueprint_bucket" { + name = "im-blueprint-bucket-%{random_suffix}" + location = "US" + force_destroy = true +} + +resource "google_storage_bucket_object" "blueprint_object" { + name = "blueprint.zip" + bucket = google_storage_bucket.blueprint_bucket.name + source = "test-fixtures/blueprint.zip" +} + +resource "google_storage_bucket" "artifacts_bucket" { + name = "im-artifacts-bucket-%{random_suffix}" + location = "US" + force_destroy = true +} + +resource "google_config_deployment" "full" { + name = "tf-test-full-deployment-%{random_suffix}" + location = "us-central1" + service_account = "projects/%{project}/serviceAccounts/${google_service_account.sa.email}" + force_destroy = true + + labels = { + environment = "test" + } + + annotations = { + purpose = "full-field-testing" + } + + terraform_blueprint { + gcs_source = "gs://${google_storage_bucket.blueprint_bucket.name}/${google_storage_bucket_object.blueprint_object.name}" + + input_values { + variable_name = "instance_name" + input_value = jsonencode("test-instance-%{random_suffix}") + } + } + + artifacts_gcs_bucket = "gs://${google_storage_bucket.artifacts_bucket.name}" + + depends_on = [ + google_project_iam_member.binding, + google_project_iam_member.storage_viewer + ] +} +`, context) +} + +func testAccCheckConfigDeploymentDestroyProducer(t *testing.T) resource.TestCheckFunc { + return func(s *terraform.State) error { + config := acctest.GoogleProviderConfig(t) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "google_config_deployment" { + continue + } + + if rs.Primary.ID == "" { + return fmt.Errorf("Unable to verify delete of deployment ID is empty") + } + + project, err := acctest.GetTestProject(rs.Primary, config) + if err != nil { + return err + } + + parts := strings.Split(rs.Primary.ID, "/") + deployment_id := parts[len(parts)-1] + location := rs.Primary.Attributes["location"] + + url := fmt.Sprintf("https://config.googleapis.com/v1/projects/%s/locations/%s/deployments/%s", project, location, deployment_id) + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) + if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { + return nil + } else if ok { + return fmt.Errorf("Error making GCP platform call: http code error : %d, http message error: %s", gerr.Code, gerr.Message) + } + return fmt.Errorf("Error making GCP platform call: %s", err.Error()) + } + return fmt.Errorf("Deployment still exists") + } + + return nil + } +} diff --git a/mmv1/third_party/terraform/services/config/test-fixtures/blueprint.zip b/mmv1/third_party/terraform/services/config/test-fixtures/blueprint.zip new file mode 100644 index 000000000000..3e5925bc478d Binary files /dev/null and b/mmv1/third_party/terraform/services/config/test-fixtures/blueprint.zip differ diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/contactcenterinsights_operation.go b/mmv1/third_party/terraform/services/contactcenterinsights/contactcenterinsights_operation.go new file mode 100644 index 000000000000..c2f13849be97 --- /dev/null +++ b/mmv1/third_party/terraform/services/contactcenterinsights/contactcenterinsights_operation.go @@ -0,0 +1,87 @@ +package contactcenterinsights + +import ( + "fmt" + "regexp" + "strings" + "time" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +type ContactCenterInsightsOperationWaiter struct { + Config *transport_tpg.Config + UserAgent string + Project string + tpgresource.CommonOperationWaiter +} + +// QueryOp is handwritten because Contact Center Insights requires regional endpoints +// for non-global regions. We need to extract the location from the operation name +// and construct the correct regional URL. The default Magic Modules generator +// does not support this dynamic endpoint switching based on operation name. +func (w *ContactCenterInsightsOperationWaiter) QueryOp() (interface{}, error) { + if w == nil { + return nil, fmt.Errorf("Cannot query operation, it's unset or nil.") + } + + // Extract location from operation name (e.g., projects/.../locations/us-east1/operations/...) + location := "" + if parts := regexp.MustCompile(`locations\/([^\/]*)\/`).FindStringSubmatch(w.CommonOperationWaiter.Op.Name); parts != nil { + location = parts[1] + } else { + return nil, fmt.Errorf( + "Saw %s when the op name is expected to contains location %s", + w.CommonOperationWaiter.Op.Name, + "projects/{{project}}/locations/{{location}}/...", + ) + } + + // Construct the regional endpoint URL + url := fmt.Sprintf("https://%s-contactcenterinsights.googleapis.com/v1/%s", location, w.CommonOperationWaiter.Op.Name) + + // For historical reasons, us-central1 acts as the global endpoint and does not use a prefix. + // See: https://docs.cloud.google.com/contact-center/insights/docs/regionalization + if location == "us-central1" { + url = fmt.Sprintf("https://contactcenterinsights.googleapis.com/v1/%s", w.CommonOperationWaiter.Op.Name) + } + + // Handle custom universe domain + universeDomain := w.Config.UniverseDomain + if universeDomain != "" && universeDomain != "googleapis.com" { + url = strings.Replace(url, "googleapis.com", universeDomain, 1) + } + + return transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: w.Config, + Method: "GET", + Project: w.Project, + RawURL: url, + UserAgent: w.UserAgent, + }) +} + +func createContactCenterInsightsWaiter(config *transport_tpg.Config, op map[string]interface{}, project, activity, userAgent string) (*ContactCenterInsightsOperationWaiter, error) { + w := &ContactCenterInsightsOperationWaiter{ + Config: config, + UserAgent: userAgent, + Project: project, + } + if err := w.CommonOperationWaiter.SetOp(op); err != nil { + return nil, err + } + return w, nil +} + +func ContactCenterInsightsOperationWaitTime(config *transport_tpg.Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error { + if val, ok := op["name"]; !ok || val == "" { + // This was a synchronous call - there is no operation to wait for. + return nil + } + w, err := createContactCenterInsightsWaiter(config, op, project, activity, userAgent) + if err != nil { + return err + } + return tpgresource.OperationWait(w, activity, timeout, config.PollInterval) +} diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_analysis_rule_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_analysis_rule_test.go index 08d87a18f658..e1c04a128f24 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_analysis_rule_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_analysis_rule_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsAnalysisRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_assessment_rule_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_assessment_rule_test.go index c79897cf3388..f7a79d491909 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_assessment_rule_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_assessment_rule_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsAssessmentRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_auto_labeling_rule_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_auto_labeling_rule_test.go index d7f99fe90001..5109e7be724a 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_auto_labeling_rule_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_auto_labeling_rule_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsAutoLabelingRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_question_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_question_test.go index 6970c9c9b134..d4221adb33c4 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_question_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_question_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsQaQuestion_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_revision_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_revision_test.go index cbac4aa97a03..2a6d4d10ae42 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_revision_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_revision_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsQaScorecardRevision_qaScorecardRevisionOptional(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_test.go index 18b630cf55f3..9413ec862409 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_qa_scorecard_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsQaScorecard_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_view_test.go b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_view_test.go index f2ddc54cd7b8..b127a23c0b6a 100644 --- a/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_view_test.go +++ b/mmv1/third_party/terraform/services/contactcenterinsights/resource_contact_center_insights_view_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/contactcenterinsights" ) func TestAccContactCenterInsightsView_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/container/data_source_google_container_cluster_test.go b/mmv1/third_party/terraform/services/container/data_source_google_container_cluster_test.go index d00914820c6c..321e759cf05b 100644 --- a/mmv1/third_party/terraform/services/container/data_source_google_container_cluster_test.go +++ b/mmv1/third_party/terraform/services/container/data_source_google_container_cluster_test.go @@ -6,13 +6,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" ) func TestAccContainerClusterDatasource_zonal(t *testing.T) { t.Parallel() - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -35,8 +37,8 @@ func TestAccContainerClusterDatasource_zonal(t *testing.T) { func TestAccContainerClusterDatasource_regional(t *testing.T) { t.Parallel() - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/container/node_config.go.tmpl b/mmv1/third_party/terraform/services/container/node_config.go.tmpl index d1d218fcc13b..bd1126fc312e 100644 --- a/mmv1/third_party/terraform/services/container/node_config.go.tmpl +++ b/mmv1/third_party/terraform/services/container/node_config.go.tmpl @@ -272,6 +272,14 @@ func schemaNodeConfig() *schema.Schema { "boot_disk": schemaBootDiskConfig(), + "gpudirect_strategy": { + Type: schema.TypeString, + Optional: true, + Computed: true, + DiffSuppressFunc: tpgresource.CaseDiffSuppress, + Description: `The type of GPUDirect strategy to enable on the node.`, + }, + "guest_accelerator": { Type: schema.TypeList, Optional: true, @@ -1503,6 +1511,10 @@ func expandNodeConfig(d *schema.ResourceData, prefix string, v interface{}) *con nc.MachineType = v.(string) } + if v, ok := nodeConfig["gpudirect_strategy"]; ok { + nc.GpuDirectConfig = expandGpuDirectConfig(v) + } + if v, ok := nodeConfig["guest_accelerator"]; ok { accels := v.([]interface{}) guestAccelerators := make([]*container.AcceleratorConfig, 0, len(accels)) @@ -1857,6 +1869,17 @@ func expandNodeConfig(d *schema.ResourceData, prefix string, v interface{}) *con return nc } +// GPUDirectConfig is currently directly stored as a GpuDirectStrategy string. +func expandGpuDirectConfig(v interface{}) *container.GPUDirectConfig { + if v == nil || v.(string) == "" { + return nil + } + + return &container.GPUDirectConfig{ + GpuDirectStrategy: v.(string), + } +} + func expandBootDiskConfig(v interface{}) *container.BootDisk { bd := &container.BootDisk{} if v == nil { @@ -2743,6 +2766,7 @@ func flattenNodeConfig(c *container.NodeConfig, v interface{}) []map[string]inte "disk_size_gb": c.DiskSizeGb, "disk_type": c.DiskType, "boot_disk": flattenBootDiskConfig(c.BootDisk), + "gpudirect_strategy": flattenGpuDirectConfig(c.GpuDirectConfig), "guest_accelerator": flattenContainerGuestAccelerators(c.Accelerators), "local_ssd_count": c.LocalSsdCount, "logging_variant": flattenLoggingVariant(c.LoggingConfig), @@ -2827,6 +2851,15 @@ func flattenResourceManagerTags(c *container.ResourceManagerTags) map[string]int return rmt } +// GPUDirectConfig currently only has one field, flatten directly to string. +func flattenGpuDirectConfig(c *container.GPUDirectConfig) string { + if c == nil { + return "" + } + + return c.GpuDirectStrategy +} + func flattenAdvancedMachineFeaturesConfig(c *container.AdvancedMachineFeatures) []map[string]interface{} { result := []map[string]interface{}{} if c != nil { diff --git a/mmv1/third_party/terraform/services/container/resource_container_cluster.go.tmpl b/mmv1/third_party/terraform/services/container/resource_container_cluster.go.tmpl index b766c3131c28..d5690475e607 100644 --- a/mmv1/third_party/terraform/services/container/resource_container_cluster.go.tmpl +++ b/mmv1/third_party/terraform/services/container/resource_container_cluster.go.tmpl @@ -101,10 +101,11 @@ var ( "addons_config.0.parallelstore_csi_driver_config", "addons_config.0.lustre_csi_driver_config", "addons_config.0.slice_controller_config", + "addons_config.0.pod_snapshot_config", {{- if ne $.TargetVersionName "ga" }} + "addons_config.0.agent_sandbox_config", "addons_config.0.istio_config", "addons_config.0.kalm_config", - "addons_config.0.pod_snapshot_config", {{- end }} } @@ -231,6 +232,7 @@ func ResourceContainerCluster() *schema.Resource { Delete: resourceContainerClusterDelete, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), resourceNodeConfigEmptyGuestAccelerator, customdiff.ForceNewIfChange("enable_l4_ilb_subsetting", isBeenEnabled), customdiff.ForceNewIfChange("enable_fqdn_network_policy", isBeenEnabled), @@ -527,6 +529,23 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, + "pod_snapshot_config": { + Type: schema.TypeList, + Optional: true, + Computed: true, + AtLeastOneOf: addonsConfigKeys, + MaxItems: 1, + Description: `Configuration for the Pod Snapshot feature.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Required: true, + Description: `Whether the Pod Snapshot feature is enabled for this cluster.`, + }, + }, + }, + }, {{- if ne $.TargetVersionName "ga" }} "istio_config": { Type: schema.TypeList, @@ -569,23 +588,6 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, - "pod_snapshot_config": { - Type: schema.TypeList, - Optional: true, - Computed: true, - AtLeastOneOf: addonsConfigKeys, - MaxItems: 1, - Description: `Configuration for the Pod Snapshot feature.`, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "enabled": { - Type: schema.TypeBool, - Required: true, - Description: `Whether the Pod Snapshot feature is enabled for this cluster.`, - }, - }, - }, - }, {{- end }} "config_connector_config": { Type: schema.TypeList, @@ -682,6 +684,25 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, + {{- if ne $.TargetVersionName "ga" }} + "agent_sandbox_config": { + Type: schema.TypeList, + Optional: true, + Computed: true, + AtLeastOneOf: addonsConfigKeys, + MaxItems: 1, + Description: `The status of the Agent Sandbox addon. It is disabled by default. Set enabled = true to enable.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Required: true, + Description: `Whether the Agent Sandbox feature is enabled.`, + }, + }, + }, + }, + {{- end }} }, }, }, @@ -1810,7 +1831,6 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, -{{ if ne $.TargetVersionName `ga` -}} "secret_sync_config": { Type: schema.TypeList, Optional: true, @@ -1849,7 +1869,6 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, -{{- end }} "project": { Type: schema.TypeString, Optional: true, @@ -2863,6 +2882,9 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -3025,9 +3047,7 @@ func resourceContainerClusterCreate(d *schema.ResourceData, meta interface{}) er {{- end }} PodAutoscaling: expandPodAutoscaling(d.Get("pod_autoscaling")), SecretManagerConfig: expandSecretManagerConfig(d.Get("secret_manager_config")), -{{- if ne $.TargetVersionName "ga" }} SecretSyncConfig: expandSecretSyncConfig(d.Get("secret_sync_config")), -{{- end }} Autoscaling: expandClusterAutoscaling(d.Get("cluster_autoscaling"), d), BinaryAuthorization: expandBinaryAuthorization(d.Get("binary_authorization")), Autopilot: &container.Autopilot{ @@ -3761,12 +3781,9 @@ func resourceContainerClusterRead(d *schema.ResourceData, meta interface{}) erro if err := d.Set("secret_manager_config", flattenSecretManagerConfig(cluster.SecretManagerConfig)); err != nil { return err } -{{ if ne $.TargetVersionName `ga` -}} if err := d.Set("secret_sync_config", flattenSecretSyncConfig(cluster.SecretSyncConfig)); err != nil { return err } -{{- end }} - if err := tpgresource.SetLabels(cluster.ResourceLabels, d, "resource_labels"); err != nil { return fmt.Errorf("Error setting labels: %s", err) } @@ -3857,10 +3874,20 @@ func resourceContainerClusterRead(d *schema.ResourceData, meta interface{}) erro return err } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceContainerClusterUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceContainerCluster) { + return ResourceContainerCluster().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -5021,7 +5048,6 @@ func resourceContainerClusterUpdate(d *schema.ResourceData, meta interface{}) er log.Printf("[INFO] GKE cluster %s secret manager csi add-on has been updated", d.Id()) } -{{ if ne $.TargetVersionName `ga` -}} if d.HasChange("secret_sync_config") { req := &container.UpdateClusterRequest{} if c, ok := d.GetOk("secret_sync_config"); !ok { @@ -5041,7 +5067,6 @@ func resourceContainerClusterUpdate(d *schema.ResourceData, meta interface{}) er return err } } -{{- end }} if d.HasChange("workload_identity_config") { // Because GKE uses a non-RESTful update function, when removing the @@ -5654,7 +5679,14 @@ func resourceContainerClusterUpdate(d *schema.ResourceData, meta interface{}) er } func resourceContainerClusterDelete(d *schema.ResourceData, meta interface{}) error { - if d.Get("deletion_protection").(bool) { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + + if d.Get("deletion_protection").(bool) { return fmt.Errorf("Cannot destroy cluster because deletion_protection is set to true. Set it to false to proceed with cluster deletion.") } config := meta.(*transport_tpg.Config) @@ -5918,6 +5950,24 @@ func expandClusterAddonsConfig(configured interface{}) *container.AddonsConfig { } } + if v, ok := config["pod_snapshot_config"]; ok && len(v.([]interface{})) > 0 { + addon := v.([]interface{})[0].(map[string]interface{}) + ac.PodSnapshotConfig = &container.PodSnapshotConfig{ + Enabled: addon["enabled"].(bool), + ForceSendFields: []string{"Enabled"}, + } + } + +{{ if ne $.TargetVersionName `ga` -}} + if v, ok := config["agent_sandbox_config"]; ok && len(v.([]interface{})) > 0 { + addon := v.([]interface{})[0].(map[string]interface{}) + ac.AgentSandboxConfig = &container.AgentSandboxConfig{ + Enabled: addon["enabled"].(bool), + ForceSendFields: []string{"Enabled"}, + } + } +{{- end }} + {{ if ne $.TargetVersionName `ga` -}} if v, ok := config["istio_config"]; ok && len(v.([]interface{})) > 0 { addon := v.([]interface{})[0].(map[string]interface{}) @@ -5935,14 +5985,6 @@ func expandClusterAddonsConfig(configured interface{}) *container.AddonsConfig { ForceSendFields: []string{"Enabled"}, } } - - if v, ok := config["pod_snapshot_config"]; ok && len(v.([]interface{})) > 0 { - addon := v.([]interface{})[0].(map[string]interface{}) - ac.PodSnapshotConfig = &container.PodSnapshotConfig{ - Enabled: addon["enabled"].(bool), - ForceSendFields: []string{"Enabled"}, - } - } {{- end }} return ac @@ -7024,7 +7066,6 @@ func expandSecretManagerConfig(configured interface{}) *container.SecretManagerC return sc } -{{ if ne $.TargetVersionName `ga` -}} func expandSecretSyncConfig(configured interface{}) *container.SecretSyncConfig { l := configured.([]interface{}) if len(l) == 0 || l[0] == nil { @@ -7055,7 +7096,6 @@ func expandSecretSyncConfig(configured interface{}) *container.SecretSyncConfig } return sc } -{{- end }} func expandDefaultMaxPodsConstraint(v interface{}) *container.MaxPodsConstraint { if v == nil { @@ -7627,6 +7667,23 @@ func flattenClusterAddonsConfig(c *container.AddonsConfig) []map[string]interfac }, } } + if c.PodSnapshotConfig != nil { + result["pod_snapshot_config"] = []map[string]interface{}{ + { + "enabled": c.PodSnapshotConfig.Enabled, + }, + } + } + +{{ if ne $.TargetVersionName `ga` -}} + if c.AgentSandboxConfig != nil { + result["agent_sandbox_config"] = []map[string]interface{}{ + { + "enabled": c.AgentSandboxConfig.Enabled, + }, + } + } +{{- end }} {{ if ne $.TargetVersionName `ga` -}} if c.IstioConfig != nil { @@ -7645,14 +7702,6 @@ func flattenClusterAddonsConfig(c *container.AddonsConfig) []map[string]interfac }, } } - - if c.PodSnapshotConfig != nil { - result["pod_snapshot_config"] = []map[string]interface{}{ - { - "enabled": c.PodSnapshotConfig.Enabled, - }, - } - } {{- end }} return []map[string]interface{}{result} @@ -8253,7 +8302,6 @@ func flattenSecretManagerConfig(c *container.SecretManagerConfig) []map[string]i return []map[string]interface{}{result} } -{{ if ne $.TargetVersionName `ga` -}} func flattenSecretSyncConfig(c *container.SecretSyncConfig) []map[string]interface{} { if c == nil { return []map[string]interface{}{ @@ -8280,8 +8328,6 @@ func flattenSecretSyncConfig(c *container.SecretSyncConfig) []map[string]interfa result["rotation_config"] = rotationList return []map[string]interface{}{result} } -{{- end }} - func flattenResourceUsageExportConfig(c *container.ResourceUsageExportConfig) []map[string]interface{} { if c == nil { @@ -8843,7 +8889,6 @@ func DatabaseEncryptionSuppress(k, old, new string, d *schema.ResourceData) bool return false } -{{ if ne $.TargetVersionName `ga` -}} func SecretSyncCfgSuppress(k, old, new string, r *schema.ResourceData) bool { if k == "secret_sync_config.#" && old == "1" && new == "0" { if v, ok := r.GetOk("secret_sync_config"); ok { @@ -8857,7 +8902,6 @@ func SecretSyncCfgSuppress(k, old, new string, r *schema.ResourceData) bool { } return false } -{{- end }} func containerClusterNetworkPolicyDiffSuppress(k, old, new string, r *schema.ResourceData) bool { // if network_policy configuration is empty, we store it as populated and enabled=false, and @@ -9121,6 +9165,30 @@ func clusterAcceleratorNetworkProfileCustomizeDiff(_ context.Context, diff *sche return nil } +{{ if ne $.TargetVersionName `ga` -}} +func expandAgentSandboxConfig(v interface{}) *container.AgentSandboxConfig { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil + } + raw := l[0].(map[string]interface{}) + return &container.AgentSandboxConfig{ + Enabled: raw["enabled"].(bool), + } +} + +func flattenAgentSandboxConfig(v *container.AgentSandboxConfig) []interface{} { + if v == nil { + return nil + } + return []interface{}{ + map[string]interface{}{ + "enabled": v.Enabled, + }, + } +} +{{- end }} + func init() { registry.Schema{ Name: "google_container_cluster", diff --git a/mmv1/third_party/terraform/services/container/resource_container_cluster_meta.yaml.tmpl b/mmv1/third_party/terraform/services/container/resource_container_cluster_meta.yaml.tmpl index 495fad013924..35fc314ab6b5 100644 --- a/mmv1/third_party/terraform/services/container/resource_container_cluster_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/container/resource_container_cluster_meta.yaml.tmpl @@ -13,6 +13,9 @@ cai_asset_name_formats: - {{"//container.googleapis.com/projects/{{project}}/locations/{{location}}/clusters/{{name}}"}} - {{"//container.googleapis.com/projects/{{project}}/zones/{{location}}/clusters/{{name}}"}} fields: +{{- if ne $.TargetVersionName "ga" }} + - api_field: 'addonsConfig.agentSandboxConfig.enabled' +{{- end }} - field: 'addons_config.cloudrun_config.disabled' api_field: 'addonsConfig.cloudRunConfig.disabled' - field: 'addons_config.cloudrun_config.load_balancer_type' @@ -25,6 +28,7 @@ fields: - api_field: 'addonsConfig.gkeBackupAgentConfig.enabled' - api_field: 'addonsConfig.horizontalPodAutoscaling.disabled' - api_field: 'addonsConfig.httpLoadBalancing.disabled' + - api_field: 'addonsConfig.podSnapshotConfig.enabled' {{- if ne $.TargetVersionName "ga" }} - api_field: 'addonsConfig.istioConfig.auth' {{- end }} @@ -33,7 +37,6 @@ fields: {{- end }} {{- if ne $.TargetVersionName "ga" }} - api_field: 'addonsConfig.kalmConfig.enabled' - - api_field: 'addonsConfig.podSnapshotConfig.enabled' {{- end }} - api_field: 'addonsConfig.lustreCsiDriverConfig.enableLegacyLustrePort' - api_field: 'addonsConfig.lustreCsiDriverConfig.disableMultiNic' @@ -681,6 +684,10 @@ fields: api_field: 'nodePools.config.loggingConfig.variantConfig.variant' - field: 'node_pool.node_config.machine_type' api_field: 'nodePools.config.machineType' + - field: 'node_config.gpudirect_strategy' + api_field: 'nodeConfig.gpuDirectConfig.gpuDirectStrategy' + - field: 'node_pool.node_config.gpudirect_strategy' + api_field: 'nodePools.config.gpuDirectConfig.gpuDirectStrategy' - field: 'node_pool.node_config.max_run_duration' api_field: 'nodePools.config.maxRunDuration' - field: 'node_pool.node_config.metadata' @@ -843,11 +850,9 @@ fields: - api_field: 'secretManagerConfig.enabled' - api_field: 'secretManagerConfig.rotationConfig.enabled' - api_field: 'secretManagerConfig.rotationConfig.rotationInterval' -{{- if ne $.TargetVersionName "ga" }} - api_field: 'secretSyncConfig.enabled' - api_field: 'secretSyncConfig.rotationConfig.enabled' - api_field: 'secretSyncConfig.rotationConfig.rotationInterval' -{{- end }} - api_field: 'securityPostureConfig.mode' - api_field: 'securityPostureConfig.vulnerabilityMode' - api_field: 'selfLink' @@ -881,3 +886,5 @@ fields: - api_field: 'workloadAltsConfig.enableAlts' {{- end }} - api_field: 'workloadIdentityConfig.workloadPool' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/container/resource_container_cluster_test.go.tmpl b/mmv1/third_party/terraform/services/container/resource_container_cluster_test.go.tmpl index 3570e000ccd8..fbc48046b94a 100644 --- a/mmv1/third_party/terraform/services/container/resource_container_cluster_test.go.tmpl +++ b/mmv1/third_party/terraform/services/container/resource_container_cluster_test.go.tmpl @@ -11,13 +11,21 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/container" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" cloudkms "google.golang.org/api/cloudkms/v1" ) func bootstrapGkeTagManagerServiceAgents(t *testing.T) { - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@container-engine-robot.iam.gserviceaccount.com", Role: "roles/resourcemanager.tagAdmin", @@ -41,8 +49,8 @@ func TestAccContainerCluster_basic(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -86,8 +94,8 @@ func TestAccContainerCluster_basic_noCpaUpgrade(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -121,8 +129,8 @@ func TestAccContainerCluster_resourceManagerTags(t *testing.T) { randomSuffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", randomSuffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) bootstrapGkeTagManagerServiceAgents(t) acctest.VcrTest(t, resource.TestCase{ @@ -179,8 +187,8 @@ func TestAccContainerCluster_networkingModeRoutes(t *testing.T) { t.Parallel() // separate shared network name because test requests a specific CIDR - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster-moderoutes") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster-moderoutes", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster-moderoutes") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster-moderoutes", networkName) firstClusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) secondClusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -214,8 +222,8 @@ func TestAccContainerCluster_misc(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -252,8 +260,8 @@ func TestAccContainerCluster_withAddons(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -283,11 +291,73 @@ func TestAccContainerCluster_withAddons(t *testing.T) { }) } +{{ if ne $.TargetVersionName `ga` -}} +func TestAccContainerCluster_agentSandbox(t *testing.T) { + t.Parallel() + + clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckContainerClusterDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccContainerCluster_agentSandbox(clusterName, networkName, subnetworkName, true), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_container_cluster.primary", "addons_config.0.agent_sandbox_config.0.enabled", "true"), + ), + }, + { + ResourceName: "google_container_cluster.primary", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + { + Config: testAccContainerCluster_agentSandbox(clusterName, networkName, subnetworkName, false), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_container_cluster.primary", "addons_config.0.agent_sandbox_config.0.enabled", "false"), + ), + }, + { + ResourceName: "google_container_cluster.primary", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + }, + }) +} + +func testAccContainerCluster_agentSandbox(clusterName, networkName, subnetworkName string, enabled bool) string { + return fmt.Sprintf(` +resource "google_container_cluster" "primary" { + name = "%s" + location = "us-central1-a" + initial_node_count = 1 + network = "%s" + subnetwork = "%s" + + addons_config { + agent_sandbox_config { + enabled = %t + } + } + + deletion_protection = false +} +`, clusterName, networkName, subnetworkName, enabled) +} +{{- end }} + func TestAccContainerCluster_withDeletionProtection(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -324,8 +394,8 @@ func TestAccContainerCluster_withNotificationConfig(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) topic := fmt.Sprintf("tf-test-topic-%s", acctest.RandString(t, 10)) newTopic := fmt.Sprintf("tf-test-topic-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -378,8 +448,8 @@ func TestAccContainerCluster_withFilteredNotificationConfig(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) topic := fmt.Sprintf("tf-test-topic-%s", acctest.RandString(t, 10)) newTopic := fmt.Sprintf("tf-test-topic-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -422,8 +492,8 @@ func TestAccContainerCluster_withConfidentialNodes(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -483,8 +553,8 @@ func TestAccContainerCluster_withLocalSsdEncryptionMode(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) npName := fmt.Sprintf("tf-test-node-pool-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -509,8 +579,8 @@ func TestAccContainerCluster_withMaxRunDuration(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) npName := fmt.Sprintf("tf-test-node-pool-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -553,8 +623,8 @@ func TestAccContainerCluster_withFlexStart(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) npName := fmt.Sprintf("tf-test-node-pool-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -586,8 +656,8 @@ func TestAccContainerCluster_withILBSubsetting(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -630,8 +700,8 @@ func TestAccContainerCluster_omittedILBSubsetting(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -674,8 +744,8 @@ func TestAccContainerCluster_disableL4LbFirewallReconciliation(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -740,8 +810,8 @@ func TestAccContainerCluster_inTransitEncryptionConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -783,8 +853,8 @@ func TestAccContainerCluster_networkPerformanceConfig(t *testing.T) { acctest.SkipIfVcr(t) clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -854,8 +924,8 @@ func TestAccContainerCluster_withAdditiveVPC(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -879,8 +949,8 @@ func TestAccContainerCluster_withMasterAuthConfig_NoCert(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -907,8 +977,8 @@ func TestAccContainerCluster_withAuthenticatorGroupsConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) orgDomain := envvar.GetTestOrgDomainFromEnv(t) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -1004,8 +1074,8 @@ func TestAccContainerCluster_withPodAutoscaling(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1201,8 +1271,8 @@ func TestAccContainerCluster_withNetworkPolicyEnabled(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1274,8 +1344,8 @@ func TestAccContainerCluster_withNetworkPolicyEnabled(t *testing.T) { func TestAccContainerCluster_withReleaseChannelEnabled(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1309,8 +1379,8 @@ func TestAccContainerCluster_withReleaseChannelEnabled(t *testing.T) { func TestAccContainerCluster_withReleaseChannelEnabledDefaultVersion(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1376,8 +1446,8 @@ func TestAccContainerCluster_withInvalidReleaseChannel(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1395,8 +1465,8 @@ func TestAccContainerCluster_withInvalidReleaseChannel(t *testing.T) { func TestAccContainerCluster_withAcceleratedGkeAutoUpgradeConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1421,8 +1491,8 @@ func TestAccContainerCluster_withAcceleratedGkeAutoUpgradeConfig(t *testing.T) { func TestAccContainerCluster_withTelemetryEnabled(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1469,8 +1539,8 @@ func TestAccContainerCluster_withManagedOpenTelemetryConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1563,8 +1633,8 @@ func TestAccContainerCluster_withManagedMLDiagnosticsConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1664,8 +1734,8 @@ func TestAccContainerCluster_withMasterAuthorizedNetworksConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1733,8 +1803,8 @@ func TestAccContainerCluster_withGcpPublicCidrsAccessEnabledToggle(t *testing.T) t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1827,8 +1897,8 @@ func TestAccContainerCluster_withAuthorizedNetworkPrivateEnforcementToggle(t *te t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1887,8 +1957,8 @@ func TestAccContainerCluster_regional(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-regional-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1913,8 +1983,8 @@ func TestAccContainerCluster_regionalWithNodePool(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-regional-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1938,8 +2008,8 @@ func TestAccContainerCluster_regionalWithNodeLocations(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2006,8 +2076,8 @@ func TestAccContainerCluster_nodePoolWithUpgradeSettings(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2125,8 +2195,8 @@ func TestAccContainerCluster_withPrivateClusterConfigGlobalAccessEnabledOnly(t * t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2159,8 +2229,8 @@ func TestAccContainerCluster_withIntraNodeVisibility(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2199,8 +2269,8 @@ func TestAccContainerCluster_withVersion(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2224,8 +2294,8 @@ func TestAccContainerCluster_updateVersion(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2258,8 +2328,8 @@ func TestAccContainerCluster_withNodeConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2302,8 +2372,8 @@ func TestAccContainerCluster_withNodeConfigLinuxNodeConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2452,8 +2522,8 @@ func TestAccContainerCluster_withKubeletConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2514,8 +2584,8 @@ func TestAccContainerCluster_withNodeConfigFastSocket(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2567,8 +2637,8 @@ func TestAccContainerCluster_withNodeConfigFastSocket(t *testing.T) { func TestAccContainerCluster_withNodeConfigGcfsConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2610,8 +2680,8 @@ func TestAccContainerCluster_withNodeConfigGcfsConfig(t *testing.T) { func TestAccContainerCluster_withNodeConfigKubeletConfigSettingsUpdates(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2668,8 +2738,8 @@ func TestAccContainerCluster_withNodeConfigKubeletConfigSettingsInNodePool(t *te t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2693,8 +2763,8 @@ func TestAccContainerCluster_withInsecureKubeletReadonlyPortEnabledInNodePool(t t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2720,8 +2790,8 @@ func TestAccContainerCluster_withInsecureKubeletReadonlyPortEnabledInNodePool(t func TestAccContainerCluster_withInsecureKubeletReadonlyPortEnabledDefaultsUpdates(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2793,8 +2863,8 @@ func TestAccContainerCluster_withInsecureKubeletReadonlyPortEnabledDefaultsUpdat func TestAccContainerCluster_withLoggingVariantInNodeConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2818,8 +2888,8 @@ func TestAccContainerCluster_withLoggingVariantInNodePool(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2842,8 +2912,8 @@ func TestAccContainerCluster_withLoggingVariantInNodePool(t *testing.T) { func TestAccContainerCluster_withLoggingVariantUpdates(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2885,8 +2955,8 @@ func TestAccContainerCluster_withAdvancedMachineFeaturesInNodePool(t *testing.T) t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2909,8 +2979,8 @@ func TestAccContainerCluster_withAdvancedMachineFeaturesInNodePool(t *testing.T) func TestAccContainerCluster_withNodePoolDefaults(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -2968,8 +3038,8 @@ func TestAccContainerCluster_withNodeConfigScopeAlias(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2993,8 +3063,8 @@ func TestAccContainerCluster_withNodeConfigShieldedInstanceConfig(t *testing.T) t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3018,8 +3088,8 @@ func TestAccContainerCluster_withNodeConfigReservationAffinity(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3050,8 +3120,8 @@ func TestAccContainerCluster_withNodeConfigReservationAffinitySpecific(t *testin reservationName := fmt.Sprintf("tf-test-reservation-%s", acctest.RandString(t, 10)) clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3087,8 +3157,8 @@ func TestAccContainerCluster_withWorkloadMetadataConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3140,8 +3210,8 @@ func TestAccContainerCluster_withSandboxConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3198,8 +3268,8 @@ func TestAccContainerCluster_withSandboxConfigType(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3223,11 +3293,11 @@ func TestAccContainerCluster_withBootDiskKmsKey(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -3240,7 +3310,7 @@ func TestAccContainerCluster_withBootDiskKmsKey(t *testing.T) { CheckDestroy: testAccCheckContainerClusterDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccContainerCluster_withBootDiskKmsKey(clusterName, kms.CryptoKey.Name, networkName, subnetworkName), + Config: testAccContainerCluster_withBootDiskKmsKey(clusterName, bootstrapped.CryptoKey.Name, networkName, subnetworkName), }, { ResourceName: "google_container_cluster.with_boot_disk_kms_key", @@ -3286,8 +3356,8 @@ func TestAccContainerCluster_backend(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3312,8 +3382,8 @@ func TestAccContainerCluster_withNodePoolBasic(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3338,8 +3408,8 @@ func TestAccContainerCluster_withNodePoolUpdateVersion(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3373,8 +3443,8 @@ func TestAccContainerCluster_withNodePoolResize(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3414,8 +3484,8 @@ func TestAccContainerCluster_withNodePoolAutoscaling(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3470,8 +3540,8 @@ func TestAccContainerCluster_withNodePoolCIA(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3535,8 +3605,8 @@ func TestAccContainerCluster_withNodePoolNamePrefix(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) npNamePrefix := "tf-test-np-" acctest.VcrTest(t, resource.TestCase{ @@ -3561,8 +3631,8 @@ func TestAccContainerCluster_withNodePoolMultiple(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) npNamePrefix := "tf-test-np-" acctest.VcrTest(t, resource.TestCase{ @@ -3588,8 +3658,8 @@ func TestAccContainerCluster_withNodePoolConflictingNameFields(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npPrefix := "tf-test-np" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3609,8 +3679,8 @@ func TestAccContainerCluster_withNodePoolNodeConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3635,8 +3705,8 @@ func TestAccContainerCluster_withNodePoolNodeDrainConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3665,8 +3735,8 @@ func TestAccContainerCluster_withClusterDisruptionBudget(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_cluster_disruption_budget" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3691,8 +3761,8 @@ func TestAccContainerCluster_withMaintenanceWindow(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_window" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3731,8 +3801,8 @@ func TestAccContainerCluster_withRecurringMaintenanceWindow(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_recurring_maintenance_window" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3780,8 +3850,8 @@ func TestAccContainerCluster_withMaintenanceExclusionWindow(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_window" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3816,8 +3886,8 @@ func TestAccContainerCluster_withMaintenanceExclusionOptions(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_options" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3849,8 +3919,8 @@ func TestAccContainerCluster_withMaintenanceExclusionOptions_untilEndOfSupport(t t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_options" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3880,8 +3950,8 @@ func TestAccContainerCluster_deleteMaintenanceExclusionOptions(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_options" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3930,8 +4000,8 @@ func TestAccContainerCluster_deleteMaintenanceExclusionOptions_untilEndOfSupport t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_options" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3978,8 +4048,8 @@ func TestAccContainerCluster_updateMaintenanceExclusionOptions(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_options" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) // step1: create a new cluster and initialize the maintenceExclusion without exclusion scopes, // step2: add exclusion scopes to the maintenancePolicy, @@ -4048,8 +4118,8 @@ func TestAccContainerCluster_updateMaintenanceExclusionOptions_untilEndOfSupport t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_options" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) // step1: create a new cluster and initialize the maintenceExclusion without exclusion scopes, // step2: add exclusion scopes to the maintenancePolicy, @@ -4114,8 +4184,8 @@ func TestAccContainerCluster_deleteExclusionWindow(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) resourceName := "google_container_cluster.with_maintenance_exclusion_window" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4325,8 +4395,8 @@ func TestAccContainerCluster_nodeAutoprovisioning(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4405,8 +4475,8 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaults(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) includeMinCpuPlatform := true acctest.VcrTest(t, resource.TestCase{ @@ -4458,8 +4528,8 @@ func TestAccContainerCluster_autoprovisioningDefaultsUpgradeSettings(t *testing. t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4496,8 +4566,8 @@ func TestAccContainerCluster_nodeAutoprovisioningNetworkTags(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4525,8 +4595,8 @@ func TestAccContainerCluster_withDefaultComputeClassEnabled(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4565,8 +4635,8 @@ func TestAccContainerCluster_withAutopilotDefaultComputeClassEnabled(t *testing. t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4653,8 +4723,8 @@ func TestAccContainerCluster_withAutopilotClusterPolicy(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4761,8 +4831,8 @@ func TestAccContainerCluster_withShieldedNodes(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4904,8 +4974,8 @@ func TestAccContainerCluster_withAutopilotKubeletConfig(t *testing.T) { randomSuffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", randomSuffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4954,8 +5024,8 @@ func TestAccContainerCluster_withAutopilot_withNodePoolAutoConfig(t *testing.T) randomSuffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", randomSuffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4980,8 +5050,8 @@ func TestAccContainerCluster_withStandard_withNodePoolDefaults(t *testing.T) { randomSuffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", randomSuffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5069,8 +5139,8 @@ func TestAccContainerCluster_withWorkloadIdentityConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -5114,8 +5184,8 @@ func TestAccContainerCluster_withWorkloadIdentityConfigAutopilot(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) pid := envvar.GetTestProjectFromEnv() - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5139,8 +5209,8 @@ func TestAccContainerCluster_withSecretManagerConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5195,14 +5265,13 @@ func TestAccContainerCluster_withSecretManagerConfig(t *testing.T) { }, }) } -{{ if ne $.TargetVersionName `ga` -}} func TestAccContainerCluster_withSecretSyncConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5266,14 +5335,13 @@ func TestAccContainerCluster_withSecretSyncConfig(t *testing.T) { }, }) } -{{- end }} func TestAccContainerCluster_withLoggingConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) minVersion := "1.32" acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5364,8 +5432,8 @@ func TestAccContainerCluster_withMonitoringConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -5485,8 +5553,8 @@ func TestAccContainerCluster_withSoleTenantGroup(t *testing.T) { t.Parallel() resourceName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -5508,8 +5576,8 @@ func TestAccContainerCluster_withSoleTenantGroup(t *testing.T) { func TestAccContainerCluster_withAutoscalingProfile(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("cluster-test-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5545,8 +5613,8 @@ func TestAccContainerCluster_withInvalidAutoscalingProfile(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() clusterName := fmt.Sprintf("cluster-test-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5600,8 +5668,8 @@ func TestAccContainerCluster_withBinaryAuthorizationEnabledBool(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5634,8 +5702,8 @@ func TestAccContainerCluster_withBinaryAuthorizationEvaluationModeAutopilot(t *t t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5668,8 +5736,8 @@ func TestAccContainerCluster_withBinaryAuthorizationEvaluationModeClassic(t *tes t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5727,8 +5795,8 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaultsDiskSizeGb(t *testing.T t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) includeDiskSizeGb := true acctest.VcrTest(t, resource.TestCase{ @@ -5762,8 +5830,8 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaultsDiskType(t *testing.T) t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) includeDiskType := true acctest.VcrTest(t, resource.TestCase{ @@ -5797,8 +5865,8 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaultsImageType(t *testing.T) t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) includeImageType := true acctest.VcrTest(t, resource.TestCase{ @@ -5832,11 +5900,11 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaultsBootDiskKmsKey(t *testi t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -5849,7 +5917,7 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaultsBootDiskKmsKey(t *testi CheckDestroy: testAccCheckContainerClusterDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccContainerCluster_autoprovisioningDefaultsBootDiskKmsKey(clusterName, kms.CryptoKey.Name, networkName, subnetworkName), + Config: testAccContainerCluster_autoprovisioningDefaultsBootDiskKmsKey(clusterName, bootstrapped.CryptoKey.Name, networkName, subnetworkName), }, { ResourceName: "google_container_cluster.nap_boot_disk_kms_key", @@ -5869,8 +5937,8 @@ func TestAccContainerCluster_nodeAutoprovisioningDefaultsShieldedInstance(t *tes t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5894,8 +5962,8 @@ func TestAccContainerCluster_autoprovisioningDefaultsManagement(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5928,8 +5996,8 @@ func TestAccContainerCluster_autoprovisioningLocations(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6074,8 +6142,8 @@ func TestAccContainerCluster_withExternalIpsConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -6109,8 +6177,8 @@ func TestAccContainerCluster_withMeshCertificatesConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -6153,8 +6221,8 @@ func TestAccContainerCluster_withCostManagementConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -6188,15 +6256,15 @@ func TestAccContainerCluster_withDatabaseEncryption(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) // Use the bootstrapped KMS key so we can avoid creating keys needlessly // as they will pile up in the project because they can not be completely // deleted. Also, we need to create the key in the same location as the // cluster as GKE does not support the "global" location for KMS keys. // See https://cloud.google.com/kubernetes-engine/docs/how-to/encrypting-secrets#creating_a_key - kmsData := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + kmsData := kms.BootstrapKMSKeyInLocation(t, "us-central1") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6230,8 +6298,8 @@ func TestAccContainerCluster_withAdvancedDatapath(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6255,8 +6323,8 @@ func TestAccContainerCluster_enableCiliumPolicies(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6350,8 +6418,8 @@ func TestAccContainerCluster_withResourceUsageExportConfig(t *testing.T) { suffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", suffix) datesetId := fmt.Sprintf("tf_test_cluster_resource_usage_%s", suffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6421,8 +6489,8 @@ func TestAccContainerCluster_withEnableKubernetesAlpha(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6446,8 +6514,8 @@ func TestAccContainerCluster_withEnableKubernetesBetaAPIs(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6471,8 +6539,8 @@ func TestAccContainerCluster_withEnableKubernetesBetaAPIsOnExistingCluster(t *te t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6505,8 +6573,8 @@ func TestAccContainerCluster_withIncompatibleMasterVersionNodeVersion(t *testing t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func(){acctest.AccTestPreCheck(t)}, @@ -6527,8 +6595,8 @@ func TestAccContainerCluster_withDNSConfig(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) domainName := fmt.Sprintf("tf-test-domain-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -6559,8 +6627,8 @@ func TestAccContainerCluster_withDNSConfig(t *testing.T) { func TestAccContainerCluster_withGatewayApiConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -6625,8 +6693,8 @@ func TestAccContainerCluster_withProtectConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6660,8 +6728,8 @@ func TestAccContainerCluster_withSecurityPostureConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6721,8 +6789,8 @@ func TestAccContainerCluster_withFleetConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) projectID := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -6818,8 +6886,8 @@ func TestAccContainerCluster_withWorkloadALTSConfigAutopilot(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7024,19 +7092,19 @@ func TestAccContainerCluster_WithCPAFeatures(t *testing.T) { suffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", suffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) // Bootstrap KMS keys and needed IAM role. - diskKey := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "control-plane-disk-encryption") - signingKey := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "us-central1", "rs256-service-account-signing") - backupKey := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "etcd-backups") + diskKey := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "control-plane-disk-encryption") + signingKey := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "us-central1", "rs256-service-account-signing") + backupKey := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "etcd-backups") // Here, we are granting the container engine service agent permissions on // *ALL* Cloud KMS keys in the project. A more realistic usage would be to // grant the service agent the necessary roles only on the individual keys // we have created. - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@container-engine-robot.iam.gserviceaccount.com", Role: "roles/container.cloudKmsKeyUser", @@ -7340,8 +7408,8 @@ func TestAccContainerCluster_kubeDns_minimal(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -7364,8 +7432,8 @@ func TestAccContainerCluster_autopilot_minimal(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -7388,8 +7456,8 @@ func TestAccContainerCluster_autopilot_withDNSConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7441,8 +7509,8 @@ func TestAccContainerCluster_autopilot_withAdditiveVPC(t *testing.T) { domain := "additive.autopilot.example" clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7505,8 +7573,8 @@ func TestAccContainerCluster_cloudDns_nil_scope(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7546,8 +7614,8 @@ func TestAccContainerCluster_autopilot_withAdditiveVPCMutation(t *testing.T) { domain := "additive-mutating.autopilot.example" clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7600,8 +7668,8 @@ func TestAccContainerCluster_autopilot_net_admin(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7643,8 +7711,8 @@ func TestAccContainerCluster_autopilot_privileged_admission(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7809,8 +7877,8 @@ func TestAccContainerCluster_withCpuCfsQuotaPool(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -7844,8 +7912,8 @@ func TestAccContainerCluster_network_tier_config(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -8201,6 +8269,9 @@ resource "google_container_cluster" "primary" { lustre_csi_driver_config { enabled = false } + pod_snapshot_config { + enabled = false + } {{- if ne $.TargetVersionName "ga" }} istio_config { disabled = true @@ -8209,9 +8280,6 @@ resource "google_container_cluster" "primary" { kalm_config { enabled = false } - pod_snapshot_config { - enabled = false - } {{- end }} } network = "%s" @@ -8290,6 +8358,9 @@ resource "google_container_cluster" "primary" { enable_legacy_lustre_port=true disable_multi_nic=false } + pod_snapshot_config { + enabled = true + } {{- if ne $.TargetVersionName "ga" }} istio_config { disabled = false @@ -8298,9 +8369,6 @@ resource "google_container_cluster" "primary" { kalm_config { enabled = true } - pod_snapshot_config { - enabled = true - } {{- end }} } network = "%s" @@ -9224,8 +9292,8 @@ func TestAccContainerCluster_withEnablePrivateEndpointToggle(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -12674,7 +12742,7 @@ resource "google_container_cluster" "with_cost_management_config" { `, projectID, clusterName, enabled, networkName, subnetworkName) } -func testAccContainerCluster_withDatabaseEncryption(clusterName string, kmsData acctest.BootstrappedKMS, networkName, subnetworkName string) string { +func testAccContainerCluster_withDatabaseEncryption(clusterName string, kmsData kms.BootstrappedKMS, networkName, subnetworkName string) string { return fmt.Sprintf(` data "google_project" "project" { } @@ -13252,7 +13320,6 @@ resource "google_container_cluster" "primary" { } `, projectID, name, networkName, subnetworkName) } -{{ if ne $.TargetVersionName `ga` -}} func testAccContainerCluster_forSecretSyncConfig(projectID, name, networkName, subnetworkName string) string { return fmt.Sprintf(` @@ -13375,7 +13442,6 @@ resource "google_container_cluster" "primary" { } `, projectID, name, networkName, subnetworkName) } -{{- end }} func testAccContainerCluster_withLoggingConfigEnabled(name, networkName, subnetworkName string, minVersion string) string { return fmt.Sprintf(` @@ -13933,8 +13999,8 @@ func TestAccContainerCluster_customPlacementPolicy(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) policy := fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) @@ -14082,11 +14148,11 @@ func TestAccContainerCluster_withConfidentialBootDisk(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-node-pool-%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -14099,7 +14165,7 @@ func TestAccContainerCluster_withConfidentialBootDisk(t *testing.T) { CheckDestroy: testAccCheckContainerClusterDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccContainerCluster_withConfidentialBootDisk(clusterName, npName, kms.CryptoKey.Name, networkName, subnetworkName), + Config: testAccContainerCluster_withConfidentialBootDisk(clusterName, npName, bootstrapped.CryptoKey.Name, networkName, subnetworkName), }, { ResourceName: "google_container_cluster.with_confidential_boot_disk", @@ -14148,11 +14214,11 @@ func TestAccContainerCluster_withConfidentialBootDiskNodeConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -14165,7 +14231,7 @@ func TestAccContainerCluster_withConfidentialBootDiskNodeConfig(t *testing.T) { CheckDestroy: testAccCheckContainerClusterDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccContainerCluster_withConfidentialBootDiskNodeConfig(clusterName, kms.CryptoKey.Name, networkName, subnetworkName), + Config: testAccContainerCluster_withConfidentialBootDiskNodeConfig(clusterName, bootstrapped.CryptoKey.Name, networkName, subnetworkName), }, { ResourceName: "google_container_cluster.with_confidential_boot_disk_node_config", @@ -14212,8 +14278,8 @@ func TestAccContainerCluster_withoutConfidentialBootDisk(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) npName := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -14813,8 +14879,8 @@ func TestAccContainerCluster_privateRegistry(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) secretID := fmt.Sprintf("tf-test-secret-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -15140,8 +15206,8 @@ func TestAccContainerCluster_registryHosts(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) secretID := fmt.Sprintf("tf-test-secret-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -15460,8 +15526,8 @@ func TestAccContainerCluster_writableCgroups(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePoolName := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -15664,8 +15730,8 @@ func TestAccContainerCluster_withProviderDefaultLabels(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -15827,11 +15893,11 @@ func TestAccContainerCluster_storagePoolsWithNodePool(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) location := envvar.GetTestZoneFromEnv() - storagePoolResourceName := acctest.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") + storagePoolResourceName := tpgcompute.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -15883,11 +15949,11 @@ func TestAccContainerCluster_storagePoolsWithNodeConfig(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) location := envvar.GetTestZoneFromEnv() - storagePoolResourceName := acctest.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") + storagePoolResourceName := tpgcompute.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -15970,8 +16036,8 @@ func TestAccContainerCluster_withAutopilotGcpFilestoreCsiDriver(t *testing.T) { randomSuffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", randomSuffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16044,8 +16110,8 @@ func TestAccContainerCluster_withDnsEndpoint(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16119,8 +16185,8 @@ func TestAccContainerCluster_withDnsEndpointAndEnableK8sTokensViaDns(t *testing. t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16177,8 +16243,8 @@ func TestAccContainerCluster_withDnsEndpointAndEnableK8sCertsViaDns(t *testing.T t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16235,8 +16301,8 @@ func TestAccContainerCluster_withCgroupMode(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16264,8 +16330,8 @@ func TestAccContainerCluster_withCgroupModeUpdate(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16319,8 +16385,8 @@ func TestAccContainerCluster_withEnterpriseConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) pid := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -16402,8 +16468,8 @@ func TestAccContainerCluster_disableControlPlaneIP(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16589,8 +16655,8 @@ func bootstrapAdditionalIpRangesNetworkConfig(t *testing.T, name string, additio sri := []subnetRangeInfo{} // We create our network to ensure no range collisions. - networkName := acctest.BootstrapSharedTestNetwork(t, fmt.Sprintf("%s-network", name)) - mainSubnet := acctest.BootstrapSubnetWithOverrides(t, fmt.Sprintf("%s-subnet-main", name), networkName, map[string]interface{}{ + networkName := tpgcompute.BootstrapSharedTestNetwork(t, fmt.Sprintf("%s-network", name)) + mainSubnet := tpgcompute.BootstrapSubnetWithOverrides(t, fmt.Sprintf("%s-subnet-main", name), networkName, map[string]interface{}{ "ipCidrRange": "10.2.0.0/24", "secondaryIpRanges": []map[string]interface{}{ { @@ -16631,7 +16697,7 @@ func bootstrapAdditionalIpRangesNetworkConfig(t *testing.T, name string, additio } subnetName := fmt.Sprintf("%s-subnet-add-%d", name, subnetIndex) - acctest.BootstrapSubnetWithOverrides(t, subnetName, networkName, subnetOverrides) + tpgcompute.BootstrapSubnetWithOverrides(t, subnetName, networkName, subnetOverrides) si := subnetRangeInfo{ SubnetName: subnetName, @@ -16755,8 +16821,8 @@ func TestAccContainerCluster_auto_ipam_config_enabled(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16827,8 +16893,8 @@ func TestAccContainerCluster_auto_ipam_config_none(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16867,8 +16933,8 @@ func TestAccContainerCluster_withAnonymousAuthenticationConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -16965,20 +17031,20 @@ func TestAccContainerCluster_WithCPAFeaturesUpdate(t *testing.T) { suffix := acctest.RandString(t, 10) clusterName := fmt.Sprintf("tf-test-cluster-%s", suffix) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) // Bootstrap KMS keys and needed IAM role. - diskKey := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "control-plane-disk-encryption") - signingKey1 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "us-central1", "rs256-service-account-signing-1") - signingKey2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "us-central1", "rs256-service-account-signing-2") - backupKey := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "etcd-backups") + diskKey := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "control-plane-disk-encryption") + signingKey1 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "us-central1", "rs256-service-account-signing-1") + signingKey2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "us-central1", "rs256-service-account-signing-2") + backupKey := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "etcd-backups") // Here, we are granting the container engine service agent permissions on // *ALL* Cloud KMS keys in the project. A more realistic usage would be to // grant the service agent the necessary roles only on the individual keys // we have created. - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@container-engine-robot.iam.gserviceaccount.com", Role: "roles/container.cloudKmsKeyUser", @@ -17098,8 +17164,8 @@ func TestAccContainerCluster_RbacBindingConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -17162,8 +17228,8 @@ func TestAccContainerCluster_withKubeletResourceManagerConfig(t *testing.T) { t.Parallel() clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -17695,8 +17761,8 @@ func TestAccContainerCluster_withClusterBootDisk(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/container/resource_container_node_pool.go.tmpl b/mmv1/third_party/terraform/services/container/resource_container_node_pool.go.tmpl index 2715948f80ce..7d99509454ea 100644 --- a/mmv1/third_party/terraform/services/container/resource_container_node_pool.go.tmpl +++ b/mmv1/third_party/terraform/services/container/resource_container_node_pool.go.tmpl @@ -201,6 +201,7 @@ func ResourceContainerNodePool() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, resourceNodeConfigEmptyGuestAccelerator, nodePoolAcceleratorNetworkProfileCustomizeDiff, @@ -235,6 +236,9 @@ func ResourceContainerNodePool() *schema.Resource { Type: schema.TypeString, Computed: true, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }), } } @@ -940,11 +944,21 @@ func resourceContainerNodePoolRead(d *schema.ResourceData, meta interface{}) err if err := d.Set("project", nodePoolInfo.project); err != nil { return fmt.Errorf("Error setting project: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceContainerNodePoolUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceContainerNodePool) { + return ResourceContainerNodePool().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -984,6 +998,13 @@ func resourceContainerNodePoolUpdate(d *schema.ResourceData, meta interface{}) e } func resourceContainerNodePoolDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/container/resource_container_node_pool_meta.yaml.tmpl b/mmv1/third_party/terraform/services/container/resource_container_node_pool_meta.yaml.tmpl index 064962f9616a..c6d8ab361704 100644 --- a/mmv1/third_party/terraform/services/container/resource_container_node_pool_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/container/resource_container_node_pool_meta.yaml.tmpl @@ -250,6 +250,8 @@ fields: api_field: 'config.loggingConfig.variantConfig.variant' - field: 'node_config.machine_type' api_field: 'config.machineType' + - field: 'node_config.gpudirect_strategy' + api_field: 'config.gpuDirectConfig.gpuDirectStrategy' - field: 'node_config.max_run_duration' api_field: 'config.maxRunDuration' - field: 'node_config.metadata' @@ -334,3 +336,5 @@ fields: - api_field: 'upgradeSettings.maxUnavailable' - api_field: 'upgradeSettings.strategy' - api_field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/container/resource_container_node_pool_test.go.tmpl b/mmv1/third_party/terraform/services/container/resource_container_node_pool_test.go.tmpl index c8db9e56fd8e..17575e29730b 100644 --- a/mmv1/third_party/terraform/services/container/resource_container_node_pool_test.go.tmpl +++ b/mmv1/third_party/terraform/services/container/resource_container_node_pool_test.go.tmpl @@ -9,8 +9,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/container" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) @@ -19,8 +23,8 @@ func TestAccContainerNodePool_basic(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -43,7 +47,7 @@ func TestAccContainerNodePool_resourceManagerTags(t *testing.T) { t.Parallel() pid := envvar.GetTestProjectFromEnv() - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") tagData := map[string]interface{}{ "purpose": "GCE_FIREWALL", "purpose_data": map[string]interface{}{ @@ -57,7 +61,7 @@ func TestAccContainerNodePool_resourceManagerTags(t *testing.T) { "pid": pid, "org": envvar.GetTestOrgFromEnv(t), "network": networkName, - "subnet": acctest.BootstrapSubnet(t, "gke-cluster", networkName), + "subnet": tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName), "tagKey1": tagKey1, "tagValue1": tags.BootstrapSharedTestProjectTagValue(t, "resourceManagerTags1", tagKey1), "tagKey2": tagKey2, @@ -117,8 +121,8 @@ func TestAccContainerNodePool_basicWithClusterId(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -192,8 +196,8 @@ func TestAccContainerNodePool_namePrefix(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -219,8 +223,8 @@ func TestAccContainerNodePool_noName(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -244,8 +248,8 @@ func TestAccContainerNodePool_withLoggingVariantUpdates(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -285,8 +289,8 @@ func TestAccContainerNodePool_withNodeConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -324,8 +328,8 @@ func TestAccContainerNodePool_withNodeConfigWithBootDiskConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -357,8 +361,8 @@ func TestAccContainerNodePool_withNodeConfigWithBootDiskConfigChangeType(t *test cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -390,8 +394,8 @@ func TestAccContainerNodePool_withNodeConfigWithBootDiskConfigChangeTypeLegacy(t cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -424,8 +428,8 @@ func TestAccContainerNodePool_withLegacyNodeConfigAndBootDiskUpdate(t *testing.T cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -633,8 +637,8 @@ func TestAccContainerNodePool_withTaintsUpdate(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -669,8 +673,8 @@ func TestAccContainerNodePool_withMachineAndDiskUpdate(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -705,8 +709,8 @@ func TestAccContainerNodePool_withReservationAffinity(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -737,8 +741,8 @@ func TestAccContainerNodePool_withReservationAffinitySpecific(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) reservation := fmt.Sprintf("tf-test-reservation-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -775,8 +779,8 @@ func TestAccContainerNodePool_withWorkloadIdentityConfig(t *testing.T) { pid := envvar.GetTestProjectFromEnv() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -817,8 +821,8 @@ func TestAccContainerNodePool_withSandboxConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -847,8 +851,8 @@ func TestAccContainerNodePool_withSandboxConfigType(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -872,8 +876,8 @@ func TestAccContainerNodePool_withKubeletConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -960,8 +964,8 @@ func TestAccContainerNodePool_withInvalidKubeletCpuManagerPolicy(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -981,8 +985,8 @@ func TestAccContainerNodePool_withLinuxNodeConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1024,8 +1028,8 @@ func TestAccContainerNodePool_withSwapConfig_bootDisk(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1078,8 +1082,8 @@ func TestAccContainerNodePool_withSwapConfig_ephemeralLocalSsd(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1107,8 +1111,8 @@ func TestAccContainerNodePool_withSwapConfig_dedicatedLocalSsd(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1173,8 +1177,8 @@ func TestAccContainerNodePool_withCgroupMode(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1207,8 +1211,8 @@ func TestAccContainerNodePool_withHugepageConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1241,8 +1245,8 @@ func TestAccContainerNodePool_withNodeKernelModuleLoading(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1417,10 +1421,10 @@ func TestAccContainerNodePool_withBootDiskKmsKey(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -1450,8 +1454,8 @@ func TestAccContainerNodePool_withUpgradeSettings(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1525,8 +1529,8 @@ func TestAccContainerNodePool_withGPU(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1545,13 +1549,38 @@ func TestAccContainerNodePool_withGPU(t *testing.T) { }) } +func TestAccContainerNodePool_withRDMA(t *testing.T) { + t.Parallel() + + cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) + np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckContainerNodePoolDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccContainerNodePool_withRDMA(cluster, np, networkName, subnetworkName), + }, + { + ResourceName: "google_container_node_pool.np_with_gpudirect", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccContainerNodePool_withManagement(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) management := ` management { @@ -1605,8 +1634,8 @@ func TestAccContainerNodePool_withNodeDrainConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1633,8 +1662,8 @@ func TestAccContainerNodePool_withAccurateTimeConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1672,8 +1701,8 @@ func TestAccContainerNodePool_withNodeConfigScopeAlias(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1698,8 +1727,8 @@ func TestAccContainerNodePool_regionalAutoscaling(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1755,8 +1784,8 @@ func TestAccContainerNodePool_totalSize(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1813,8 +1842,8 @@ func TestAccContainerNodePool_autoscaling(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1869,8 +1898,8 @@ func TestAccContainerNodePool_resize(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1908,8 +1937,8 @@ func TestAccContainerNodePool_version(t *testing.T) { t.Parallel() cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1949,8 +1978,8 @@ func TestAccContainerNodePool_regionalClusters(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1974,8 +2003,8 @@ func TestAccContainerNodePool_EmptyGuestAccelerator(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2021,8 +2050,8 @@ func TestAccContainerNodePool_shieldedInstanceConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2048,8 +2077,8 @@ func TestAccContainerNodePool_concurrent(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np1 := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) np2 := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2101,8 +2130,8 @@ func TestAccContainerNodePool_withSoleTenantConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) minNodeCpus := 1 acctest.VcrTest(t, resource.TestCase{ @@ -2130,8 +2159,8 @@ func TestAccContainerNodePool_ephemeralStorageConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2183,8 +2212,8 @@ func TestAccContainerNodePool_ephemeralStorageLocalSsdConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2242,8 +2271,8 @@ func TestAccContainerNodePool_ephemeralStorageLocalSsdConfigWithDataCacheCount(t cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2301,8 +2330,8 @@ func TestAccContainerNodePool_ephemeralStorageLocalSsdConfigOnlyDataCacheCount(t cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2360,8 +2389,8 @@ func TestAccContainerNodePool_localNvmeSsdBlockConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2423,8 +2452,8 @@ func TestAccContainerNodePool_secondaryBootDisks(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2503,8 +2532,8 @@ func TestAccContainerNodePool_gcfsConfig(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2564,8 +2593,8 @@ func TestAccContainerNodePool_gvnic(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2633,8 +2662,8 @@ func TestAccContainerNodePool_fastSocket(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2709,8 +2738,8 @@ func TestAccContainerNodePool_compactPlacement(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2763,8 +2792,8 @@ func TestAccContainerNodePool_customPlacementPolicy(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) policy := fmt.Sprintf("tf-test-policy-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2830,8 +2859,8 @@ func TestAccContainerNodePool_enableQueuedProvisioning(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2901,8 +2930,8 @@ func TestAccContainerNodePool_threadsPerCore(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2961,8 +2990,8 @@ func TestAccContainerNodePool_nestedVirtualization(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3023,8 +3052,8 @@ func TestAccContainerNodePool_performanceMonitoringUnit(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -4652,6 +4681,51 @@ resource "google_container_node_pool" "with_upgrade_settings" { `, clusterName, networkName, subnetworkName, nodePoolName, upgradeSettings) } +func testAccContainerNodePool_withRDMA(cluster, np, networkName, subnetworkName string) string { + return fmt.Sprintf(` +data "google_container_engine_versions" "central1b" { + location = "us-central1-b" +} + +resource "google_container_cluster" "cluster" { + name = "%s" + location = "us-central1-b" + min_master_version = data.google_container_engine_versions.central1b.latest_master_version + deletion_protection = false + network = "%s" + subnetwork = "%s" + enable_multi_networking = true + datapath_provider = "ADVANCED_DATAPATH" + + initial_node_count = 1 + remove_default_node_pool = true +} + +resource "google_container_node_pool" "np_with_gpudirect" { + name = "%s" + location = "us-central1-b" + cluster = google_container_cluster.cluster.name + network_config { accelerator_network_profile = "auto" } + + node_config { + machine_type = "a3-ultragpu-8g" + + guest_accelerator { + type = "nvidia-h200-141gb" + count = 8 + } + + gpudirect_strategy = "RDMA" + + ephemeral_storage_local_ssd_config { + local_ssd_count = 32 + data_cache_count = 0 + } + } +} +`, cluster, networkName, subnetworkName, np) +} + func testAccContainerNodePool_withGPU(cluster, np, networkName, subnetworkName string) string { return fmt.Sprintf(` data "google_container_engine_versions" "central1c" { @@ -5120,8 +5194,8 @@ func TestAccContainerNodePool_withConfidentialNodes(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5206,8 +5280,8 @@ func TestAccContainerNodePool_withLocalSsdEncryptionMode(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5265,8 +5339,8 @@ func TestAccContainerNodePool_withMaxRunDuration(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5360,8 +5434,8 @@ func TestAccContainerNodePool_withFlexStart(t *testing.T) { clusterName := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-cluster-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5443,8 +5517,8 @@ func TestAccContainerNodePool_tpuTopology(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np1 := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) np2 := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5515,8 +5589,8 @@ func TestAccContainerNodePool_withHostMaintenancePolicy(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5573,11 +5647,11 @@ func TestAccContainerNodePool_withConfidentialBootDisk(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -5590,7 +5664,7 @@ func TestAccContainerNodePool_withConfidentialBootDisk(t *testing.T) { CheckDestroy: testAccCheckContainerClusterDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccContainerNodePool_withConfidentialBootDisk(cluster, np, kms.CryptoKey.Name, networkName, subnetworkName), + Config: testAccContainerNodePool_withConfidentialBootDisk(cluster, np, bootstrapped.CryptoKey.Name, networkName, subnetworkName), }, { ResourceName: "google_container_node_pool.with_confidential_boot_disk", @@ -5645,8 +5719,8 @@ func TestAccContainerNodePool_withoutConfidentialBootDisk(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-np-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -5841,8 +5915,8 @@ func TestAccContainerNodePool_privateRegistry(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodepool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) secretID := fmt.Sprintf("tf-test-secret-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6033,11 +6107,14 @@ resource "google_container_node_pool" "np" { func TestAccContainerNodePool_writableCgroups(t *testing.T) { t.Parallel() + // TODO(chrishenzie): Convert this to a negative test (expecting failure) + // once the API behavior change is fully rolled out. + t.Skip("Skipping due to API behavior change blocking writable cgroups modifications on node pools") cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodepool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6149,8 +6226,8 @@ func TestAccContainerNodePool_registryHosts(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodepool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) secretID := fmt.Sprintf("tf-test-secret-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6285,8 +6362,8 @@ func TestAccContainerNodePool_defaultDriverInstallation(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6353,11 +6430,11 @@ func TestAccContainerNodePool_storagePools(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) np := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) location := envvar.GetTestZoneFromEnv() - storagePoolResourceName := acctest.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") + storagePoolResourceName := tpgcompute.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -6413,11 +6490,11 @@ func TestAccContainerNodePool_withMachineDiskStoragePoolsUpdate(t *testing.T) { cluster := fmt.Sprintf("tf-test-cluster-%s", acctest.RandString(t, 10)) nodePool := fmt.Sprintf("tf-test-nodepool-%s", acctest.RandString(t, 10)) - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) location := envvar.GetTestZoneFromEnv() - storagePoolResourceName := acctest.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") + storagePoolResourceName := tpgcompute.BootstrapComputeStoragePool(t, "basic-1", "hyperdisk-balanced") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_note_test.go.tmpl b/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_note_test.go.tmpl index 8d2294c6cf78..785d52be66b1 100644 --- a/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_note_test.go.tmpl +++ b/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_note_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/containeranalysis" ) func TestAccContainerAnalysisNote_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_occurrence_test.go b/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_occurrence_test.go index 35cf574935c8..d4232045470c 100644 --- a/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_occurrence_test.go +++ b/mmv1/third_party/terraform/services/containeranalysis/resource_container_analysis_occurrence_test.go @@ -7,6 +7,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/binaryauthorization" + _ "github.com/hashicorp/terraform-provider-google/google/services/containeranalysis" "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -35,7 +37,7 @@ func getTestOccurrenceAttestationPayload(t *testing.T) string { func getSignedTestOccurrenceAttestationPayload( t *testing.T, config *transport_tpg.Config, - signingKey acctest.BootstrappedKMS, rawPayload string) string { + signingKey kms.BootstrappedKMS, rawPayload string) string { pbytes := []byte(rawPayload) ssum := sha512.Sum512(pbytes) hashed := base64.StdEncoding.EncodeToString(ssum[:]) @@ -63,7 +65,7 @@ func TestAccContainerAnalysisOccurrence_basic(t *testing.T) { return } - signKey := acctest.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") + signKey := kms.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") payload := getTestOccurrenceAttestationPayload(t) signed := getSignedTestOccurrenceAttestationPayload(t, config, signKey, payload) params := map[string]interface{}{ @@ -102,10 +104,10 @@ func TestAccContainerAnalysisOccurrence_multipleSignatures(t *testing.T) { } payload := getTestOccurrenceAttestationPayload(t) - key1 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "global", "tf-bootstrap-binauthz-key1") + key1 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "global", "tf-bootstrap-binauthz-key1") signature1 := getSignedTestOccurrenceAttestationPayload(t, config, key1, payload) - key2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "global", "tf-bootstrap-binauthz-key2") + key2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ASYMMETRIC_SIGN", "global", "tf-bootstrap-binauthz-key2") signature2 := getSignedTestOccurrenceAttestationPayload(t, config, key2, payload) paramsMultipleSignatures := map[string]interface{}{ diff --git a/mmv1/third_party/terraform/services/containeranalysis/resource_container_registry_test.go b/mmv1/third_party/terraform/services/containeranalysis/resource_container_registry_test.go index 3f40ae33d9d9..d93ec1ae12af 100644 --- a/mmv1/third_party/terraform/services/containeranalysis/resource_container_registry_test.go +++ b/mmv1/third_party/terraform/services/containeranalysis/resource_container_registry_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccContainerRegistry_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_install_manifest.go b/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_install_manifest.go index 4c32364544b6..5f77b1413bea 100644 --- a/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_install_manifest.go +++ b/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_install_manifest.go @@ -61,7 +61,7 @@ func dataSourceGoogleContainerAttachedInstallManifestRead(d *schema.ResourceData return fmt.Errorf("Cannot determine location: set location in this data source or at provider-level") } - url, err := tpgresource.ReplaceVars(d, config, "{{ContainerAttachedBasePath}}projects/{{project}}/locations/{{location}}:generateAttachedClusterInstallManifest") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}:generateAttachedClusterInstallManifest") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_versions.go b/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_versions.go index 0f85eb2a46ec..6f6280fd2230 100644 --- a/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_versions.go +++ b/mmv1/third_party/terraform/services/containerattached/data_source_google_container_attached_versions.go @@ -51,7 +51,7 @@ func dataSourceGoogleContainerAttachedVersionsRead(d *schema.ResourceData, meta return fmt.Errorf("Cannot determine location: set location in this data source or at provider-level") } - url, err := tpgresource.ReplaceVars(d, config, "{{ContainerAttachedBasePath}}projects/{{project}}/locations/{{location}}/attachedServerConfig") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/attachedServerConfig") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/containerattached/resource_container_attached_cluster_update_test.go b/mmv1/third_party/terraform/services/containerattached/resource_container_attached_cluster_update_test.go index e4de49f585d9..ee9e7fc8153a 100644 --- a/mmv1/third_party/terraform/services/containerattached/resource_container_attached_cluster_update_test.go +++ b/mmv1/third_party/terraform/services/containerattached/resource_container_attached_cluster_update_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/containerattached" ) func TestAccContainerAttachedCluster_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/containeraws/data_source_google_container_aws_versions.go b/mmv1/third_party/terraform/services/containeraws/data_source_google_container_aws_versions.go index 1fa32185f238..dd816b2f1cdf 100644 --- a/mmv1/third_party/terraform/services/containeraws/data_source_google_container_aws_versions.go +++ b/mmv1/third_party/terraform/services/containeraws/data_source_google_container_aws_versions.go @@ -56,7 +56,7 @@ func dataSourceGoogleContainerAwsVersionsRead(d *schema.ResourceData, meta inter return fmt.Errorf("Cannot determine location: set location in this data source or at provider-level") } - url, err := tpgresource.ReplaceVars(d, config, "{{ContainerAwsBasePath}}projects/{{project}}/locations/{{location}}/awsServerConfig") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/awsServerConfig") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster.go.tmpl b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster.go.tmpl index b1206dee38fd..52b4109a9c98 100644 --- a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster.go.tmpl +++ b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster.go.tmpl @@ -33,6 +33,7 @@ func ResourceContainerAwsCluster() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -186,6 +187,9 @@ func ResourceContainerAwsCluster() *schema.Resource { Description: "Output only. Workload Identity settings.", Elem: ContainerAwsClusterWorkloadIdentityConfigSchema(), }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -828,10 +832,20 @@ func resourceContainerAwsClusterRead(d *schema.ResourceData, meta interface{}) e if err = d.Set("workload_identity_config", flattenContainerAwsClusterWorkloadIdentityConfig(res.WorkloadIdentityConfig)); err != nil { return fmt.Errorf("error setting workload_identity_config in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceContainerAwsClusterUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceContainerAwsCluster) { + return ResourceContainerAwsCluster().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -888,6 +902,13 @@ func resourceContainerAwsClusterUpdate(d *schema.ResourceData, meta interface{}) } func resourceContainerAwsClusterDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster_meta.yaml.tmpl b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster_meta.yaml.tmpl index f25424849a69..9e4b6e9019c4 100644 --- a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_cluster_meta.yaml.tmpl @@ -60,3 +60,5 @@ fields: - api_field: 'workloadIdentityConfig.identityProvider' - api_field: 'workloadIdentityConfig.issuerUri' - api_field: 'workloadIdentityConfig.workloadPool' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool.go.tmpl b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool.go.tmpl index d8410aea4021..f5818ad0e6b5 100644 --- a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool.go.tmpl +++ b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool.go.tmpl @@ -36,6 +36,7 @@ func ResourceContainerAwsNodePool() *schema.Resource { dcl.ResourceContainerAwsNodePoolCustomizeDiffFunc, {{- end }} tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -184,6 +185,10 @@ func ResourceContainerAwsNodePool() *schema.Resource { Computed: true, Description: "Output only. The time at which this node pool was last updated.", }, + + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -751,10 +756,20 @@ func resourceContainerAwsNodePoolRead(d *schema.ResourceData, meta interface{}) if err = d.Set("update_time", res.UpdateTime); err != nil { return fmt.Errorf("error setting update_time in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceContainerAwsNodePoolUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceContainerAwsNodePool) { + return ResourceContainerAwsNodePool().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -810,6 +825,13 @@ func resourceContainerAwsNodePoolUpdate(d *schema.ResourceData, meta interface{} } func resourceContainerAwsNodePoolDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool_meta.yaml.tmpl b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool_meta.yaml.tmpl index 17c7c8cf1cbf..e090ad4c4bf1 100644 --- a/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/containeraws/resource_container_aws_node_pool_meta.yaml.tmpl @@ -57,3 +57,5 @@ fields: - api_field: 'updateSettings.surgeSettings.maxUnavailable' - api_field: 'updateTime' - api_field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/containerazure/data_source_google_container_azure_versions.go b/mmv1/third_party/terraform/services/containerazure/data_source_google_container_azure_versions.go index a2b27a3bb702..ca9fa4ec0da0 100644 --- a/mmv1/third_party/terraform/services/containerazure/data_source_google_container_azure_versions.go +++ b/mmv1/third_party/terraform/services/containerazure/data_source_google_container_azure_versions.go @@ -56,7 +56,7 @@ func dataSourceGoogleContainerAzureVersionsRead(d *schema.ResourceData, meta int return fmt.Errorf("Cannot determine location: set location in this data source or at provider-level") } - url, err := tpgresource.ReplaceVars(d, config, "{{ContainerAzureBasePath}}projects/{{project}}/locations/{{location}}/azureServerConfig") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/azureServerConfig") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client.go b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client.go index 1075ed9c0dca..2889aa754114 100644 --- a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client.go +++ b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client.go @@ -21,6 +21,7 @@ func ResourceContainerAzureClient() *schema.Resource { return &schema.Resource{ Create: resourceContainerAzureClientCreate, Read: resourceContainerAzureClientRead, + Update: resourceContainerAzureClientUpdate, Delete: resourceContainerAzureClientDelete, Importer: &schema.ResourceImporter{ @@ -33,6 +34,7 @@ func ResourceContainerAzureClient() *schema.Resource { }, CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -90,6 +92,9 @@ func ResourceContainerAzureClient() *schema.Resource { Computed: true, Description: "Output only. A globally unique identifier for the client.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -208,10 +213,29 @@ func resourceContainerAzureClientRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error setting uid in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceContainerAzureClientUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceContainerAzureClientRead(d, meta) +} + +//UDP update end + func resourceContainerAzureClientDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client_meta.yaml b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client_meta.yaml index 733b8c81196f..25fd9e89cf2e 100644 --- a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client_meta.yaml +++ b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_client_meta.yaml @@ -12,3 +12,5 @@ fields: - field: 'project' - api_field: 'tenantId' - api_field: 'uid' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster.go.tmpl b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster.go.tmpl index f21a48531609..c108e8009589 100644 --- a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster.go.tmpl +++ b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster.go.tmpl @@ -33,6 +33,7 @@ func ResourceContainerAzureCluster() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -204,6 +205,9 @@ func ResourceContainerAzureCluster() *schema.Resource { Description: "Output only. Workload Identity settings.", Elem: ContainerAzureClusterWorkloadIdentityConfigSchema(), }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -739,10 +743,20 @@ func resourceContainerAzureClusterRead(d *schema.ResourceData, meta interface{}) if err = d.Set("workload_identity_config", flattenContainerAzureClusterWorkloadIdentityConfig(res.WorkloadIdentityConfig)); err != nil { return fmt.Errorf("error setting workload_identity_config in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceContainerAzureClusterUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceContainerAzureCluster) { + return ResourceContainerAzureCluster().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -801,6 +815,13 @@ func resourceContainerAzureClusterUpdate(d *schema.ResourceData, meta interface{ } func resourceContainerAzureClusterDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster_meta.yaml.tmpl b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster_meta.yaml.tmpl index 54598e64ffe5..9dbe855b6ece 100644 --- a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_cluster_meta.yaml.tmpl @@ -48,3 +48,5 @@ fields: - api_field: 'workloadIdentityConfig.identityProvider' - api_field: 'workloadIdentityConfig.issuerUri' - api_field: 'workloadIdentityConfig.workloadPool' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool.go.tmpl b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool.go.tmpl index e4e8a904ee08..da7eafce4355 100644 --- a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool.go.tmpl +++ b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool.go.tmpl @@ -33,6 +33,7 @@ func ResourceContainerAzureNodePool() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, tpgresource.SetAnnotationsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -170,6 +171,9 @@ func ResourceContainerAzureNodePool() *schema.Resource { Computed: true, Description: "Output only. The time at which this node pool was last updated.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -491,10 +495,20 @@ func resourceContainerAzureNodePoolRead(d *schema.ResourceData, meta interface{} if err = d.Set("update_time", res.UpdateTime); err != nil { return fmt.Errorf("error setting update_time in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceContainerAzureNodePoolUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceContainerAzureNodePool) { + return ResourceContainerAzureNodePool().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -549,6 +563,13 @@ func resourceContainerAzureNodePoolUpdate(d *schema.ResourceData, meta interface } func resourceContainerAzureNodePoolDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool_meta.yaml.tmpl b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool_meta.yaml.tmpl index ef92715fe513..7a81177055ab 100644 --- a/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/containerazure/resource_container_azure_node_pool_meta.yaml.tmpl @@ -34,3 +34,5 @@ fields: - api_field: 'uid' - api_field: 'updateTime' - api_field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_connection_profile_test.go b/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_connection_profile_test.go index 771c0b8ca4b2..e4b60c5edb68 100644 --- a/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_connection_profile_test.go +++ b/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_connection_profile_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/databasemigrationservice" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) @@ -21,6 +23,9 @@ func TestAccDatabaseMigrationServiceConnectionProfile_update(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccDatabaseMigrationServiceConnectionProfile_basic(suffix), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_database_migration_service_connection_profile.default", "role", "SOURCE"), + ), }, { ResourceName: "google_database_migration_service_connection_profile.default", @@ -30,6 +35,9 @@ func TestAccDatabaseMigrationServiceConnectionProfile_update(t *testing.T) { }, { Config: testAccDatabaseMigrationServiceConnectionProfile_update(suffix), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_database_migration_service_connection_profile.default", "role", "DESTINATION"), + ), }, { ResourceName: "google_database_migration_service_connection_profile.default", @@ -47,6 +55,7 @@ resource "google_database_migration_service_connection_profile" "default" { location = "us-central1" connection_profile_id = "tf-test-dbms-connection-profile%{random_suffix}" display_name = "tf-test-dbms-connection-profile-display%{random_suffix}" + role = "SOURCE" labels = { foo = "bar" } @@ -66,6 +75,7 @@ resource "google_database_migration_service_connection_profile" "default" { location = "us-central1" connection_profile_id = "tf-test-dbms-connection-profile%{random_suffix}" display_name = "tf-test-dbms-connection-profile-updated-display%{random_suffix}" + role = "DESTINATION" labels = { bar = "foo" } @@ -84,7 +94,7 @@ func TestAccDatabaseMigrationServiceConnectionProfile_databaseMigrationServiceCo context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1"), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_migration_job_test.go b/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_migration_job_test.go index 5988896a2922..f71166f6e740 100644 --- a/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_migration_job_test.go +++ b/mmv1/third_party/terraform/services/databasemigrationservice/resource_database_migration_service_migration_job_test.go @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/databasemigrationservice" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDatabaseMigrationServiceMigrationJob_update(t *testing.T) { @@ -256,3 +260,177 @@ resource "google_database_migration_service_migration_job" "mysqltomysql" { } `, context) } + +func TestAccDatabaseMigrationServiceMigrationJob_postgresQuickstart(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + t.Logf("Running test with random suffix: %s", context["random_suffix"]) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckDatabaseMigrationServiceMigrationJobDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDatabaseMigrationServiceMigrationJob_postgresQuickstart(context), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_database_migration_service_migration_job.psql_to_psql", "type", "CONTINUOUS"), + resource.TestCheckResourceAttr("google_database_migration_service_migration_job.psql_to_psql", "postgres_homogeneous_config.0.is_native_logical", "true"), + ), + }, + { + ResourceName: "google_database_migration_service_migration_job.psql_to_psql", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "migration_job_id", "terraform_labels", "state"}, + }, + }, + }) +} + +func testAccDatabaseMigrationServiceMigrationJob_postgresQuickstart(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_compute_network" "default" { + name = "tf-test-network%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "default" { + name = "tf-test-subnet%{random_suffix}" + ip_cidr_range = "10.0.0.0/16" + region = "us-east1" + network = google_compute_network.default.id +} + +resource "google_compute_global_address" "private_ip_alloc" { + name = "tf-test-network-ip%{random_suffix}" + address_type = "INTERNAL" + purpose = "VPC_PEERING" + prefix_length = 16 + network = google_compute_network.default.id +} + +resource "google_service_networking_connection" "vpc_connection" { + network = google_compute_network.default.id + service = "servicenetworking.googleapis.com" + reserved_peering_ranges = [google_compute_global_address.private_ip_alloc.name] + deletion_policy = "ABANDON" +} + +resource "google_compute_network_attachment" "default" { + name = "tf-test-attachment%{random_suffix}" + region = "us-east1" + connection_preference = "ACCEPT_AUTOMATIC" + subnetworks = [google_compute_subnetwork.default.id] +} + +resource "google_database_migration_service_private_connection" "default" { + display_name = "tf-test-pc%{random_suffix}" + location = "us-east1" + private_connection_id = "tf-test-pc%{random_suffix}" + + psc_interface_config { + network_attachment = google_compute_network_attachment.default.id + } + + # Ensures the VPC peering for Cloud SQL exists before we try to use the network + # and is the last to be deleted. + depends_on = [google_service_networking_connection.vpc_connection] +} + +resource "google_sql_database_instance" "source" { + name = "tf-test-src-psql%{random_suffix}" + database_version = "POSTGRES_12" + region = "us-east1" + settings { + tier = "db-f1-micro" + ip_configuration { + ipv4_enabled = false + private_network = google_compute_network.default.id + } + } + deletion_protection = false + depends_on = [google_service_networking_connection.vpc_connection] +} + +resource "google_sql_user" "source_postgres" { + name = "postgres" + instance = google_sql_database_instance.source.name + password = "P@ssw0rd!" +} + +resource "google_database_migration_service_connection_profile" "source" { + location = "us-east1" + connection_profile_id = "tf-test-src-cp%{random_suffix}" + display_name = "Source Connection Profile" + role = "SOURCE" + postgresql { + host = google_sql_database_instance.source.private_ip_address + port = 5432 + username = "postgres" + password = "P@ssw0rd!" + database = "template1" + ssl { + type = "REQUIRED" + } + private_connectivity { + private_connection = google_database_migration_service_private_connection.default.id + } + } + depends_on = [google_sql_user.source_postgres] +} + +resource "google_sql_database_instance" "dest" { + name = "tf-test-dest-psql%{random_suffix}" + database_version = "POSTGRES_12" + region = "us-east1" + settings { + tier = "db-f1-micro" + } + deletion_protection = false +} + +resource "google_sql_user" "dest_postgres" { + name = "postgres" + instance = google_sql_database_instance.dest.name + password = "P@ssw0rd!" +} + +resource "google_database_migration_service_connection_profile" "dest" { + location = "us-east1" + connection_profile_id = "tf-test-dest-cp%{random_suffix}" + display_name = "Destination Connection Profile" + role = "DESTINATION" + postgresql { + username = "postgres" + password = "P@ssw0rd!" + cloud_sql_id = google_sql_database_instance.dest.name + } + depends_on = [google_sql_user.dest_postgres] +} + +resource "google_database_migration_service_migration_job" "psql_to_psql" { + location = "us-east1" + migration_job_id = "tf-test-mj-psql%{random_suffix}" + display_name = "Postgres Quickstart Migration Job" + + source = google_database_migration_service_connection_profile.source.name + destination = google_database_migration_service_connection_profile.dest.name + type = "CONTINUOUS" + + postgres_homogeneous_config { + is_native_logical = true + max_additional_subscriptions = 10 + } + + objects_config { + source_objects_config { + objects_selection_type = "ALL_OBJECTS" + } + } +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_template_test.go b/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_template_test.go index 74b6b8275bb8..8820b47efa1d 100644 --- a/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_template_test.go +++ b/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_template_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/datacatalog" ) func TestAccDataCatalogTagTemplate_dataCatalogTagTemplate_updateFields(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_test.go b/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_test.go index 81c08b1474f4..f76a2371c629 100644 --- a/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_test.go +++ b/mmv1/third_party/terraform/services/datacatalog/resource_data_catalog_tag_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/datacatalog" ) func TestAccDataCatalogTag_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job.go.tmpl b/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job.go.tmpl index a87a61fd4036..50e20161057d 100644 --- a/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job.go.tmpl +++ b/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job.go.tmpl @@ -259,6 +259,15 @@ func ResourceDataflowFlexTemplateJob() *schema.Resource { Default: false, Description: `If true, treat DRAINING and CANCELLING as terminal job states and do not wait for further changes before removing from terraform state and moving on. WARNING: this will lead to job name conflicts if you do not ensure that the job names are different, e.g. by embedding a release ID or by using a random_id.`, }, + "create_ignore_already_exists": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: `If true, if a 409 AlreadyExists error is returned on create, the provider will ignore it and adopt the existing resource.`, + }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -298,6 +307,20 @@ func resourceDataflowFlexTemplateJobCreate(d *schema.ResourceData, meta interfac response, err := NewClient(config, userAgent).Projects.Locations.FlexTemplates.Launch(project, region, &request).Do() if err != nil { + if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 409 && d.Get("create_ignore_already_exists").(bool) { + jobName := d.Get("name").(string) + existingJob, lookupErr := findDataflowJobByName(config, project, region, userAgent, jobName) + if lookupErr != nil { + return fmt.Errorf("error looking up job after 409: %s", lookupErr) + } + if existingJob != nil { + d.SetId(existingJob.Id) + if err := d.Set("job_id", existingJob.Id); err != nil { + return fmt.Errorf("Error setting job_id: %s", err) + } + return resourceDataflowFlexTemplateJobRead(d, meta) + } + } return err } @@ -523,6 +546,18 @@ func resourceDataflowFlexTemplateJobRead(d *schema.ResourceData, meta interface{ d.SetId("") return nil } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + + + // Explicitly set client-side fields to default values if unset + if _, ok := d.GetOkExists("create_ignore_already_exists"); !ok { + if err := d.Set("create_ignore_already_exists", false); err != nil { + return fmt.Errorf("Error setting create_ignore_already_exists: %s", err) + } + } return nil } @@ -571,8 +606,13 @@ func resourceDataflowFlexTemplateJobUpdate(d *schema.ResourceData, meta interfac if resourceDataflowJobIsVirtualUpdate(d, ResourceDataflowFlexTemplateJob().Schema) { return nil } + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceDataflowFlexTemplateJob) { + return ResourceDataflowFlexTemplateJob().Read(d, meta) + } + - if jobHasUpdate(d, ResourceDataflowFlexTemplateJob().Schema) { + if flexTemplateJobHasUpdate(d, ResourceDataflowFlexTemplateJob().Schema) { config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -637,6 +677,13 @@ func resourceDataflowFlexTemplateJobUpdate(d *schema.ResourceData, meta interfac } func resourceDataflowFlexTemplateJobDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -865,6 +912,47 @@ func dataflowFlexJobTypeParameterOverride(ename, pname string, d *schema.Resourc return nil } +func findDataflowJobByName(config *transport_tpg.Config, project, region, userAgent, name string) (*dataflow.Job, error) { + client := NewClient(config, userAgent) + + if region == "" { + return nil, fmt.Errorf("region is required to list dataflow jobs") + } + call := client.Projects.Locations.Jobs.List(project, region).Name(name).Filter("ACTIVE") + + resp, err := call.Do() + if err != nil { + return nil, err + } + + for _, job := range resp.Jobs { + if job.Name == name { + if _, terminal := DataflowTerminalStatesMap[job.CurrentState]; !terminal { + return job, nil + } + } + } + + return nil, nil +} + +func flexTemplateJobHasUpdate(d *schema.ResourceData, resourceSchema map[string]*schema.Schema) bool { + if d.HasChange("on_delete") || d.HasChange("labels") || d.HasChange("terraform_labels") || d.HasChange("create_ignore_already_exists") { + for field := range resourceSchema { + if field == "on_delete" || field == "labels" || field == "terraform_labels" || field == "create_ignore_already_exists" { + continue + } + + if d.HasChange(field) { + return true + } + } + return false + } + + return true +} + func init() { registry.Schema{ Name: "google_dataflow_flex_template_job", diff --git a/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_meta.yaml.tmpl b/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_meta.yaml.tmpl index 46885b19677f..d2c0552c5f4f 100644 --- a/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_meta.yaml.tmpl @@ -9,6 +9,7 @@ fields: - field: 'additional_pipeline_options' - field: 'autoscaling_algorithm' - field: 'container_spec_gcs_path' + - field: 'create_ignore_already_exists' - field: 'effective_labels' provider_only: true - field: 'enable_streaming_engine' @@ -37,4 +38,6 @@ fields: provider_only: true - api_field: 'transformNameMapping' - api_field: 'type' + - field: 'deletion_policy' + provider_only: true {{ end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_test.go.tmpl b/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_test.go.tmpl index 1f8691422aba..d3f4dae47858 100644 --- a/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dataflow/resource_dataflow_flex_template_job_test.go.tmpl @@ -12,7 +12,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/services/dataflow" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" compute_tpg "github.com/hashicorp/terraform-provider-google/google/services/compute" @@ -52,6 +56,36 @@ func TestAccDataflowFlexTemplateJob_basic(t *testing.T) { }) } +func TestAccDataflowFlexTemplateJob_createIgnoreAlreadyExists(t *testing.T) { + acctest.SkipIfVcr(t) + t.Parallel() + + randStr := acctest.RandString(t, 10) + job := "tf-test-dataflow-job-" + randStr + bucket := "tf-test-dataflow-bucket-" + randStr + topic := "tf-test-topic" + randStr + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckDataflowJobDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDataflowFlexTemplateJob_basic(job, bucket, topic), + Check: resource.ComposeTestCheckFunc( + testAccDataflowFlexJobExists(t, "google_dataflow_flex_template_job.flex_job", false), + ), + }, + { + Config: testAccDataflowFlexTemplateJob_duplicateIgnoreAlreadyExists(job, bucket, topic), + Check: resource.ComposeTestCheckFunc( + testAccDataflowFlexJobExists(t, "google_dataflow_flex_template_job.duplicate", false), + ), + }, + }, + }) +} + func TestAccDataflowFlexTemplateJob_streamUpdate(t *testing.T) { // This resource uses custom retry logic that cannot be sped up without // modifying the actual resource @@ -304,12 +338,12 @@ func TestAccDataflowFlexTemplateJob_withKmsKey(t *testing.T) { randStr := acctest.RandString(t, 10) job := "tf-test-dataflow-job-" + randStr - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - cryptoKey := kms.CryptoKey.Name + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + cryptoKey := bootstrapped.CryptoKey.Name bucket := "tf-test-dataflow-bucket-" + randStr topic := "tf-test-topic" + randStr - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -2159,4 +2193,72 @@ resource "google_dataflow_flex_template_job" "flex_job" { `, context) } +func testAccDataflowFlexTemplateJob_duplicateIgnoreAlreadyExists(job, bucket, topicName string) string { + return fmt.Sprintf(` + +resource "google_pubsub_topic" "example" { + name = "%s" +} + +data "google_storage_bucket_object" "flex_template" { + name = "latest/flex/Streaming_Data_Generator" + bucket = "dataflow-templates" +} + +resource "google_storage_bucket" "bucket" { + name = "%s" + location = "US-CENTRAL1" + force_destroy = true + uniform_bucket_level_access = true +} + +resource "google_storage_bucket_object" "schema" { + name = "schema.json" + bucket = google_storage_bucket.bucket.name + content = < %q expect DiffSuppress to return %t", tn, tc.Old, tc.New, tc.ExpectDiffSuppress) } } } + +func BootstrapSubnetForDataprocBatches(t *testing.T, subnetName string, networkName string) string { + subnetOptions := map[string]interface{}{ + "privateIpGoogleAccess": true, + } + return tpgcompute.BootstrapSubnetWithOverrides(t, subnetName, networkName, subnetOptions) +} + +func BootstrapSubnetWithFirewallForDataprocBatches(t *testing.T, testId string, subnetName string) string { + networkName := tpgcompute.BootstrapSharedTestNetwork(t, testId) + subnetworkName := BootstrapSubnetForDataprocBatches(t, subnetName, networkName) + BootstrapFirewallForDataprocSharedNetwork(t, subnetName, networkName) + return subnetworkName +} + +// The default network within GCP already comes pre configured with +// certain firewall rules open to allow internal communication. As we +// are boostrapping a network for dataproc tests, we need to additionally +// open up similar rules to allow the nodes to talk to each other +// internally as part of their configuration or this will just hang. +const SharedTestFirewallPrefix = "tf-bootstrap-firewall-" + +func BootstrapFirewallForDataprocSharedNetwork(t *testing.T, firewallName string, networkName string) string { + project := envvar.GetTestProjectFromEnv() + firewallName = SharedTestFirewallPrefix + firewallName + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + log.Printf("[DEBUG] Getting Firewall %q for Network %q", firewallName, networkName) + _, err := tpgcompute.NewClient(config, config.UserAgent).Firewalls.Get(project, firewallName).Do() + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] firewallName %q not found, bootstrapping", firewallName) + url := fmt.Sprintf("%sprojects/%s/global/firewalls", transport_tpg.BaseUrl(tpgcompute.Product, config), project) + + networkId := fmt.Sprintf("projects/%s/global/networks/%s", project, networkName) + allowObj := []interface{}{ + map[string]interface{}{ + "IPProtocol": "icmp", + }, + map[string]interface{}{ + "IPProtocol": "tcp", + "ports": []string{"0-65535"}, + }, + map[string]interface{}{ + "IPProtocol": "udp", + "ports": []string{"0-65535"}, + }, + } + + firewallObj := map[string]interface{}{ + "name": firewallName, + "network": networkId, + "allowed": allowObj, + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + Body: firewallObj, + Timeout: 4 * time.Minute, + }) + if err != nil { + t.Fatalf("Error bootstrapping Firewall %q for Network %q: %s", firewallName, networkName, err) + } + + log.Printf("[DEBUG] Waiting for Firewall creation to finish") + err = tpgcompute.ComputeOperationWaitTime(config, res, project, "Error bootstrapping Firewall", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error bootstrapping Firewall %q: %s", firewallName, err) + } + } + + firewall, err := tpgcompute.NewClient(config, config.UserAgent).Firewalls.Get(project, firewallName).Do() + if err != nil { + t.Errorf("Error getting Firewall %q: %s", firewallName, err) + } + if firewall == nil { + t.Fatalf("Error getting Firewall %q: is nil", firewallName) + } + return firewall.Name +} diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster.go index 3cace0fc20a0..9a1feb7df5a9 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster.go @@ -199,6 +199,7 @@ func ResourceDataprocCluster() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, // User labels are not supported in Dataproc Virtual Cluster tpgresource.SetLabelsDiffWithoutAttributionLabel, @@ -1661,7 +1662,7 @@ by Dataproc`, Computed: true, AtLeastOneOf: clusterSoftwareConfigKeys, ForceNew: true, - DiffSuppressFunc: dataprocImageVersionDiffSuppress, + DiffSuppressFunc: DataprocImageVersionDiffSuppress, Description: `The Cloud Dataproc image version to use for the cluster - this controls the sets of software versions installed onto the nodes when you create clusters. If not specified, defaults to the latest version.`, }, "override_properties": { @@ -2036,6 +2037,9 @@ by Dataproc`, }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -3010,6 +3014,11 @@ func expandAccelerators(configured []interface{}) []*dataproc.AcceleratorConfig } func resourceDataprocClusterUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceDataprocCluster) { + return ResourceDataprocCluster().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -3201,6 +3210,10 @@ func resourceDataprocClusterRead(d *schema.ResourceData, meta interface{}) error return err } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -3534,7 +3547,7 @@ func flattenInitializationActions(nia []*dataproc.NodeInitializationAction) ([]m "script": v.ExecutableFile, } if len(v.ExecutionTimeout) > 0 { - tsec, err := extractInitTimeout(v.ExecutionTimeout) + tsec, err := ExtractInitTimeout(v.ExecutionTimeout) if err != nil { return nil, err } @@ -3833,7 +3846,7 @@ func flattenWorkerInstanceGroupConfig(d *schema.ResourceData, icg *dataproc.Inst return []map[string]interface{}{data} } -func extractInitTimeout(t string) (int, error) { +func ExtractInitTimeout(t string) (int, error) { d, err := time.ParseDuration(t) if err != nil { return 0, err @@ -3842,6 +3855,13 @@ func extractInitTimeout(t string) (int, error) { } func resourceDataprocClusterDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -3889,53 +3909,53 @@ func configOptions(d *schema.ResourceData, option string) (map[string]interface{ return nil, false } -func dataprocImageVersionDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { - oldV, err := parseDataprocImageVersion(old) +func DataprocImageVersionDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { + oldV, err := ParseDataprocImageVersion(old) if err != nil { return false } - newV, err := parseDataprocImageVersion(new) + newV, err := ParseDataprocImageVersion(new) if err != nil { return false } - if newV.major != oldV.major { + if newV.Major != oldV.Major { return false } - if newV.minor != oldV.minor { + if newV.Minor != oldV.Minor { return false } ignoreSubminor := []string{"", "prodcurrent", "prodprevious"} // Only compare subminor version if set to a numeric value in config version. - if !slices.Contains(ignoreSubminor, newV.subminor) && newV.subminor != oldV.subminor { + if !slices.Contains(ignoreSubminor, newV.Subminor) && newV.Subminor != oldV.Subminor { return false } // Only compare os if it is set in config version. - if newV.osName != "" && newV.osName != oldV.osName { + if newV.OsName != "" && newV.OsName != oldV.OsName { return false } return true } -type dataprocImageVersion struct { - major string - minor string - subminor string - osName string +type DataprocImageVersion struct { + Major string + Minor string + Subminor string + OsName string } -func parseDataprocImageVersion(version string) (*dataprocImageVersion, error) { +func ParseDataprocImageVersion(version string) (*DataprocImageVersion, error) { matches := resolveDataprocImageVersion.FindStringSubmatch(version) if len(matches) != 5 { return nil, fmt.Errorf("invalid image version %q", version) } - return &dataprocImageVersion{ - major: matches[1], - minor: matches[2], - subminor: matches[3], - osName: matches[4], + return &DataprocImageVersion{ + Major: matches[1], + Minor: matches[2], + Subminor: matches[3], + OsName: matches[4], }, nil } diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_internal_test.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_internal_test.go index fb5aa82c4808..21e01b7e4f8a 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_internal_test.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_internal_test.go @@ -1,13 +1,15 @@ -package dataproc +package dataproc_test import ( "testing" + + "github.com/hashicorp/terraform-provider-google/google/services/dataproc" ) func TestDataprocExtractInitTimeout(t *testing.T) { t.Parallel() - actual, err := extractInitTimeout("500s") + actual, err := dataproc.ExtractInitTimeout("500s") expected := 500 if err != nil { t.Fatalf("Expected %d, but got error %v", expected, err) @@ -20,7 +22,7 @@ func TestDataprocExtractInitTimeout(t *testing.T) { func TestDataprocExtractInitTimeout_nonSeconds(t *testing.T) { t.Parallel() - actual, err := extractInitTimeout("5m") + actual, err := dataproc.ExtractInitTimeout("5m") expected := 300 if err != nil { t.Fatalf("Expected %d, but got error %v", expected, err) @@ -33,7 +35,7 @@ func TestDataprocExtractInitTimeout_nonSeconds(t *testing.T) { func TestDataprocExtractInitTimeout_empty(t *testing.T) { t.Parallel() - _, err := extractInitTimeout("") + _, err := dataproc.ExtractInitTimeout("") expected := "time: invalid duration" if err != nil && err.Error() != expected { return @@ -44,7 +46,7 @@ func TestDataprocExtractInitTimeout_empty(t *testing.T) { func TestDataprocParseImageVersion(t *testing.T) { t.Parallel() - testCases := map[string]dataprocImageVersion{ + testCases := map[string]dataproc.DataprocImageVersion{ "1.2": {"1", "2", "", ""}, "1.2.3": {"1", "2", "3", ""}, "1.2.3rc": {"1", "2", "3rc", ""}, @@ -54,20 +56,20 @@ func TestDataprocParseImageVersion(t *testing.T) { } for v, expected := range testCases { - actual, err := parseDataprocImageVersion(v) - if actual.major != expected.major { + actual, err := dataproc.ParseDataprocImageVersion(v) + if actual.Major != expected.Major { t.Errorf("parsing version %q returned error: %v", v, err) } if err != nil { t.Errorf("parsing version %q returned error: %v", v, err) } - if actual.minor != expected.minor { + if actual.Minor != expected.Minor { t.Errorf("parsing version %q returned error: %v", v, err) } - if actual.subminor != expected.subminor { + if actual.Subminor != expected.Subminor { t.Errorf("parsing version %q returned error: %v", v, err) } - if actual.osName != expected.osName { + if actual.OsName != expected.OsName { t.Errorf("parsing version %q returned error: %v", v, err) } } @@ -79,7 +81,7 @@ func TestDataprocParseImageVersion(t *testing.T) { "1-debian", } for _, v := range errorTestCases { - if _, err := parseDataprocImageVersion(v); err == nil { + if _, err := dataproc.ParseDataprocImageVersion(v); err == nil { t.Errorf("expected parsing invalid version %q to return error", v) } } @@ -114,12 +116,12 @@ func TestDataprocDiffSuppress(t *testing.T) { } for _, tup := range doSuppress { - if !dataprocImageVersionDiffSuppress("", tup[0], tup[1], nil) { + if !dataproc.DataprocImageVersionDiffSuppress("", tup[0], tup[1], nil) { t.Errorf("expected (old: %q, new: %q) to be suppressed", tup[0], tup[1]) } } for _, tup := range noSuppress { - if dataprocImageVersionDiffSuppress("", tup[0], tup[1], nil) { + if dataproc.DataprocImageVersionDiffSuppress("", tup[0], tup[1], nil) { t.Errorf("expected (old: %q, new: %q) to not be suppressed", tup[0], tup[1]) } } diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_meta.yaml b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_meta.yaml index 7a5bef75c48a..995380a9c134 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_meta.yaml +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_meta.yaml @@ -152,3 +152,5 @@ fields: - api_field: 'virtualClusterConfig.kubernetesClusterConfig.kubernetesSoftwareConfig.componentVersion' - api_field: 'virtualClusterConfig.kubernetesClusterConfig.kubernetesSoftwareConfig.properties' - api_field: 'virtualClusterConfig.stagingBucket' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_migrate.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_migrate.go index 0e503027fbc5..cfd16d501078 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_migrate.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_migrate.go @@ -1147,7 +1147,7 @@ by Dataproc`, Computed: true, AtLeastOneOf: clusterSoftwareConfigKeys, ForceNew: true, - DiffSuppressFunc: dataprocImageVersionDiffSuppress, + DiffSuppressFunc: DataprocImageVersionDiffSuppress, Description: `The Cloud Dataproc image version to use for the cluster - this controls the sets of software versions installed onto the nodes when you create clusters. If not specified, defaults to the latest version.`, }, "override_properties": { diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_test.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_test.go index 72cec85239dc..660c12f3af96 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_test.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_test.go @@ -15,8 +15,14 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" dataproc_tpg "github.com/hashicorp/terraform-provider-google/google/services/dataproc" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataprocmetastore" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -113,8 +119,8 @@ func TestAccDataprocVirtualCluster_basic(t *testing.T) { rnd := acctest.RandString(t, 10) pid := envvar.GetTestProjectFromEnv() version := "3.5-dataproc-17" - networkName := acctest.BootstrapSharedTestNetwork(t, "gke-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "gke-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "gke-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -154,9 +160,9 @@ func TestAccDataprocCluster_withAccelerators(t *testing.T) { project := envvar.GetTestProjectFromEnv() acceleratorType := "nvidia-tesla-t4" zone := "us-central1-c" - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -286,9 +292,9 @@ func TestAccDataprocCluster_withConfidentialCompute(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) imageUri := "https://www.googleapis.com/compute/v1/projects/cloud-dataproc/global/images/dataproc-2-1-ubu20-20241026-165100-rc01" acctest.VcrTest(t, resource.TestCase{ @@ -331,9 +337,9 @@ func TestAccDataprocCluster_withMetadataAndTags(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -361,11 +367,11 @@ func TestAccDataprocCluster_withResourceManagerTags(t *testing.T) { pid := envvar.GetTestProjectFromEnv() projectNumber := envvar.GetTestProjectNumberFromEnv() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) // TODO: remove this IAM binding once tagUser permissions are present in Dataproc Service Agent role. - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: fmt.Sprintf("serviceAccount:service-%s@dataproc-accounts.iam.gserviceaccount.com", projectNumber), Role: "roles/resourcemanager.tagUser", @@ -394,9 +400,9 @@ func TestAccDataprocCluster_withMinNumInstances(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -420,9 +426,9 @@ func TestAccDataprocCluster_withReservationAffinity(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -448,9 +454,9 @@ func TestAccDataprocCluster_withDataprocMetricConfig(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -477,9 +483,9 @@ func TestAccDataprocCluster_withNodeGroupAffinity(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -502,9 +508,9 @@ func TestAccDataprocCluster_singleNodeCluster(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -570,9 +576,9 @@ func TestAccDataprocCluster_nonPreemptibleSecondary(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -595,9 +601,9 @@ func TestAccDataprocCluster_spotSecondary(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -803,9 +809,9 @@ func TestAccDataprocCluster_withStagingBucket(t *testing.T) { var cluster dataproc.Cluster clusterName := fmt.Sprintf("tf-test-dproc-%s", rnd) bucketName := fmt.Sprintf("%s-bucket", clusterName) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -838,9 +844,9 @@ func TestAccDataprocCluster_withTempBucket(t *testing.T) { var cluster dataproc.Cluster clusterName := fmt.Sprintf("tf-test-dproc-%s", rnd) bucketName := fmt.Sprintf("%s-temp-bucket", clusterName) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -872,9 +878,9 @@ func TestAccDataprocCluster_withInitAction(t *testing.T) { var cluster dataproc.Cluster bucketName := fmt.Sprintf("tf-test-dproc-%s-init-bucket", rnd) objectName := "msg.txt" - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -899,9 +905,9 @@ func TestAccDataprocCluster_withConfigOverrides(t *testing.T) { rnd := acctest.RandString(t, 10) var cluster dataproc.Cluster - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -925,9 +931,9 @@ func TestAccDataprocCluster_withServiceAcc(t *testing.T) { sa := "a" + acctest.RandString(t, 10) saEmail := fmt.Sprintf("%s@%s.iam.gserviceaccount.com", sa, envvar.GetTestProjectFromEnv()) rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster @@ -962,9 +968,9 @@ func TestAccDataprocCluster_withImageVersion(t *testing.T) { rnd := acctest.RandString(t, 10) version := "2.0.35-debian10" - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -987,9 +993,9 @@ func TestAccDataprocCluster_withOptionalComponents(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1012,9 +1018,9 @@ func TestAccDataprocCluster_withLifecycleConfigIdleDeleteTtl(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1046,9 +1052,9 @@ func TestAccDataprocCluster_withLifecycleConfigAutoDeletion(t *testing.T) { rnd := acctest.RandString(t, 10) now := time.Now() fmtString := "2006-01-02T15:04:05.072Z" - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1076,9 +1082,9 @@ func TestAccDataprocCluster_withLifecycleConfigIdleStopTtl(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1110,9 +1116,9 @@ func TestAccDataprocCluster_withLifecycleConfigAutoStop(t *testing.T) { rnd := acctest.RandString(t, 10) now := time.Now() fmtString := "2006-01-02T15:04:05.072Z" - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1139,9 +1145,9 @@ func TestAccDataprocCluster_withLabels(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1219,9 +1225,9 @@ func TestAccDataprocCluster_withEndpointConfig(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1243,12 +1249,12 @@ func TestAccDataprocCluster_KMS(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - kms := acctest.BootstrapKMSKey(t) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + bootstrapped := kms.BootstrapKMSKey(t) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@compute-system.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -1262,7 +1268,7 @@ func TestAccDataprocCluster_KMS(t *testing.T) { CheckDestroy: testAccCheckDataprocClusterDestroy(t), Steps: []resource.TestStep{ { - Config: testAccDataprocCluster_KMS(rnd, kms.CryptoKey.Name, subnetworkName), + Config: testAccDataprocCluster_KMS(rnd, bootstrapped.CryptoKey.Name, subnetworkName), Check: resource.ComposeTestCheckFunc( testAccCheckDataprocClusterExists(t, "google_dataproc_cluster.kms", &cluster), ), @@ -1275,10 +1281,10 @@ func TestAccDataprocCluster_withKerberos(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - kms := acctest.BootstrapKMSKey(t) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + bootstrapped := kms.BootstrapKMSKey(t) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1287,7 +1293,7 @@ func TestAccDataprocCluster_withKerberos(t *testing.T) { CheckDestroy: testAccCheckDataprocClusterDestroy(t), Steps: []resource.TestStep{ { - Config: testAccDataprocCluster_withKerberos(rnd, kms.CryptoKey.Name, subnetworkName), + Config: testAccDataprocCluster_withKerberos(rnd, bootstrapped.CryptoKey.Name, subnetworkName), Check: resource.ComposeTestCheckFunc( testAccCheckDataprocClusterExists(t, "google_dataproc_cluster.kerb", &cluster), ), @@ -1300,9 +1306,9 @@ func TestAccDataprocCluster_withIdentityConfig(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1325,9 +1331,9 @@ func TestAccDataprocCluster_updateIdentityConfigUserMapping(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster @@ -1358,9 +1364,9 @@ func TestAccDataprocCluster_withAutoscalingPolicy(t *testing.T) { t.Parallel() rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) var cluster dataproc.Cluster acctest.VcrTest(t, resource.TestCase{ @@ -1425,9 +1431,9 @@ func TestAccDataprocCluster_withClusterTier(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1495,9 +1501,9 @@ func TestAccDataprocCluster_withEngine(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1573,9 +1579,9 @@ func TestAccDataprocCluster_withClusterTypeSingleNode(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1599,9 +1605,9 @@ func TestAccDataprocCluster_withClusterTypeZeroScale(t *testing.T) { var cluster dataproc.Cluster rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_upgrade_test.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_upgrade_test.go index 5e427a19e75f..04121e0aad72 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_upgrade_test.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_cluster_upgrade_test.go @@ -8,6 +8,7 @@ import ( "google.golang.org/api/dataproc/v1" "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" ) // Tests schema version migration by creating a cluster with an old version of the provider (4.65.0) @@ -18,9 +19,9 @@ func TestAccDataprocClusterLabelsMigration_withoutLabels_withoutChanges(t *testi rnd := acctest.RandString(t, 10) var cluster dataproc.Cluster - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) oldVersion := map[string]resource.ExternalProvider{ "google": { @@ -67,9 +68,9 @@ func TestAccDataprocClusterLabelsMigration_withLabels_withoutChanges(t *testing. rnd := acctest.RandString(t, 10) var cluster dataproc.Cluster - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) oldVersion := map[string]resource.ExternalProvider{ "google": { @@ -119,9 +120,9 @@ func TestAccDataprocClusterLabelsMigration_withUpdate(t *testing.T) { rnd := acctest.RandString(t, 10) var cluster dataproc.Cluster - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) oldVersion := map[string]resource.ExternalProvider{ "google": { diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job.go index 9f09bb3756b6..11ddb6352d84 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job.go @@ -32,6 +32,7 @@ func ResourceDataprocJob() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, tpgresource.SetLabelsDiff, ), @@ -213,6 +214,9 @@ func ResourceDataprocJob() *schema.Resource { "pig_config": pigSchema, "sparksql_config": sparkSqlSchema, "presto_config": prestoSchema, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -413,10 +417,22 @@ func resourceDataprocJobRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error setting presto_config: %s", err) } } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceDataprocJobDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_meta.yaml b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_meta.yaml index 409d58798690..038263234ade 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_meta.yaml +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_meta.yaml @@ -75,3 +75,5 @@ fields: provider_only: true - field: 'wait_for_completion' provider_only: true + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_test.go.tmpl b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_test.go.tmpl index 23b016be221b..29623964ad08 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_job_test.go.tmpl @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" tpgdataproc "github.com/hashicorp/terraform-provider-google/google/services/dataproc" "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -50,9 +51,9 @@ func TestAccDataprocJob_updatable(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) jobId := fmt.Sprintf("tf-test-dproc-update-job-id-%s", rnd) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -83,9 +84,9 @@ func TestAccDataprocJob_PySpark(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) jobId := fmt.Sprintf("tf-test-dproc-custom-job-id-%s", rnd) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -125,9 +126,9 @@ func TestAccDataprocJob_Spark(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -161,9 +162,9 @@ func TestAccDataprocJob_Hadoop(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -197,9 +198,9 @@ func TestAccDataprocJob_Hive(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -233,9 +234,9 @@ func TestAccDataprocJob_Pig(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -297,15 +298,15 @@ func testAccDataprocJobSparkSql(t *testing.T, config string) { func TestAccDataprocJob_SparkSql_QueryList(t *testing.T) { rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) testAccDataprocJobSparkSql(t, testAccDataprocJob_SparkSql_QueryList(rnd, subnetworkName)) } func TestAccDataprocJob_SparkSql_QueryFile(t *testing.T) { rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) testAccDataprocJobSparkSql(t, testAccDataprocJob_SparkSql_QueryFile(rnd, subnetworkName)) } @@ -314,9 +315,9 @@ func TestAccDataprocJob_Presto(t *testing.T) { var job dataproc.Job rnd := acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedTestNetwork(t, "dataproc-cluster") - subnetworkName := acctest.BootstrapSubnet(t, "dataproc-cluster", networkName) - acctest.BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, "dataproc-cluster") + subnetworkName := tpgcompute.BootstrapSubnet(t, "dataproc-cluster", networkName) + BootstrapFirewallForDataprocSharedNetwork(t, "dataproc-cluster", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_session_template_test.go b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_session_template_test.go index c336f6ac7d90..a504c8c7e35f 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_session_template_test.go +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_session_template_test.go @@ -8,12 +8,17 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataproc" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataprocmetastore" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataprocSessionTemplate_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@dataproc-accounts.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -22,9 +27,9 @@ func TestAccDataprocSessionTemplate_update(t *testing.T) { context := map[string]interface{}{ "project_name": envvar.GetTestProjectFromEnv(), - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-session-template-key1").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-session-template-key1").CryptoKey.Name, "prevent_destroy": false, - "subnetwork_name": acctest.BootstrapSubnetWithFirewallForDataprocBatches(t, "jupyer-session-test-network", "jupyter-session-test-subnetwork"), + "subnetwork_name": BootstrapSubnetWithFirewallForDataprocBatches(t, "jupyer-session-test-network", "jupyter-session-test-subnetwork"), "random_suffix": acctest.RandString(t, 10), } @@ -110,7 +115,7 @@ resource "google_dataproc_session_template" "dataproc_session_templates_jupyter_ ttl = "4800s" network_tags = ["tag2"] kms_key = "%{kms_key_name}" - subnetwork_uri = "%{subnetwork_name}" + subnetwork_uri = "%{subnetwork_name}" service_account = "${data.google_project.project.number}-compute@developer.gserviceaccount.com" staging_bucket = google_storage_bucket.bucket.name } diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template.go.tmpl b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template.go.tmpl index 2ca6fad78138..96e354b52f58 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template.go.tmpl +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template.go.tmpl @@ -32,6 +32,7 @@ func ResourceDataprocWorkflowTemplate() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, tpgresource.SetLabelsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), SchemaVersion: 1, StateUpgraders: []schema.StateUpgrader{ @@ -147,6 +148,9 @@ func ResourceDataprocWorkflowTemplate() *schema.Resource { Computed: true, Description: "Output only. The time template was last updated.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -2322,6 +2326,11 @@ func resourceDataprocWorkflowTemplateRead(d *schema.ResourceData, meta interface if err = d.Set("update_time", res.UpdateTime); err != nil { return fmt.Errorf("error setting update_time in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } @@ -2332,6 +2341,13 @@ func resourceDataprocWorkflowTemplateUpdate(d *schema.ResourceData, meta interfa } func resourceDataprocWorkflowTemplateDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_meta.yaml.tmpl b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_meta.yaml.tmpl index 35bb465f38b0..d5f866670807 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_meta.yaml.tmpl @@ -187,3 +187,5 @@ fields: provider_only: true - api_field: 'updateTime' - api_field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_test.go.tmpl b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_test.go.tmpl index 0ee1ed7d883a..798fc7174044 100644 --- a/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dataproc/resource_dataproc_workflow_template_test.go.tmpl @@ -8,7 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataproc" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -82,7 +84,7 @@ func TestAccDataprocWorkflowTemplate_encryptionConfig(t *testing.T) { "random_suffix": acctest.RandString(t, 10), "project": envvar.GetTestProjectFromEnv(), "version": "2.0.35-debian10", - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-workflow").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-dataproc-workflow").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/dataprocgdc/resource_dataproc_gdc_application_environment_test.go b/mmv1/third_party/terraform/services/dataprocgdc/resource_dataproc_gdc_application_environment_test.go index 0b0f43830992..44f60f4e10d1 100644 --- a/mmv1/third_party/terraform/services/dataprocgdc/resource_dataproc_gdc_application_environment_test.go +++ b/mmv1/third_party/terraform/services/dataprocgdc/resource_dataproc_gdc_application_environment_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataprocgdc" ) func TestAccDataprocGdcApplicationEnvironment_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dataprocmetastore/data_source_dataproc_metastore_service_test.go b/mmv1/third_party/terraform/services/dataprocmetastore/data_source_dataproc_metastore_service_test.go index 04109d7f2c73..6766ed218809 100644 --- a/mmv1/third_party/terraform/services/dataprocmetastore/data_source_dataproc_metastore_service_test.go +++ b/mmv1/third_party/terraform/services/dataprocmetastore/data_source_dataproc_metastore_service_test.go @@ -3,6 +3,7 @@ package dataprocmetastore_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataprocmetastore" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_federation_test.go b/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_federation_test.go index 72ac92b3671b..4f3950d8edcd 100644 --- a/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_federation_test.go +++ b/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_federation_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataprocmetastore" "github.com/hashicorp/terraform-provider-google/google/services/tags" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "strings" diff --git a/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_service_test.go b/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_service_test.go index e2bfcb10391a..e5b69db07674 100644 --- a/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_service_test.go +++ b/mmv1/third_party/terraform/services/dataprocmetastore/resource_dataproc_metastore_service_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dataprocmetastore" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/services/tags" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "strings" diff --git a/mmv1/third_party/terraform/services/datastream/data_source_google_datastream_static_ips.go b/mmv1/third_party/terraform/services/datastream/data_source_google_datastream_static_ips.go index 5574896bc6b9..4bdcc9707095 100644 --- a/mmv1/third_party/terraform/services/datastream/data_source_google_datastream_static_ips.go +++ b/mmv1/third_party/terraform/services/datastream/data_source_google_datastream_static_ips.go @@ -46,7 +46,7 @@ func dataSourceGoogleDatastreamStaticIpsRead(d *schema.ResourceData, meta interf return err } - url, err := tpgresource.ReplaceVars(d, config, "{{DatastreamBasePath}}projects/{{project}}/locations/{{location}}:fetchStaticIps") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}:fetchStaticIps") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/datastream/resource_datastream_connection_profile_test.go b/mmv1/third_party/terraform/services/datastream/resource_datastream_connection_profile_test.go index bad46829cb62..23a8d1f32b11 100644 --- a/mmv1/third_party/terraform/services/datastream/resource_datastream_connection_profile_test.go +++ b/mmv1/third_party/terraform/services/datastream/resource_datastream_connection_profile_test.go @@ -8,6 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/datastream" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDatastreamConnectionProfile_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/datastream/resource_datastream_stream_test.go b/mmv1/third_party/terraform/services/datastream/resource_datastream_stream_test.go index f021e9fa6b08..0ac1d3a69b42 100644 --- a/mmv1/third_party/terraform/services/datastream/resource_datastream_stream_test.go +++ b/mmv1/third_party/terraform/services/datastream/resource_datastream_stream_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/datastream" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDatastreamStream_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/deploymentmanager/resource_deployment_manager_deployment_test.go b/mmv1/third_party/terraform/services/deploymentmanager/resource_deployment_manager_deployment_test.go index 054f0e880603..99830981ec11 100644 --- a/mmv1/third_party/terraform/services/deploymentmanager/resource_deployment_manager_deployment_test.go +++ b/mmv1/third_party/terraform/services/deploymentmanager/resource_deployment_manager_deployment_test.go @@ -435,7 +435,7 @@ func testAccCheckDeploymentManagerDeploymentDestroyProducer(t *testing.T) func(s config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{DeploymentManagerBasePath}}projects/{{project}}/global/deployments/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(deploymentmanager.Product, config)+"projects/{{project}}/global/deployments/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_account_connector_test.go b/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_account_connector_test.go index c8e51cca34d7..87e7cde290a5 100644 --- a/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_account_connector_test.go +++ b/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_account_connector_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/developerconnect" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccDeveloperConnectAccountConnector_developerConnectAccountConnectorGithubUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_connection_test.go b/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_connection_test.go index 6f2ab046c446..186b95e30739 100644 --- a/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_connection_test.go +++ b/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_connection_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/developerconnect" ) func TestAccDeveloperConnectConnection_developerConnectConnectionGithubUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_insights_config_test.go b/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_insights_config_test.go index 07dcd42965bf..4a6e4a71d9e0 100644 --- a/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_insights_config_test.go +++ b/mmv1/third_party/terraform/services/developerconnect/resource_developer_connect_insights_config_test.go @@ -21,6 +21,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" + _ "github.com/hashicorp/terraform-provider-google/google/services/developerconnect" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDeveloperConnectInsightsConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_agent_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_agent_test.go index 640d82c9e1e5..522da1cd4506 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_agent_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_agent_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDialogflowAgent_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_conversation_profile_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_conversation_profile_test.go index 4f5774799a66..3d32526d6bc1 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_conversation_profile_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_conversation_profile_test.go @@ -20,6 +20,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDialogflowConversationProfile_update(t *testing.T) { @@ -496,3 +500,100 @@ func testAccDialogflowConversationProfile_dialogflowRegional(context map[string] } `, context) } + +func TestAccDialogflowConversationProfile_sipConfig(t *testing.T) { + t.Parallel() + + randomSuffix := acctest.RandString(t, 10) + + context := map[string]interface{}{ + "profile_name": "tf-test-dialogflow-profile-" + randomSuffix, + "random_suffix": randomSuffix, + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + CheckDestroy: testAccCheckDialogflowConversationProfileDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDialogflowConversationProfile_sipConfigStep1(context), + }, + { + ResourceName: "google_dialogflow_conversation_profile.profile", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccDialogflowConversationProfile_sipConfigStep2(context), + }, + { + ResourceName: "google_dialogflow_conversation_profile.profile", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccDialogflowConversationProfile_sipConfigStep3(context), + }, + { + ResourceName: "google_dialogflow_conversation_profile.profile", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccDialogflowConversationProfile_sipConfigStep1(context), + }, + { + ResourceName: "google_dialogflow_conversation_profile.profile", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccDialogflowConversationProfile_sipConfigStep1(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_dialogflow_conversation_profile" "profile" { + provider = google-beta + display_name = "%{profile_name}" + location = "europe-west1" + language_code = "en-US" +} +`, context) +} + +func testAccDialogflowConversationProfile_sipConfigStep2(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_dialogflow_conversation_profile" "profile" { + provider = google-beta + display_name = "%{profile_name}" + location = "europe-west1" + language_code = "en-US" + sip_config { + create_conversation_on_the_fly = true + inactive_start = true + max_audio_recording_duration = "300s" + allow_virtual_agent_interaction = true + keep_conversation_running = true + copy_inbound_call_leg_headers = ["X-Header-1"] + ignore_reinvite_media_direction = true + } +} +`, context) +} + +func testAccDialogflowConversationProfile_sipConfigStep3(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_dialogflow_conversation_profile" "profile" { + provider = google-beta + display_name = "%{profile_name}" + location = "europe-west1" + language_code = "en-US" + sip_config { + max_audio_recording_duration = "600s" + copy_inbound_call_leg_headers = ["X-Header-1", "X-Header-2"] + } +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_entity_type_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_entity_type_test.go index 40339bd665f0..e27468dc50bc 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_entity_type_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_entity_type_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_environment_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_environment_test.go index b342b93c5f67..6ef95e5adfc1 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_environment_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_environment_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_fulfillment_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_fulfillment_test.go index 4cde09ca75e7..4868c3b5c208 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_fulfillment_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_fulfillment_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_generator_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_generator_test.go index 5a292719b58d..b98315771f51 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_generator_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_generator_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_intent_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_intent_test.go index f4e4194ca4d4..082dcfedbe00 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_intent_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_intent_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_sip_trunk_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_sip_trunk_test.go new file mode 100644 index 000000000000..b705e555f732 --- /dev/null +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_sip_trunk_test.go @@ -0,0 +1,111 @@ +/* + * Copyright 2026 Google Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package dialogflow_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func TestAccDialogflowSipTrunk_update(t *testing.T) { + t.Parallel() + + randomSuffix := acctest.RandString(t, 10) + + context := map[string]interface{}{ + "trunk_name": "tf-test-trunk-" + randomSuffix, + "random_suffix": randomSuffix, + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckDialogflowSipTrunkDestroyCustom(t), + Steps: []resource.TestStep{ + { + Config: testAccDialogflowSipTrunk_updateStep1(context), + }, + { + Config: testAccDialogflowSipTrunk_updateStep2(context), + }, + }, + }) +} + +func testAccCheckDialogflowSipTrunkDestroyCustom(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "google_dialogflow_sip_trunk" { + continue + } + + config := acctest.GoogleProviderConfig(t) + + location := "europe-west3" + if loc, ok := rs.Primary.Attributes["location"]; ok { + location = loc + } + + url := fmt.Sprintf("https://%s-dialogflow.googleapis.com/v2beta1/%s", location, rs.Primary.ID) + + billingProject := "" + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, + }) + if err == nil { + return fmt.Errorf("SipTrunk still exists at %s", url) + } + } + + return nil + } +} + +func testAccDialogflowSipTrunk_updateStep1(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_dialogflow_sip_trunk" "trunk" { + display_name = "%{trunk_name}" + location = "europe-west3" + expected_hostname = [ + "%{trunk_name}.example.com" + ] +} +`, context) +} + +func testAccDialogflowSipTrunk_updateStep2(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_dialogflow_sip_trunk" "trunk" { + display_name = "%{trunk_name}-updated" + location = "europe-west3" + expected_hostname = [ + "%{trunk_name}.example.com", + "%{trunk_name}-2.example.com" + ] +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_version_test.go b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_version_test.go index f2e6c63281cf..a12c9b62f801 100644 --- a/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_version_test.go +++ b/mmv1/third_party/terraform/services/dialogflow/resource_dialogflow_version_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflow" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_agent_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_agent_test.go index 9e4965209503..8081695375b0 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_agent_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_agent_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_generator_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_generator_test.go index 328afa7b07d4..694a8ed66be4 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_generator_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_generator_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" ) func TestAccDialogflowCXGenerator_dialogflowcxGeneratorUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_playbook_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_playbook_test.go index bc555efd3f7b..6ce8f19484c5 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_playbook_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_playbook_test.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_security_settings_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_security_settings_test.go index e8aa3661a17d..2e2ad71e5c3c 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_security_settings_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_security_settings_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/datalossprevention" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDialogflowCXSecuritySettings_dialogflowcxSecuritySettings_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_test_case_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_test_case_test.go index 5f76f8bf2670..eaa5820f8bb6 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_test_case_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_test_case_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_tool_test.go.tmpl b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_tool_test.go.tmpl index 5c428f485ccd..e23de50beb85 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_tool_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflow_cx_tool_test.go.tmpl @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/integrationconnectors" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_entity_type_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_entity_type_test.go index cd48f8ca6e92..e7eb7042d819 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_entity_type_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_entity_type_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" ) func TestAccDialogflowCXEntityType_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_environment_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_environment_test.go index d7b2f2fdf6af..1d418600e790 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_environment_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_environment_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_flow_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_flow_test.go index 11db4db55773..abe31f9f725d 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_flow_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_flow_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDialogflowCXFlow_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_generative_settings_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_generative_settings_test.go index 01b9a3bfb57b..69bc6fa08f1a 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_generative_settings_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_generative_settings_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" ) func TestAccDialogflowCXGenerativeSettings_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_intent_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_intent_test.go index 0ac876819db3..909eadb1cb47 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_intent_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_intent_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" ) func TestAccDialogflowCXIntent_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_page_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_page_test.go index a23053ea67c4..9b0f6a4c905d 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_page_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_page_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDialogflowCXPage_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_version_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_version_test.go index f16edf0b400c..d837c753bfc4 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_version_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_version_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" ) func TestAccDialogflowCXVersion_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_webhook_test.go b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_webhook_test.go index e27412ab1921..aa363f881286 100644 --- a/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_webhook_test.go +++ b/mmv1/third_party/terraform/services/dialogflowcx/resource_dialogflowcx_webhook_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dialogflowcx" ) func TestAccDialogflowCXWebhook_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store.go b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store.go index 6c6b44a73d7c..10c5781a1e45 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store.go +++ b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store.go @@ -1,5 +1,3 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 package discoveryengine import ( @@ -50,7 +48,7 @@ func dataSourceGoogleDiscoveryEngineDataStoreRead(d *schema.ResourceData, meta i var res map[string]interface{} if hasId { - url, err := tpgresource.ReplaceVars(d, config, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/default_collection/dataStores/{{data_store_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/collections/default_collection/dataStores/{{data_store_id}}") if err != nil { return err } @@ -67,7 +65,7 @@ func dataSourceGoogleDiscoveryEngineDataStoreRead(d *schema.ResourceData, meta i } } else { // List all data stores and filter by display_name - listURL, err := tpgresource.ReplaceVars(d, config, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/default_collection/dataStores") + listURL, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/collections/default_collection/dataStores") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store_test.go b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store_test.go index 9bd1d102416f..e7f1295bfb94 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_store_test.go @@ -1,5 +1,3 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 package discoveryengine_test import ( @@ -7,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDataSourceGoogleDiscoveryEngineDataStore_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores.go b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores.go index bb0f01ddb9ec..695d65b4ffa4 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores.go +++ b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores.go @@ -1,5 +1,3 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 package discoveryengine import ( @@ -92,7 +90,7 @@ func dataSourceGoogleDiscoveryEngineDataStoresRead(d *schema.ResourceData, meta billingProject = bp } - url, err := tpgresource.ReplaceVars(d, config, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/default_collection/dataStores") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/collections/default_collection/dataStores") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores_test.go b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores_test.go index b5574a9bdbc0..080a7d107c80 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/data_source_discovery_engine_data_stores_test.go @@ -1,5 +1,3 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 package discoveryengine_test import ( @@ -7,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDataSourceGoogleDiscoveryEngineDataStores_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_acl_config_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_acl_config_test.go index c6b385d7a19b..be8aafc3dd95 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_acl_config_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_acl_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineAclConfig_discoveryengineAclconfigBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_assistant_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_assistant_test.go index 2ec6ebab61bf..f05ef4e786f2 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_assistant_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_assistant_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineAssistant_discoveryengineAssistantBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_chat_engine_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_chat_engine_test.go index 06e48be432f8..8a9308df6e0a 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_chat_engine_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_chat_engine_test.go @@ -3,6 +3,7 @@ package discoveryengine_test import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" "testing" ) diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_cmek_config_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_cmek_config_test.go index a6305dbb909b..0503237723fb 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_cmek_config_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_cmek_config_test.go @@ -5,13 +5,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDiscoveryEngineCmekConfig_discoveryengineCmekconfigDefaultExample_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us", "tftest-shared-key-"+acctest.RandString(t, 10)).CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us", "tftest-shared-key-"+acctest.RandString(t, 10)).CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_control_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_control_test.go index 693a6dce3912..a071eff22dde 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_control_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_control_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineControl_discoveryengineControlBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_data_store_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_data_store_test.go index aa84960d94b8..f5afc40e763a 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_data_store_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_data_store_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineDataStore_discoveryengineDatastoreBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_license_config_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_license_config_test.go index 673da0c0ba30..d41a9a766273 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_license_config_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_license_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineLicenseConfig_discoveryengineLicenseconfigBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_recommendation_engine_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_recommendation_engine_test.go index 8a576f38f892..be3bf75f9eeb 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_recommendation_engine_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_recommendation_engine_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineRecommendationEngine_discoveryengineRecommendationengineMediaExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_search_engine_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_search_engine_test.go index 563409c25317..ca4577d8cbed 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_search_engine_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_search_engine_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_serving_config_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_serving_config_test.go index 9ab9cf948a78..437adae9f1f5 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_serving_config_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_serving_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineServingConfig_discoveryengineServingConfigBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_user_store_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_user_store_test.go index 35b5126892d7..7d185fede2c0 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_user_store_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_user_store_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineUserStore_discoveryengineUserstoreBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_widget_config_test.go b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_widget_config_test.go index a029e2d746c0..8bac4de8085e 100644 --- a/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_widget_config_test.go +++ b/mmv1/third_party/terraform/services/discoveryengine/resource_discovery_engine_widget_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/discoveryengine" ) func TestAccDiscoveryEngineWidgetConfig_discoveryengineWidgetconfigBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/data_source_dns_key_test.go b/mmv1/third_party/terraform/services/dns/data_source_dns_key_test.go index eb6c37bad539..24924e0a98ca 100644 --- a/mmv1/third_party/terraform/services/dns/data_source_dns_key_test.go +++ b/mmv1/third_party/terraform/services/dns/data_source_dns_key_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" ) func TestAccDataSourceDNSKeys_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zone_test.go.tmpl b/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zone_test.go.tmpl index 766755a4cb45..721942d287c1 100644 --- a/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zone_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zone_test.go.tmpl @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" ) func TestAccDataSourceDnsManagedZone_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zones_test.go b/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zones_test.go index a4d22002ad98..ff50a82625d9 100644 --- a/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zones_test.go +++ b/mmv1/third_party/terraform/services/dns/data_source_dns_managed_zones_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" ) func TestAccDataSourceDnsManagedZones_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/data_source_dns_record_set_test.go b/mmv1/third_party/terraform/services/dns/data_source_dns_record_set_test.go index 795e8dcd2f65..690659b5c497 100644 --- a/mmv1/third_party/terraform/services/dns/data_source_dns_record_set_test.go +++ b/mmv1/third_party/terraform/services/dns/data_source_dns_record_set_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" ) func TestAcccDataSourceDnsRecordSet_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/data_source_dns_record_sets_test.go b/mmv1/third_party/terraform/services/dns/data_source_dns_record_sets_test.go index 624ca82f58e5..719d29393a84 100644 --- a/mmv1/third_party/terraform/services/dns/data_source_dns_record_sets_test.go +++ b/mmv1/third_party/terraform/services/dns/data_source_dns_record_sets_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" ) func TestAccDataSourceDnsRecordSets_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_managed_zone_test.go.tmpl b/mmv1/third_party/terraform/services/dns/resource_dns_managed_zone_test.go.tmpl index 4c0130495226..f4d86a7491a8 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_managed_zone_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dns/resource_dns_managed_zone_test.go.tmpl @@ -4,6 +4,9 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicedirectory" "github.com/hashicorp/terraform-provider-google/google/envvar" tpgdns "github.com/hashicorp/terraform-provider-google/google/services/dns" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_policy_test.go b/mmv1/third_party/terraform/services/dns/resource_dns_policy_test.go index aa2811070392..c82a21628874 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_policy_test.go +++ b/mmv1/third_party/terraform/services/dns/resource_dns_policy_test.go @@ -5,6 +5,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_record_set.go b/mmv1/third_party/terraform/services/dns/resource_dns_record_set.go index 5c6d4efff85d..3b74172de32e 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_record_set.go +++ b/mmv1/third_party/terraform/services/dns/resource_dns_record_set.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-google/google/registry" + "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "google.golang.org/api/dns/v1" @@ -97,6 +98,7 @@ func ResourceDnsRecordSet() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -243,6 +245,9 @@ func ResourceDnsRecordSet() *schema.Resource { ForceNew: true, Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -477,10 +482,21 @@ func resourceDnsRecordSetRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error setting project: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceDnsRecordSetDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -567,6 +583,11 @@ func resourceDnsRecordSetDelete(d *schema.ResourceData, meta interface{}) error } func resourceDnsRecordSetUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceDnsRecordSet) { + return ResourceDnsRecordSet().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -835,7 +856,7 @@ func expandDnsRecordSetHealthCheckedTargetsInternalLoadBalancerNetworkUrl(v inte } else if strings.HasPrefix(v.(string), "https://") { return v, nil } - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}"+v.(string)) + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(compute.Product, config)+v.(string)) if err != nil { return "", err } diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_record_set_meta.yaml.tmpl b/mmv1/third_party/terraform/services/dns/resource_dns_record_set_meta.yaml.tmpl index 49cb9682f4f9..7f53537d4df1 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_record_set_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/dns/resource_dns_record_set_meta.yaml.tmpl @@ -56,3 +56,5 @@ fields: - api_field: 'rrdatas' - api_field: 'ttl' - api_field: 'type' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_record_set_test.go.tmpl b/mmv1/third_party/terraform/services/dns/resource_dns_record_set_test.go.tmpl index 82e1d2319cec..0b865455e9ed 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_record_set_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dns/resource_dns_record_set_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" tpgdns "github.com/hashicorp/terraform-provider-google/google/services/dns" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_rule_test.go.tmpl b/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_rule_test.go.tmpl index b4cdf5492903..6c63957db70f 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_rule_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_rule_test.go.tmpl @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" ) func TestAccDNSResponsePolicyRule_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_test.go.tmpl b/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_test.go.tmpl index bd8ebc00dbf0..c033b7e2c141 100644 --- a/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/dns/resource_dns_response_policy_test.go.tmpl @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" ) func TestAccDNSResponsePolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/documentai/resource_document_ai_schema_test.go b/mmv1/third_party/terraform/services/documentai/resource_document_ai_schema_test.go index 1dcbcd7965e3..5f36586fe62a 100644 --- a/mmv1/third_party/terraform/services/documentai/resource_document_ai_schema_test.go +++ b/mmv1/third_party/terraform/services/documentai/resource_document_ai_schema_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/documentai" ) func TestAccDocumentAISchema_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/documentaiwarehouse/resource_document_ai_warehouse_document_schema_test.go b/mmv1/third_party/terraform/services/documentaiwarehouse/resource_document_ai_warehouse_document_schema_test.go index 1a3a5568b955..a9cd20e2f628 100644 --- a/mmv1/third_party/terraform/services/documentaiwarehouse/resource_document_ai_warehouse_document_schema_test.go +++ b/mmv1/third_party/terraform/services/documentaiwarehouse/resource_document_ai_warehouse_document_schema_test.go @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/documentaiwarehouse" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -591,7 +593,7 @@ func testAccCheckDocumentAIWarehouseDocumentSchemaDestroyProducer(t *testing.T) config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{DocumentAIWarehouseBasePath}}{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(documentaiwarehouse.Product, config)+"{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/essentialcontacts/resource_essential_contacts_contact_test.go b/mmv1/third_party/terraform/services/essentialcontacts/resource_essential_contacts_contact_test.go index e1b3c7dfd039..c004c59ced88 100644 --- a/mmv1/third_party/terraform/services/essentialcontacts/resource_essential_contacts_contact_test.go +++ b/mmv1/third_party/terraform/services/essentialcontacts/resource_essential_contacts_contact_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/essentialcontacts" ) func TestAccEssentialContactsContact_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_channel_test.go b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_channel_test.go index 5c6a91c1c3b3..34f4157ee416 100644 --- a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_channel_test.go +++ b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_channel_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/eventarc" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) @@ -17,11 +20,11 @@ func TestAccEventarcChannel_cryptoKeyUpdate(t *testing.T) { "region": region, "project_name": envvar.GetTestProjectFromEnv(), "project_number": envvar.GetTestProjectNumberFromEnv(), - "key1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-channel-key1").CryptoKey.Name, - "key2": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-channel-key2").CryptoKey.Name, + "key1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-channel-key1").CryptoKey.Name, + "key2": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-channel-key2").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", diff --git a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_api_source_test.go.tmpl b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_api_source_test.go.tmpl index 8d50165baa7a..502b476052ce 100644 --- a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_api_source_test.go.tmpl +++ b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_api_source_test.go.tmpl @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/eventarc" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_channel_config_test.go b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_channel_config_test.go index ff3ffa0299eb..400f1fbc3c40 100644 --- a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_channel_config_test.go +++ b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_google_channel_config_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/eventarc" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" @@ -39,7 +42,7 @@ func testAccEventarcGoogleChannelConfig_basic(t *testing.T) { "region": region, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -79,7 +82,7 @@ func testAccEventarcGoogleChannelConfig_longForm(t *testing.T) { "region": region, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -120,10 +123,10 @@ func testAccEventarcGoogleChannelConfig_cryptoKeyUpdate(t *testing.T) { "project_number": envvar.GetTestProjectNumberFromEnv(), "region": region, "random_suffix": acctest.RandString(t, 10), - "key1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-google-channel-config-key1").CryptoKey.Name, - "key2": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-google-channel-config-key2").CryptoKey.Name, + "key1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-google-channel-config-key1").CryptoKey.Name, + "key2": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-google-channel-config-key2").CryptoKey.Name, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", diff --git a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_message_bus_test.go b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_message_bus_test.go index 4697db07ef60..96afa2cc9044 100644 --- a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_message_bus_test.go +++ b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_message_bus_test.go @@ -10,6 +10,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/eventarc" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -44,7 +48,7 @@ func testAccEventarcMessageBus_basic(t *testing.T) { "region": envvar.GetTestRegionFromEnv(), "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -90,10 +94,10 @@ func testAccEventarcMessageBus_cryptoKey(t *testing.T) { context := map[string]interface{}{ "project_number": envvar.GetTestProjectNumberFromEnv(), "region": region, - "key": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-messagebus-key").CryptoKey.Name, + "key": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-messagebus-key").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -136,11 +140,11 @@ func testAccEventarcMessageBus_update(t *testing.T) { context := map[string]interface{}{ "project_number": envvar.GetTestProjectNumberFromEnv(), "region": region, - "key1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-messagebus-key1").CryptoKey.Name, - "key2": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-messagebus-key2").CryptoKey.Name, + "key1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-messagebus-key1").CryptoKey.Name, + "key2": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-messagebus-key2").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -241,11 +245,11 @@ func testAccEventarcMessageBus_googleApiSource(t *testing.T) { region := envvar.GetTestRegionFromEnv() context := map[string]interface{}{ "project_number": envvar.GetTestProjectNumberFromEnv(), - "key1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-googleapisource-key1").CryptoKey.Name, + "key1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-googleapisource-key1").CryptoKey.Name, "region": region, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -307,12 +311,12 @@ func testAccEventarcMessageBus_updateGoogleApiSource(t *testing.T) { region := envvar.GetTestRegionFromEnv() context := map[string]interface{}{ "project_number": envvar.GetTestProjectNumberFromEnv(), - "key1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-googleapisource-key1").CryptoKey.Name, - "key2": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-googleapisource-key2").CryptoKey.Name, + "key1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-googleapisource-key1").CryptoKey.Name, + "key2": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", region, "tf-bootstrap-eventarc-googleapisource-key2").CryptoKey.Name, "region": region, "random_suffix": acctest.RandString(t, 10), } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -661,7 +665,7 @@ func testAccCheckEventarcMessageBusDestroyProducer(t *testing.T) func(s *terrafo config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{EventarcBasePath}}projects/{{project}}/locations/{{location}}/messageBuses/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(eventarc.Product, config)+"projects/{{project}}/locations/{{location}}/messageBuses/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_pipeline_test.go b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_pipeline_test.go index 431cce671aff..e575b1e51d3a 100644 --- a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_pipeline_test.go +++ b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_pipeline_test.go @@ -5,6 +5,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/eventarc" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" @@ -20,12 +24,12 @@ func TestAccEventarcPipeline_update(t *testing.T) { "pipeline_name": "tf-test-some-pipeline" + randomSuffix, "topic_name": "tf-test-some-topic" + randomSuffix, "service_account": envvar.GetTestServiceAccountFromEnv(t), - "key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-pipeline-key").CryptoKey.Name, - "key2_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-pipeline-key2").CryptoKey.Name, + "key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-pipeline-key").CryptoKey.Name, + "key2_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-eventarc-pipeline-key2").CryptoKey.Name, "random_suffix": randomSuffix, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-eventarc.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", diff --git a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_trigger_test.go b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_trigger_test.go index 1beaeb9b1df5..e60fea06e187 100644 --- a/mmv1/third_party/terraform/services/eventarc/resource_eventarc_trigger_test.go +++ b/mmv1/third_party/terraform/services/eventarc/resource_eventarc_trigger_test.go @@ -5,6 +5,11 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" + _ "github.com/hashicorp/terraform-provider-google/google/services/eventarc" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/workflows" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/filestore/data_source_filestore_instance_test.go b/mmv1/third_party/terraform/services/filestore/data_source_filestore_instance_test.go index 01d46734e230..432af18ae2b1 100644 --- a/mmv1/third_party/terraform/services/filestore/data_source_filestore_instance_test.go +++ b/mmv1/third_party/terraform/services/filestore/data_source_filestore_instance_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/filestore" ) func TestAccFilestoreInstanceDatasource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/filestore/resource_filestore_backup_test.go b/mmv1/third_party/terraform/services/filestore/resource_filestore_backup_test.go index ed3eee805a05..8803d0b296e6 100644 --- a/mmv1/third_party/terraform/services/filestore/resource_filestore_backup_test.go +++ b/mmv1/third_party/terraform/services/filestore/resource_filestore_backup_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/filestore" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/filestore/resource_filestore_instance_test.go b/mmv1/third_party/terraform/services/filestore/resource_filestore_instance_test.go index 19e1aa5bf0d1..26be264522e1 100644 --- a/mmv1/third_party/terraform/services/filestore/resource_filestore_instance_test.go +++ b/mmv1/third_party/terraform/services/filestore/resource_filestore_instance_test.go @@ -11,7 +11,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/filestore" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/filestore/resource_filestore_restore_test.go b/mmv1/third_party/terraform/services/filestore/resource_filestore_restore_test.go index cea0ee41a490..e15335f95ad8 100644 --- a/mmv1/third_party/terraform/services/filestore/resource_filestore_restore_test.go +++ b/mmv1/third_party/terraform/services/filestore/resource_filestore_restore_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + _ "github.com/hashicorp/terraform-provider-google/google/services/filestore" ) func TestAccFilestoreInstance_restore(t *testing.T) { @@ -90,7 +92,7 @@ func TestAccFilestoreInstance_restoreBackupDR(t *testing.T) { instanceID := fmt.Sprintf("tf-test-%d", acctest.RandInt(t)) backupVaultID := "tf-test-backup-vault-filestore" location := "us-central1" - backupVault := acctest.BootstrapBackupDRVault(t, backupVaultID, location) + backupVault := backupdr.BootstrapBackupDRVault(t, backupVaultID, location) providerFactories := acctest.ProtoV5ProviderFactories(t) acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_config_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_config_test.go.tmpl index 7280759962b9..164530881e0c 100644 --- a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_config_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_test.go.tmpl index 68bcc815d63e..9da914e960b1 100644 --- a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_android_app_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_config_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_config_test.go.tmpl index f94c796b6759..d41ed66fd85d 100644 --- a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_config_test.go.tmpl @@ -4,6 +4,7 @@ import ( "fmt" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_test.go.tmpl index a32c459e2ef4..f32cde588333 100644 --- a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_apple_app_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_config_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_config_test.go.tmpl index c9d4321134ec..0eadc5f81e05 100644 --- a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_config_test.go.tmpl @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_test.go.tmpl index 6ce7e58b0278..9b6e3092dff6 100644 --- a/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/data_source_google_firebase_web_app_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/firebase/resource_firebase_android_app_update_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/resource_firebase_android_app_update_test.go.tmpl index 34a17d2e91ea..875107cc09c3 100644 --- a/mmv1/third_party/terraform/services/firebase/resource_firebase_android_app_update_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/resource_firebase_android_app_update_test.go.tmpl @@ -4,6 +4,8 @@ package firebase_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" + _ "github.com/hashicorp/terraform-provider-google/google/services/apikeys" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebase/resource_firebase_apple_app_update_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/resource_firebase_apple_app_update_test.go.tmpl index 23af2fd581f2..7c9e258ae9ac 100644 --- a/mmv1/third_party/terraform/services/firebase/resource_firebase_apple_app_update_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/resource_firebase_apple_app_update_test.go.tmpl @@ -4,6 +4,8 @@ package firebase_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" + _ "github.com/hashicorp/terraform-provider-google/google/services/apikeys" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebase/resource_firebase_project_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/resource_firebase_project_test.go.tmpl index 295afa7968f3..d7faafa24976 100644 --- a/mmv1/third_party/terraform/services/firebase/resource_firebase_project_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/resource_firebase_project_test.go.tmpl @@ -4,6 +4,7 @@ package firebase_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebase/resource_firebase_web_app_test.go.tmpl b/mmv1/third_party/terraform/services/firebase/resource_firebase_web_app_test.go.tmpl index 8a932269376b..f88c39a2bebb 100644 --- a/mmv1/third_party/terraform/services/firebase/resource_firebase_web_app_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebase/resource_firebase_web_app_test.go.tmpl @@ -10,6 +10,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" + _ "github.com/hashicorp/terraform-provider-google/google/services/apikeys" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_config_test.go.tmpl b/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_config_test.go.tmpl index 14a4bdff4ad1..4aec4cae90a2 100644 --- a/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_config_test.go.tmpl @@ -13,6 +13,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/apikeys" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseailogic" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_prompt_template_test.go.tmpl b/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_prompt_template_test.go.tmpl index 901bf27ad15a..75ccc6c939b6 100644 --- a/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_prompt_template_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebaseailogic/resource_firebase_ai_logic_prompt_template_test.go.tmpl @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseailogic" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_debug_token_test.go.tmpl b/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_debug_token_test.go.tmpl index b2b09069c0eb..b9d1aa640e0b 100644 --- a/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_debug_token_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_debug_token_test.go.tmpl @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseappcheck" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_resource_policy_test.go b/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_resource_policy_test.go index 32d6b6014dbc..b9d47e30de9b 100644 --- a/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_resource_policy_test.go +++ b/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_resource_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseappcheck" ) func TestAccFirebaseAppCheckResourcePolicy_firebaseAppCheckResourcePolicyUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_service_config_test.go.tmpl b/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_service_config_test.go.tmpl index d893f5329877..e7bf29facd9e 100644 --- a/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_service_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebaseappcheck/resource_firebase_app_check_service_config_test.go.tmpl @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasedatabase" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseappcheck" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/firebaseapphosting/resource_firebase_app_hosting_backend_test.go b/mmv1/third_party/terraform/services/firebaseapphosting/resource_firebase_app_hosting_backend_test.go index e136ab74b50d..d4ebd390f175 100644 --- a/mmv1/third_party/terraform/services/firebaseapphosting/resource_firebase_app_hosting_backend_test.go +++ b/mmv1/third_party/terraform/services/firebaseapphosting/resource_firebase_app_hosting_backend_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseapphosting" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccFirebaseAppHostingBackend_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/firebasedatabase/resource_firebase_database_instance_test.go.tmpl b/mmv1/third_party/terraform/services/firebasedatabase/resource_firebase_database_instance_test.go.tmpl index 62c3c0fa1370..fbd997191ff7 100644 --- a/mmv1/third_party/terraform/services/firebasedatabase/resource_firebase_database_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebasedatabase/resource_firebase_database_instance_test.go.tmpl @@ -4,6 +4,7 @@ package firebasedatabase_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasedatabase" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebasedataconnect/resource_firebase_data_connect_service_test.go b/mmv1/third_party/terraform/services/firebasedataconnect/resource_firebase_data_connect_service_test.go index 04f9294a99c9..edcc69fdc80f 100644 --- a/mmv1/third_party/terraform/services/firebasedataconnect/resource_firebase_data_connect_service_test.go +++ b/mmv1/third_party/terraform/services/firebasedataconnect/resource_firebase_data_connect_service_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasedataconnect" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccFirebaseDataConnectService_Update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/firebaseextensions/resource_firebase_extensions_instance_test.go.tmpl b/mmv1/third_party/terraform/services/firebaseextensions/resource_firebase_extensions_instance_test.go.tmpl index 347765a7652b..4835246d68ac 100644 --- a/mmv1/third_party/terraform/services/firebaseextensions/resource_firebase_extensions_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebaseextensions/resource_firebase_extensions_instance_test.go.tmpl @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseextensions" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/firebasehosting/data_source_google_firebase_hosting_channel_test.go.tmpl b/mmv1/third_party/terraform/services/firebasehosting/data_source_google_firebase_hosting_channel_test.go.tmpl index a986ca15bc8e..eade7656418e 100644 --- a/mmv1/third_party/terraform/services/firebasehosting/data_source_google_firebase_hosting_channel_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebasehosting/data_source_google_firebase_hosting_channel_test.go.tmpl @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasehosting" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_channel_test.go.tmpl b/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_channel_test.go.tmpl index f0d7719035cf..66b1f32e3e00 100644 --- a/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_channel_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_channel_test.go.tmpl @@ -4,6 +4,7 @@ package firebasehosting_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasehosting" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_custom_domain_test.go.tmpl b/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_custom_domain_test.go.tmpl index 1d101ece7d89..db051685cb06 100644 --- a/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_custom_domain_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_custom_domain_test.go.tmpl @@ -4,6 +4,7 @@ package firebasehosting_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasehosting" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_site_test.go.tmpl b/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_site_test.go.tmpl index 87c2d3316650..5152cb81e710 100644 --- a/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_site_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebasehosting/resource_firebase_hosting_site_test.go.tmpl @@ -4,6 +4,8 @@ package firebasehosting_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebase" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasehosting" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firebaseremoteconfig/resource_firebase_remote_config_remote_config_test.go b/mmv1/third_party/terraform/services/firebaseremoteconfig/resource_firebase_remote_config_remote_config_test.go index f32e37f897ee..d3d3ada52811 100644 --- a/mmv1/third_party/terraform/services/firebaseremoteconfig/resource_firebase_remote_config_remote_config_test.go +++ b/mmv1/third_party/terraform/services/firebaseremoteconfig/resource_firebase_remote_config_remote_config_test.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebaseremoteconfig" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release.go b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release.go index 2da190a1def1..eafcb089767d 100644 --- a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release.go +++ b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release.go @@ -20,6 +20,7 @@ func ResourceFirebaserulesRelease() *schema.Resource { return &schema.Resource{ Create: resourceFirebaserulesReleaseCreate, Read: resourceFirebaserulesReleaseRead, + Update: resourceFirebaserulesReleaseUpdate, Delete: resourceFirebaserulesReleaseDelete, Importer: &schema.ResourceImporter{ @@ -32,6 +33,7 @@ func ResourceFirebaserulesRelease() *schema.Resource { }, CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -76,6 +78,9 @@ func ResourceFirebaserulesRelease() *schema.Resource { Computed: true, Description: "Output only. Time the release was updated.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -184,10 +189,29 @@ func resourceFirebaserulesReleaseRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error setting update_time in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceFirebaserulesReleaseUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceFirebaserulesReleaseRead(d, meta) +} + +//UDP update end + func resourceFirebaserulesReleaseDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_generated_test.go.tmpl b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_generated_test.go.tmpl index b392feaaf5d2..165f218e8a55 100644 --- a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_generated_test.go.tmpl +++ b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_generated_test.go.tmpl @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/firebasestorage" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/firebaserules" dcl "github.com/hashicorp/terraform-provider-google/google/tpgdclresource" diff --git a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_meta.yaml b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_meta.yaml index 5caf910a758c..bef01cb66c6f 100644 --- a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_meta.yaml +++ b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_release_meta.yaml @@ -10,3 +10,5 @@ fields: - field: 'project' - api_field: 'rulesetName' - api_field: 'updateTime' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset.go b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset.go index 2059d81bca50..b60d01987ff2 100644 --- a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset.go +++ b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset.go @@ -20,6 +20,7 @@ func ResourceFirebaserulesRuleset() *schema.Resource { return &schema.Resource{ Create: resourceFirebaserulesRulesetCreate, Read: resourceFirebaserulesRulesetRead, + Update: resourceFirebaserulesRulesetUpdate, Delete: resourceFirebaserulesRulesetDelete, Importer: &schema.ResourceImporter{ @@ -32,6 +33,7 @@ func ResourceFirebaserulesRuleset() *schema.Resource { }, CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -71,6 +73,9 @@ func ResourceFirebaserulesRuleset() *schema.Resource { Computed: true, Description: "Output only. Name of the `Ruleset`. The ruleset_id is auto generated by the service. Format: `projects/{project_id}/rulesets/{ruleset_id}`", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -247,10 +252,29 @@ func resourceFirebaserulesRulesetRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error setting name in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceFirebaserulesRulesetUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceFirebaserulesRulesetRead(d, meta) +} + +//UDP update end + func resourceFirebaserulesRulesetDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset_meta.yaml b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset_meta.yaml index 32dfa7a247b7..45bc3811176c 100644 --- a/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset_meta.yaml +++ b/mmv1/third_party/terraform/services/firebaserules/resource_firebaserules_ruleset_meta.yaml @@ -12,3 +12,5 @@ fields: - api_field: 'source.files.fingerprint' - api_field: 'source.files.name' - api_field: 'source.language' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/firestore/data_source_google_firestore_document_test.go b/mmv1/third_party/terraform/services/firestore/data_source_google_firestore_document_test.go index 5c7d40638477..e29bd3f35c08 100644 --- a/mmv1/third_party/terraform/services/firestore/data_source_google_firestore_document_test.go +++ b/mmv1/third_party/terraform/services/firestore/data_source_google_firestore_document_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firestore" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDatasourceFirestoreDocument_simple(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/firestore/resource_firestore_database_test.go b/mmv1/third_party/terraform/services/firestore/resource_firestore_database_test.go index d95406e36775..43142f77b15e 100644 --- a/mmv1/third_party/terraform/services/firestore/resource_firestore_database_test.go +++ b/mmv1/third_party/terraform/services/firestore/resource_firestore_database_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firestore" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) diff --git a/mmv1/third_party/terraform/services/firestore/resource_firestore_database_update_test.go b/mmv1/third_party/terraform/services/firestore/resource_firestore_database_update_test.go index 596a4ccb48ed..30365584102f 100644 --- a/mmv1/third_party/terraform/services/firestore/resource_firestore_database_update_test.go +++ b/mmv1/third_party/terraform/services/firestore/resource_firestore_database_update_test.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firestore" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/firestore/resource_firestore_document_test.go b/mmv1/third_party/terraform/services/firestore/resource_firestore_document_test.go index e4d3914f984c..462e56d62fac 100644 --- a/mmv1/third_party/terraform/services/firestore/resource_firestore_document_test.go +++ b/mmv1/third_party/terraform/services/firestore/resource_firestore_document_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firestore" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccFirestoreDocument_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/firestore/resource_firestore_field_test.go b/mmv1/third_party/terraform/services/firestore/resource_firestore_field_test.go index 7543ea0043aa..d49c94ef66c3 100644 --- a/mmv1/third_party/terraform/services/firestore/resource_firestore_field_test.go +++ b/mmv1/third_party/terraform/services/firestore/resource_firestore_field_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/firestore" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccFirestoreField_firestoreFieldUpdateAddIndexExample(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/iam_gemini_repository_group_test.go b/mmv1/third_party/terraform/services/gemini/iam_gemini_repository_group_test.go index 40e8ad93b89d..1478ad55a293 100644 --- a/mmv1/third_party/terraform/services/gemini/iam_gemini_repository_group_test.go +++ b/mmv1/third_party/terraform/services/gemini/iam_gemini_repository_group_test.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/developerconnect" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_code_repository_index_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_code_repository_index_test.go index ed0f8f87a795..0e12bbd9c67c 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_code_repository_index_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_code_repository_index_test.go @@ -8,10 +8,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/developerconnect" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccGeminiCodeRepositoryIndex_update(t *testing.T) { - bootstrappedKMS := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + bootstrappedKMS := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "project_id": os.Getenv("GOOGLE_PROJECT"), @@ -49,7 +52,7 @@ func TestAccGeminiCodeRepositoryIndex_update(t *testing.T) { // will be force-removed upon CRI deletion, because the CRI provider uses --force option by default // The plan after the _delete function should not be empty due to the child resource in plan func TestAccGeminiCodeRepositoryIndex_delete(t *testing.T) { - bootstrappedKMS := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + bootstrappedKMS := kms.BootstrapKMSKeyInLocation(t, "us-central1") randomSuffix := acctest.RandString(t, 10) context := map[string]interface{}{ "random_suffix": randomSuffix, diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_binding_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_binding_test.go index f9d053b35866..28e5c0114b22 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_binding_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_binding_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiCodeToolsSettingBinding_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_test.go index 5743e8d565b6..79e80397b7e1 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_code_tools_setting_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiCodeToolsSetting_geminiCodeToolsSettingBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_binding_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_binding_test.go index ad2de07295e2..d3e4c792002e 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_binding_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_binding_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiDataSharingWithGoogleSettingBinding_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_test.go index 6c13c4f1b57d..587b57da0b42 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_data_sharing_with_google_setting_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiDataSharingWithGoogleSetting_geminiDataSharingWithGoogleSettingBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_binding_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_binding_test.go index a69ef8ff388f..2e545094178d 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_binding_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_binding_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiGeminiGcpEnablementSettingBinding_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_test.go index 93eb4a8f5afe..0d73952bb116 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_gemini_gcp_enablement_setting_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiGeminiGcpEnablementSetting_geminiGeminiGcpEnablementSettingBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_binding_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_binding_test.go index dd0368926e09..9b7c08f1062b 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_binding_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_binding_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiLoggingSettingBinding_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_test.go index 6423dc8166ff..7cced022881e 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_logging_setting_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiLoggingSetting_geminiLoggingSettingBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_binding_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_binding_test.go index 8012ed347746..2794b92d40ac 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_binding_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_binding_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiReleaseChannelSettingBinding_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_test.go index 893a8b71920a..c45f88e8e302 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_release_channel_setting_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gemini" ) func TestAccGeminiReleaseChannelSetting_geminiReleaseChannelSettingBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gemini/resource_gemini_repository_group_test.go b/mmv1/third_party/terraform/services/gemini/resource_gemini_repository_group_test.go index 69d86cf59a7b..a56b121847a4 100644 --- a/mmv1/third_party/terraform/services/gemini/resource_gemini_repository_group_test.go +++ b/mmv1/third_party/terraform/services/gemini/resource_gemini_repository_group_test.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/developerconnect" "github.com/hashicorp/terraform-provider-google/google/services/gemini" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_channel_test.go b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_channel_test.go index 24d6a4f44a66..6ed22fb6264b 100644 --- a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_channel_test.go +++ b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_channel_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkebackup" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_plan_test.go b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_plan_test.go index 658e79ce5b0b..536137fbcda7 100644 --- a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_plan_test.go +++ b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_backup_plan_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkebackup" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) @@ -15,8 +18,8 @@ func TestAccGKEBackupBackupPlan_update(t *testing.T) { context := map[string]interface{}{ "project": envvar.GetTestProjectFromEnv(), "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedTestNetwork(t, "gke-cluster"), - "subnetwork_name": acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster")), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster"), + "subnetwork_name": tpgcompute.BootstrapSubnet(t, "gke-cluster", tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster")), } acctest.VcrTest(t, resource.TestCase{ @@ -171,7 +174,7 @@ resource "google_container_cluster" "primary" { network = "%{network_name}" subnetwork = "%{subnetwork_name}" } - + resource "google_gke_backup_backup_plan" "backupplan" { name = "tf-test-testplan%{random_suffix}" cluster = google_container_cluster.primary.id @@ -222,7 +225,7 @@ resource "google_container_cluster" "primary" { network = "%{network_name}" subnetwork = "%{subnetwork_name}" } - + resource "google_gke_backup_backup_plan" "backupplan" { name = "tf-test-testplan%{random_suffix}" cluster = google_container_cluster.primary.id @@ -296,7 +299,7 @@ resource "google_container_cluster" "primary" { network = "%{network_name}" subnetwork = "%{subnetwork_name}" } - + resource "google_gke_backup_backup_plan" "backupplan" { name = "tf-test-testplan%{random_suffix}" cluster = google_container_cluster.primary.id diff --git a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_channel_test.go b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_channel_test.go index 029f7b0ed26f..bd30ec60ff7c 100644 --- a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_channel_test.go +++ b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_channel_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkebackup" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_plan_test.go b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_plan_test.go index 04c53ad5f927..2962a8bcfcaf 100644 --- a/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_plan_test.go +++ b/mmv1/third_party/terraform/services/gkebackup/resource_gke_backup_restore_plan_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkebackup" ) func TestAccGKEBackupRestorePlan_update(t *testing.T) { @@ -14,8 +17,8 @@ func TestAccGKEBackupRestorePlan_update(t *testing.T) { context := map[string]interface{}{ "project": envvar.GetTestProjectFromEnv(), "deletion_protection": false, - "network_name": acctest.BootstrapSharedTestNetwork(t, "gke-cluster"), - "subnetwork_name": acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster")), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster"), + "subnetwork_name": tpgcompute.BootstrapSubnet(t, "gke-cluster", tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/gkehub/data_source_google_gke_hub_membership_test.go b/mmv1/third_party/terraform/services/gkehub/data_source_google_gke_hub_membership_test.go index 9dac0b1556df..980789b0913d 100644 --- a/mmv1/third_party/terraform/services/gkehub/data_source_google_gke_hub_membership_test.go +++ b/mmv1/third_party/terraform/services/gkehub/data_source_google_gke_hub_membership_test.go @@ -9,6 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + "github.com/hashicorp/terraform-provider-google/google/services/gkehub" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -116,7 +120,7 @@ func testAccCheckGoogleGkeHubMembershipDestroyProducer(t *testing.T) func(s *ter } config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{GKEHub2BasePath}}projects/{{project}}/locations/{{location}}/memberships/{{membership_id}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(gkehub.Product, config)+"projects/{{project}}/locations/{{location}}/memberships/{{membership_id}}") if err != nil { return fmt.Errorf("Error constructing URL for GKE Hub Membership: %s", err) } diff --git a/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership.go.tmpl b/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership.go.tmpl index b551a9291458..dcda4a312283 100644 --- a/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership.go.tmpl +++ b/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership.go.tmpl @@ -100,6 +100,9 @@ func ResourceGkeHubFeatureMembership() *schema.Resource { DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, Description: "The project of the feature", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -895,10 +898,20 @@ func resourceGkeHubFeatureMembershipRead(d *schema.ResourceData, meta interface{ if err = d.Set("project", res.Project); err != nil { return fmt.Errorf("error setting project in state: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceGkeHubFeatureMembershipUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGkeHubFeatureMembership) { + return ResourceGkeHubFeatureMembership().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -956,6 +969,13 @@ func resourceGkeHubFeatureMembershipUpdate(d *schema.ResourceData, meta interfac } func resourceGkeHubFeatureMembershipDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_meta.yaml.tmpl b/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_meta.yaml.tmpl index 834d4d26de9d..713ff0903129 100644 --- a/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_meta.yaml.tmpl @@ -76,3 +76,5 @@ fields: - field: 'policycontroller.policy_controller_hub_config.referential_rules_enabled' - field: 'policycontroller.version' - field: 'project' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_test.go.tmpl b/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_test.go.tmpl index 3bbc24a27af3..4fd6da28f6e9 100644 --- a/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_test.go.tmpl +++ b/mmv1/third_party/terraform/services/gkehub/resource_gke_hub_feature_membership_test.go.tmpl @@ -10,6 +10,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/gkehub" dcl "github.com/hashicorp/terraform-provider-google/google/tpgdclresource" diff --git a/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_feature_test.go b/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_feature_test.go index f076d64bb66d..5195b9126ba1 100644 --- a/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_feature_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_feature_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -69,7 +70,7 @@ func testAccCheckGoogleGkeHubFeatureDestroyProducer(t *testing.T) func(s *terraf config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{GKEHub2BasePath}}projects/{{project}}/locations/{{location}}/features/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(gkehub2.Product, config)+"projects/{{project}}/locations/{{location}}/features/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_membership_binding_test.go b/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_membership_binding_test.go index bab681b0d568..0032a4b16203 100644 --- a/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_membership_binding_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/data_source_google_gke_hub_membership_binding_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" ) func TestAccDataSourceGoogleGKEHub2MembershipBinding_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkehub2/iam_gke_hub_feature_test.go b/mmv1/third_party/terraform/services/gkehub2/iam_gke_hub_feature_test.go index c9133ec25c35..dbc06f87b12f 100644 --- a/mmv1/third_party/terraform/services/gkehub2/iam_gke_hub_feature_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/iam_gke_hub_feature_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccGKEHub2FeatureIamBindingGenerated(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_feature_test.go b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_feature_test.go index f04b037d39f8..52fb0cbbc44c 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_feature_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_feature_test.go @@ -10,6 +10,11 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub" + "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -1183,7 +1188,7 @@ func testAccCheckGKEHubFeatureDestroyProducer(t *testing.T) func(s *terraform.St config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{GKEHub2BasePath}}projects/{{project}}/locations/{{location}}/features/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(gkehub2.Product, config)+"projects/{{project}}/locations/{{location}}/features/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_fleet_test.go.tmpl b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_fleet_test.go.tmpl index 8127202e4e94..161481a9cfde 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_fleet_test.go.tmpl +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_fleet_test.go.tmpl @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_membership_binding_test.go b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_membership_binding_test.go index 9f8b0530e171..f8f0987308bb 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_membership_binding_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_membership_binding_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/container" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" ) func TestAccGKEHub2MembershipBinding_gkehubMembershipBindingBasicExample_update(t *testing.T) { @@ -18,8 +22,8 @@ func TestAccGKEHub2MembershipBinding_gkehubMembershipBindingBasicExample_update( "project": envvar.GetTestProjectFromEnv(), "location": envvar.GetTestRegionFromEnv(), "random_suffix": acctest.RandString(t, 10), - "network_name": acctest.BootstrapSharedTestNetwork(t, "gke-cluster"), - "subnetwork_name": acctest.BootstrapSubnet(t, "gke-cluster", acctest.BootstrapSharedTestNetwork(t, "gke-cluster")), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster"), + "subnetwork_name": tpgcompute.BootstrapSubnet(t, "gke-cluster", tpgcompute.BootstrapSharedTestNetwork(t, "gke-cluster")), } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_namespace_test.go b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_namespace_test.go index de68903b9c35..6e101435130a 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_namespace_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_namespace_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" ) func TestAccGKEHub2Namespace_gkehubNamespaceBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_rollout_sequence_test.go.tmpl b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_rollout_sequence_test.go.tmpl index 749b07b6fd24..a070e3895a9a 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_rollout_sequence_test.go.tmpl +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_rollout_sequence_test.go.tmpl @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_rbac_role_binding_test.go b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_rbac_role_binding_test.go index ae358d84ebb7..a86eac3649ff 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_rbac_role_binding_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_rbac_role_binding_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccGKEHub2ScopeRBACRoleBinding_gkehubScopeRbacRoleBindingBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_test.go b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_test.go index cbae79fb4950..630e6ba813fc 100644 --- a/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_test.go +++ b/mmv1/third_party/terraform/services/gkehub2/resource_gke_hub_scope_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkehub2" ) func TestAccGKEHub2Scope_gkehubScopeBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_admin_cluster_test.go b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_admin_cluster_test.go index 94cdaaecc1df..65d90bf6a0a1 100644 --- a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_admin_cluster_test.go +++ b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_admin_cluster_test.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkeonprem" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_cluster_test.go b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_cluster_test.go index 692a58875fd1..3c79763fd994 100644 --- a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_cluster_test.go +++ b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_cluster_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkeonprem" ) func TestAccGkeonpremBareMetalCluster_bareMetalClusterUpdateBasic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_node_pool_test.go b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_node_pool_test.go index e0e430b79f3a..bf41436db068 100644 --- a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_node_pool_test.go +++ b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_bare_metal_node_pool_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkeonprem" ) func TestAccGkeonpremBareMetalNodePool_bareMetalNodePoolUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_cluster_test.go b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_cluster_test.go index 4f495496da86..3abe705b7fe5 100644 --- a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_cluster_test.go +++ b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_cluster_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkeonprem" ) func TestAccGkeonpremVmwareCluster_vmwareClusterUpdateBasic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_node_pool_test.go b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_node_pool_test.go index d06f0820df29..28d0213f09dc 100644 --- a/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_node_pool_test.go +++ b/mmv1/third_party/terraform/services/gkeonprem/resource_gkeonprem_vmware_node_pool_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/gkeonprem" ) func TestAccGkeonpremVmwareNodePool_vmwareNodePoolUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dataset_test.go b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dataset_test.go index 1eda1c86b4f5..e06591cd1dff 100644 --- a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dataset_test.go +++ b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dataset_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dicom_store_test.go b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dicom_store_test.go index 1e855721772c..5b2103a15d17 100644 --- a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dicom_store_test.go +++ b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_dicom_store_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_fhir_store_test.go b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_fhir_store_test.go index 261d432d7519..ce12ac11b2f2 100644 --- a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_fhir_store_test.go +++ b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_fhir_store_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_hl7_v2_store_test.go b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_hl7_v2_store_test.go index 8afd1737c8e1..4f77ede70d3e 100644 --- a/mmv1/third_party/terraform/services/healthcare/iam_healthcare_hl7_v2_store_test.go +++ b/mmv1/third_party/terraform/services/healthcare/iam_healthcare_hl7_v2_store_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_dicom_store_test.go b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_dicom_store_test.go index be971784c355..4821d7688c53 100644 --- a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_dicom_store_test.go +++ b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_dicom_store_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_fhir_store_test.go.tmpl b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_fhir_store_test.go.tmpl index 50892c496179..50ebbe6c081b 100644 --- a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_fhir_store_test.go.tmpl +++ b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_fhir_store_test.go.tmpl @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_hl7_v2_store_test.go.tmpl b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_hl7_v2_store_test.go.tmpl index ed8e5d3cf796..0b80b37289dd 100644 --- a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_hl7_v2_store_test.go.tmpl +++ b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_hl7_v2_store_test.go.tmpl @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" "github.com/hashicorp/terraform-provider-google/google/services/healthcare" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_workspace_test.go b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_workspace_test.go index 1e7f8e11b105..d544610a2b85 100644 --- a/mmv1/third_party/terraform/services/healthcare/resource_healthcare_workspace_test.go +++ b/mmv1/third_party/terraform/services/healthcare/resource_healthcare_workspace_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/healthcare" ) func TestAccHealthcareWorkspace_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/hypercomputecluster/resource_hypercomputecluster_cluster_test.go b/mmv1/third_party/terraform/services/hypercomputecluster/resource_hypercomputecluster_cluster_test.go index 6c823575aa08..063924b7e51c 100644 --- a/mmv1/third_party/terraform/services/hypercomputecluster/resource_hypercomputecluster_cluster_test.go +++ b/mmv1/third_party/terraform/services/hypercomputecluster/resource_hypercomputecluster_cluster_test.go @@ -7,6 +7,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/filestore" + _ "github.com/hashicorp/terraform-provider-google/google/services/hypercomputecluster" + _ "github.com/hashicorp/terraform-provider-google/google/services/lustre" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccHypercomputeclusterCluster_update(t *testing.T) { @@ -513,6 +519,7 @@ resource "google_hypercomputecluster_cluster" "cluster" { bucket = "bucket-new-2-%{random_suffix}" autoclass { enabled = true + terminal_storage_class = "NEARLINE" } hierarchical_namespace { enabled = false @@ -543,6 +550,7 @@ resource "google_hypercomputecluster_cluster" "cluster" { description = "Lustre instance created via Terraform" filesystem = "lustrefs" lustre = "projects/${local.project_id}/locations/us-central1-a/instances/lustre-%{random_suffix}" + per_unit_storage_throughput = "1000" } } } diff --git a/mmv1/third_party/terraform/services/iam2/resource_iam_access_boundary_policy_test.go b/mmv1/third_party/terraform/services/iam2/resource_iam_access_boundary_policy_test.go index 916dbf0ca439..6b85cbc7e02b 100644 --- a/mmv1/third_party/terraform/services/iam2/resource_iam_access_boundary_policy_test.go +++ b/mmv1/third_party/terraform/services/iam2/resource_iam_access_boundary_policy_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/accesscontextmanager" + "github.com/hashicorp/terraform-provider-google/google/services/iam2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -189,7 +192,7 @@ func testAccCheckIAM2AccessBoundaryPolicyDestroyProducer(t *testing.T) func(s *t config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{IAM2BasePath}}policies/{{parent}}/accessboundarypolicies/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(iam2.Product, config)+"policies/{{parent}}/accessboundarypolicies/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/iam2/resource_iam_deny_policy_test.go b/mmv1/third_party/terraform/services/iam2/resource_iam_deny_policy_test.go index 3725784c4660..7f051f47a280 100644 --- a/mmv1/third_party/terraform/services/iam2/resource_iam_deny_policy_test.go +++ b/mmv1/third_party/terraform/services/iam2/resource_iam_deny_policy_test.go @@ -3,6 +3,8 @@ package iam2_test import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iam2" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "testing" diff --git a/mmv1/third_party/terraform/services/iam3/resource_iam_folders_policy_binding_test.go b/mmv1/third_party/terraform/services/iam3/resource_iam_folders_policy_binding_test.go index 7e4373a4b156..c9ae4e1ea514 100644 --- a/mmv1/third_party/terraform/services/iam3/resource_iam_folders_policy_binding_test.go +++ b/mmv1/third_party/terraform/services/iam3/resource_iam_folders_policy_binding_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iam3" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccIAM3FoldersPolicyBinding_iamFoldersPolicyBindingExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iam3/resource_iam_organizations_policy_binding_test.go b/mmv1/third_party/terraform/services/iam3/resource_iam_organizations_policy_binding_test.go index 6eccb406b3f4..5beedae8d0c7 100644 --- a/mmv1/third_party/terraform/services/iam3/resource_iam_organizations_policy_binding_test.go +++ b/mmv1/third_party/terraform/services/iam3/resource_iam_organizations_policy_binding_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iam3" ) func TestAccIAM3OrganizationsPolicyBinding_iam3OrganizationsPolicyBindingExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iam3/resource_iam_principal_access_boundary_policy_test.go b/mmv1/third_party/terraform/services/iam3/resource_iam_principal_access_boundary_policy_test.go index 8aa95953b7a3..7691f9dd130f 100644 --- a/mmv1/third_party/terraform/services/iam3/resource_iam_principal_access_boundary_policy_test.go +++ b/mmv1/third_party/terraform/services/iam3/resource_iam_principal_access_boundary_policy_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iam3" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccIAM3PrincipalAccessBoundaryPolicy_iam3PrincipalAccessBoundaryPolicyExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iam3/resource_iam_projects_policy_binding_test.go b/mmv1/third_party/terraform/services/iam3/resource_iam_projects_policy_binding_test.go index 3e2ade2da282..a8f044943699 100644 --- a/mmv1/third_party/terraform/services/iam3/resource_iam_projects_policy_binding_test.go +++ b/mmv1/third_party/terraform/services/iam3/resource_iam_projects_policy_binding_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iam3" ) func TestAccIAM3ProjectsPolicyBinding_iamProjectsPolicyBindingExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iambeta/bootstrap_test_utils.go b/mmv1/third_party/terraform/services/iambeta/bootstrap_test_utils.go new file mode 100644 index 000000000000..0564f25ccd83 --- /dev/null +++ b/mmv1/third_party/terraform/services/iambeta/bootstrap_test_utils.go @@ -0,0 +1,100 @@ +package iambeta + +import ( + "fmt" + "log" + "testing" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + iam "google.golang.org/api/iam/v1" +) + +var ServiceAccountPrefix = "tf-bootstrap-sa-" +var serviceAccountDisplay = "Bootstrapped Service Account for Terraform tests" + +// Some tests need a second service account, other than the test runner, to assert functionality on. +// This provides a well-known service account that can be used when dynamically creating a service +// account isn't an option. +func GetOrCreateServiceAccount(config *transport_tpg.Config, project, serviceAccountEmail string) (*iam.ServiceAccount, error) { + name := fmt.Sprintf("projects/%s/serviceAccounts/%s@%s.iam.gserviceaccount.com", project, serviceAccountEmail, project) + log.Printf("[DEBUG] Verifying %s as bootstrapped service account.\n", name) + + sa, err := NewClient(config, config.UserAgent).Projects.ServiceAccounts.Get(name).Do() + if err != nil && !transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + return nil, fmt.Errorf("encountered a non-404 error when looking for bootstrapped service account %s: %w", name, err) + } + + if sa == nil { + log.Printf("[DEBUG] Account missing. Creating %s as bootstrapped service account.\n", name) + sa = &iam.ServiceAccount{ + DisplayName: serviceAccountDisplay, + } + + r := &iam.CreateServiceAccountRequest{ + AccountId: serviceAccountEmail, + ServiceAccount: sa, + } + sa, err = NewClient(config, config.UserAgent).Projects.ServiceAccounts.Create("projects/"+project, r).Do() + if err != nil { + return nil, fmt.Errorf("error when creating bootstrapped service account %s: %w", name, err) + } + } + + return sa, nil +} + +// In order to test impersonation we need to grant the testRunner's account the ability to grant tokens +// on a different service account. Granting permissions takes time and there is no operation to wait on +// so instead this creates a single service account once per test-suite with the correct permissions. +// The first time this test is run it will fail, but subsequent runs will succeed. +func impersonationServiceAccountPermissions(config *transport_tpg.Config, sa *iam.ServiceAccount, testRunner string) error { + log.Printf("[DEBUG] Setting service account permissions.\n") + policy := iam.Policy{ + Bindings: []*iam.Binding{}, + } + + binding := &iam.Binding{ + Role: "roles/iam.serviceAccountTokenCreator", + Members: []string{"serviceAccount:" + sa.Email, "serviceAccount:" + testRunner}, + } + policy.Bindings = append(policy.Bindings, binding) + + // Overwrite the roles each time on this service account. This is because this account is + // only created for the test suite and will stop snowflaking of permissions to get tests + // to run. Overwriting permissions on 1 service account shouldn't affect others. + _, err := NewClient(config, config.UserAgent).Projects.ServiceAccounts.SetIamPolicy(sa.Name, &iam.SetIamPolicyRequest{ + Policy: &policy, + }).Do() + if err != nil { + return err + } + + return nil +} + +// A separate testId should be used for each test, to create separate service accounts for each, +// and avoid race conditions where the policy of the same service account is being modified by 2 +// tests at once. This is needed as long as the function overwrites the policy on every run. +func BootstrapServiceAccount(t *testing.T, testId, testRunner string) string { + project := envvar.GetTestProjectFromEnv() + serviceAccountEmail := ServiceAccountPrefix + testId + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + sa, err := GetOrCreateServiceAccount(config, project, serviceAccountEmail) + if err != nil { + t.Fatalf("Bootstrapping failed. Cannot retrieve service account, %s", err) + } + + err = impersonationServiceAccountPermissions(config, sa, testRunner) + if err != nil { + t.Fatalf("Bootstrapping failed. Cannot set service account permissions, %s", err) + } + + return sa.Email +} diff --git a/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_provider_test.go b/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_provider_test.go index 83c712a330cc..0869e5901d5c 100644 --- a/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_provider_test.go +++ b/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_provider_test.go @@ -2,6 +2,7 @@ package iambeta_test import ( "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_test.go b/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_test.go index 0a303d908299..1fee3692dadf 100644 --- a/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_test.go +++ b/mmv1/third_party/terraform/services/iambeta/data_source_iam_workload_identity_pool_test.go @@ -2,6 +2,7 @@ package iambeta_test import ( "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_managed_identity_test.go b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_managed_identity_test.go index dd12b564236f..79e7a595f17c 100644 --- a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_managed_identity_test.go +++ b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_managed_identity_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" ) func TestAccIAMBetaWorkloadIdentityPoolManagedIdentity_minimal(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_namespace_test.go b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_namespace_test.go index 2d001be58f06..a0592704a71d 100644 --- a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_namespace_test.go +++ b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_namespace_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" ) func TestAccIAMBetaWorkloadIdentityPoolNamespace_minimal(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_provider_test.go b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_provider_test.go index 5c0f2134a4cc..9835fbb4fe65 100644 --- a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_provider_test.go +++ b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_provider_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_test.go b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_test.go index 6f1f9ea33592..14dba0b6a353 100644 --- a/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_test.go +++ b/mmv1/third_party/terraform/services/iambeta/resource_iam_workload_identity_pool_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/envvar" diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_credential_test.go b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_credential_test.go index 82167e5a58de..14ce0b8d1e41 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_credential_test.go +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_credential_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" ) func TestAccIAMWorkforcePoolOauthClientCredential_full(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_test.go b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_test.go index 506fadd3c7ec..6bd433025bc3 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_test.go +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_oauth_client_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" ) func TestAccIAMWorkforcePoolOauthClient_full(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_key_test.go b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_key_test.go index a9d23a2d1c1f..7dd97ba6ade3 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_key_test.go +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_key_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" ) func TestAccIAMWorkforcePoolWorkforcePoolProviderKey_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_tenant_test.go b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_tenant_test.go index beef673726d9..cb8daf3a50aa 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_tenant_test.go +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_tenant_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" ) func TestAccIAMWorkforcePoolWorkforcePoolProviderScimTenant_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_token_test.go b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_token_test.go index fb2283d32689..a2359f639e51 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_token_test.go +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_scim_token_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" ) func TestAccIAMWorkforcePoolWorkforcePoolProviderScimToken_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_test.go.tmpl b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_test.go.tmpl index 1048001fe8ab..4f979f75f4fd 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_test.go.tmpl +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_provider_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_test.go b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_test.go index 91c6c5211e3d..a6516529e1f5 100644 --- a/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_test.go +++ b/mmv1/third_party/terraform/services/iamworkforcepool/resource_iam_workforce_pool_test.go @@ -4,6 +4,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iamworkforcepool" "testing" ) diff --git a/mmv1/third_party/terraform/services/iap/resource_iap_brand_test.go b/mmv1/third_party/terraform/services/iap/resource_iap_brand_test.go index a9fc2d73eea1..b5e837b7effc 100644 --- a/mmv1/third_party/terraform/services/iap/resource_iap_brand_test.go +++ b/mmv1/third_party/terraform/services/iap/resource_iap_brand_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/iap" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccIapBrand_iapBrandExample(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iap/resource_iap_settings_test.go b/mmv1/third_party/terraform/services/iap/resource_iap_settings_test.go index 22c7852082f9..83f48d35558f 100644 --- a/mmv1/third_party/terraform/services/iap/resource_iap_settings_test.go +++ b/mmv1/third_party/terraform/services/iap/resource_iap_settings_test.go @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/iap" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccIapSettings_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/iap/resource_iap_tunnel_dest_group_test.go b/mmv1/third_party/terraform/services/iap/resource_iap_tunnel_dest_group_test.go index 33cc4c2974cc..74f3839d240c 100644 --- a/mmv1/third_party/terraform/services/iap/resource_iap_tunnel_dest_group_test.go +++ b/mmv1/third_party/terraform/services/iap/resource_iap_tunnel_dest_group_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/iap" ) func TestAccIapTunnelDestGroup_updates(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_config_test.go index 2f48709a64ad..f56d7f365df9 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_config_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccIdentityPlatformConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_default_supported_idp_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_default_supported_idp_config_test.go index d6ed2ec75cfd..9663ed7da8b8 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_default_supported_idp_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_default_supported_idp_config_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -57,7 +58,7 @@ func testAccCheckIdentityPlatformDefaultSupportedIdpConfigDestroyProducer(t *tes config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{IdentityPlatformBasePath}}projects/{{project}}/defaultSupportedIdpConfigs/{{client_id}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(identityplatform.Product, config)+"projects/{{project}}/defaultSupportedIdpConfigs/{{client_id}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_inbound_saml_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_inbound_saml_config_test.go index 289d7e618f1c..b76eea47ae48 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_inbound_saml_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_inbound_saml_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" ) func TestAccIdentityPlatformInboundSamlConfig_inboundSamlConfigUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_oauth_idp_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_oauth_idp_config_test.go index de9b0982bd98..a41eb726e6f0 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_oauth_idp_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_oauth_idp_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" ) func TestAccIdentityPlatformOauthIdpConfig_identityPlatformOauthIdpConfigUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_default_supported_idp_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_default_supported_idp_config_test.go index bf00aea5e8f4..c4db337e205a 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_default_supported_idp_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_default_supported_idp_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" ) func TestAccIdentityPlatformTenantDefaultSupportedIdpConfig_identityPlatformTenantDefaultSupportedIdpConfigUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_inbound_saml_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_inbound_saml_config_test.go index df0f1ba763c1..cc9d19518a85 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_inbound_saml_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_inbound_saml_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" ) func TestAccIdentityPlatformTenantInboundSamlConfig_identityPlatformTenantInboundSamlConfigUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_oauth_idp_config_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_oauth_idp_config_test.go index d47ec29578bf..4d4d9a90696b 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_oauth_idp_config_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_oauth_idp_config_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" ) func TestAccIdentityPlatformTenantOauthIdpConfig_identityPlatformTenantOauthIdpConfigUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_test.go b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_test.go index 5f50be573367..ec4cee6635eb 100644 --- a/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_test.go +++ b/mmv1/third_party/terraform/services/identityplatform/resource_identity_platform_tenant_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/identityplatform" ) func TestAccIdentityPlatformTenant_identityPlatformTenantUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_connection_test.go b/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_connection_test.go index a52fa7aaa50e..9ff513eccbbe 100644 --- a/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_connection_test.go +++ b/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_connection_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/integrationconnectors" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -1444,7 +1446,7 @@ func testAccCheckIntegrationConnectorsConnectionDestroyProducer(t *testing.T) fu config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{IntegrationConnectorsBasePath}}projects/{{project}}/locations/{{location}}/connections/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(integrationconnectors.Product, config)+"projects/{{project}}/locations/{{location}}/connections/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_endpoint_attachment_test.go b/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_endpoint_attachment_test.go index aedde000553c..e15944cf9d8e 100644 --- a/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_endpoint_attachment_test.go +++ b/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_endpoint_attachment_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/integrationconnectors" ) func TestAccIntegrationConnectorsEndpointAttachment_integrationConnectorsEndpointAttachmentExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_managed_zone_test.go b/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_managed_zone_test.go index 5a97f350cd61..55821bb74540 100644 --- a/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_managed_zone_test.go +++ b/mmv1/third_party/terraform/services/integrationconnectors/resource_integration_connectors_managed_zone_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" + _ "github.com/hashicorp/terraform-provider-google/google/services/integrationconnectors" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccIntegrationConnectorsManagedZone_integrationConnectorsManagedZoneExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/kms/bootstrap_test_utils.go b/mmv1/third_party/terraform/services/kms/bootstrap_test_utils.go new file mode 100644 index 000000000000..ec19dd61b4a6 --- /dev/null +++ b/mmv1/third_party/terraform/services/kms/bootstrap_test_utils.go @@ -0,0 +1,135 @@ +package kms + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + cloudkms "google.golang.org/api/cloudkms/v1" +) + +var SharedKeyRing = "tftest-shared-keyring-1" + +var SharedCryptoKey = map[string]string{ + "ENCRYPT_DECRYPT": "tftest-shared-key-1", + "ASYMMETRIC_SIGN": "tftest-shared-sign-key-1", + "ASYMMETRIC_DECRYPT": "tftest-shared-decrypt-key-1", +} + +type BootstrappedKMS struct { + *cloudkms.KeyRing + *cloudkms.CryptoKey + CryptoKeyVersions []*cloudkms.CryptoKeyVersion +} + +func BootstrapKMSKey(t *testing.T) BootstrappedKMS { + return BootstrapKMSKeyInLocation(t, "global") +} + +func BootstrapKMSKeyInLocation(t *testing.T, locationID string) BootstrappedKMS { + return BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", locationID) +} + +// BootstrapKMSKeyWithPurpose returns a KMS key in the "global" location. +// See BootstrapKMSKeyWithPurposeInLocation. +func BootstrapKMSKeyWithPurpose(t *testing.T, purpose string) BootstrappedKMS { + return BootstrapKMSKeyWithPurposeInLocation(t, purpose, "global") +} + +/** +* BootstrapKMSKeyWithPurposeInLocation will return a KMS key in a +* particular location with the given purpose that can be used +* in tests that are testing KMS integration with other resources. +* +* This will either return an existing key or create one if it hasn't been created +* in the project yet. The motivation is because keyrings don't get deleted and we +* don't want a linear growth of disabled keyrings in a project. We also don't want +* to incur the overhead of creating a new project for each test that needs to use +* a KMS key. +**/ +func BootstrapKMSKeyWithPurposeInLocation(t *testing.T, purpose, locationID string) BootstrappedKMS { + return BootstrapKMSKeyWithPurposeInLocationAndName(t, purpose, locationID, SharedCryptoKey[purpose]) +} + +func BootstrapKMSKeyWithPurposeInLocationAndName(t *testing.T, purpose, locationID, keyShortName string) BootstrappedKMS { + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return BootstrappedKMS{ + &cloudkms.KeyRing{}, + &cloudkms.CryptoKey{}, + nil, + } + } + + projectID := envvar.GetTestProjectFromEnv() + keyRingParent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + keyRingName := fmt.Sprintf("%s/keyRings/%s", keyRingParent, SharedKeyRing) + keyParent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s", projectID, locationID, SharedKeyRing) + keyName := fmt.Sprintf("%s/cryptoKeys/%s", keyParent, keyShortName) + + // Get or Create the hard coded shared keyring for testing + kmsClient := NewClient(config, config.UserAgent) + keyRing, err := kmsClient.Projects.Locations.KeyRings.Get(keyRingName).Do() + if err != nil { + if transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + keyRing, err = kmsClient.Projects.Locations.KeyRings.Create(keyRingParent, &cloudkms.KeyRing{}). + KeyRingId(SharedKeyRing).Do() + if err != nil { + t.Errorf("Unable to bootstrap KMS key. Cannot create keyRing: %s", err) + } + } else { + t.Errorf("Unable to bootstrap KMS key. Cannot retrieve keyRing: %s", err) + } + } + + if keyRing == nil { + t.Fatalf("Unable to bootstrap KMS key. keyRing is nil!") + } + + // Get or Create the hard coded, shared crypto key for testing + cryptoKey, err := kmsClient.Projects.Locations.KeyRings.CryptoKeys.Get(keyName).Do() + if err != nil { + if transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + algos := map[string]string{ + "ENCRYPT_DECRYPT": "GOOGLE_SYMMETRIC_ENCRYPTION", + "ASYMMETRIC_SIGN": "RSA_SIGN_PKCS1_4096_SHA256", + "ASYMMETRIC_DECRYPT": "RSA_DECRYPT_OAEP_4096_SHA256", + } + template := cloudkms.CryptoKeyVersionTemplate{ + Algorithm: algos[purpose], + } + + newKey := cloudkms.CryptoKey{ + Purpose: purpose, + VersionTemplate: &template, + } + + cryptoKey, err = kmsClient.Projects.Locations.KeyRings.CryptoKeys.Create(keyParent, &newKey). + CryptoKeyId(keyShortName).Do() + if err != nil { + t.Errorf("Unable to bootstrap KMS key. Cannot create new CryptoKey: %s", err) + } + + } else { + t.Errorf("Unable to bootstrap KMS key. Cannot call CryptoKey service: %s", err) + } + } + + if cryptoKey == nil { + t.Fatalf("Unable to bootstrap KMS key. CryptoKey is nil!") + } + + // TODO: b/372305432 Use the pagination properly. + ckvResp, err := kmsClient.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.List(keyName).Do() + if err != nil { + t.Fatalf("Unable to list cryptoKeyVersions: %v", err) + } + + return BootstrappedKMS{ + keyRing, + cryptoKey, + ckvResp.CryptoKeyVersions, + } +} diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_auotokey_config_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_auotokey_config_test.go index 5875c6953613..5d5141b314b5 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_auotokey_config_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_auotokey_config_test.go @@ -1,17 +1,318 @@ package kms_test import ( + "context" "fmt" "regexp" "strings" "testing" + "time" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanagerv3" + tpgserviceusage "github.com/hashicorp/terraform-provider-google/google/services/serviceusage" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + resourceManagerV3 "google.golang.org/api/cloudresourcemanager/v3" + + cloudkms "google.golang.org/api/cloudkms/v1" + cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1" ) +var DefaultKeyHandleName = "eed58b7b-20ad-4da8-ad85-ba78a0d5ab87" +var DefaultKeyHandleResourceType = "compute.googleapis.com/Disk" +var CloudKmsSrviceName = "cloudkms.googleapis.com" + +type BootstrappedKMSAutokey struct { + *cloudkms.AutokeyConfig + *cloudkms.KeyHandle +} + +func BootstrapKMSAutokeyKeyHandle(t *testing.T) BootstrappedKMSAutokey { + return BootstrapKMSAutokeyKeyHandleWithLocation(t, "global") +} + +func BootstrapKMSAutokeyKeyHandleWithLocation(t *testing.T, locationID string) BootstrappedKMSAutokey { + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return BootstrappedKMSAutokey{ + &cloudkms.AutokeyConfig{}, + &cloudkms.KeyHandle{}, + } + } + + autokeyFolder, kmsProject, resourceProject := setupAutokeyTestResources(t, config) + + // Enable autokey on autokey test folder + kmsClient := kms.NewClient(config, config.UserAgent) + autokeyConfigID := fmt.Sprintf("%s/autokeyConfig", autokeyFolder.Name) + autokeyConfig, err := kmsClient.Folders.UpdateAutokeyConfig(autokeyConfigID, &cloudkms.AutokeyConfig{ + KeyProject: fmt.Sprintf("projects/%s", kmsProject.ProjectId), + }).UpdateMask("keyProject").Do() + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot enable autokey on autokey test folder: %s", err) + } + + keyHandleParent := fmt.Sprintf("projects/%s/locations/%s", resourceProject.ProjectId, locationID) + keyHandleName := fmt.Sprintf("%s/keyHandles/%s", keyHandleParent, DefaultKeyHandleName) + + // Get or Create the hard coded keyHandle for testing + keyHandle, err := kmsClient.Projects.Locations.KeyHandles.Get(keyHandleName).Do() + + if err != nil { + if transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + newKeyHandle := cloudkms.KeyHandle{ + ResourceTypeSelector: DefaultKeyHandleResourceType, + } + + keyHandleOp, err := kmsClient.Projects.Locations.KeyHandles.Create(keyHandleParent, &newKeyHandle).KeyHandleId(DefaultKeyHandleName).Do() + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot create new KeyHandle: %s", err) + } + + opAsMap, err := tpgresource.ConvertToMap(keyHandleOp) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot get operation map: %s", err) + } + + var response map[string]interface{} + err = kms.KMSOperationWaitTimeWithResponse(config, opAsMap, &response, resourceProject.ProjectId, "creating keyHandle", config.UserAgent, time.Duration(5)*time.Minute) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot wait for create keyhandle operation: %s", err) + } + keyHandle = &cloudkms.KeyHandle{ + Name: response["name"].(string), + KmsKey: response["kmsKey"].(string), + ResourceTypeSelector: response["resourceTypeSelector"].(string), + } + } else { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot call KeyHandle service: %s", err) + } + } + + if keyHandle == nil { + t.Fatalf("unable to bootstrap KMS keyHandle. KeyHandle is nil!") + } + + return BootstrappedKMSAutokey{ + autokeyConfig, + keyHandle, + } +} + +func setupAutokeyTestResources(t *testing.T, config *transport_tpg.Config) (*resourceManagerV3.Folder, *cloudresourcemanager.Project, *cloudresourcemanager.Project) { + projectIDSuffix := strings.Replace(envvar.GetTestProjectFromEnv(), "ci-test-project-", "", 1) + defaultAutokeyTestFolderName := fmt.Sprintf("autokeytest-%s-fd", projectIDSuffix) + defaultAutokeyTestKmsProject := fmt.Sprintf("test-kms-%s-prj", projectIDSuffix) + defaultAutokeyTestResourceProject := fmt.Sprintf("test-res-%s-prj", projectIDSuffix) + + curUserEmail, err := transport_tpg.GetCurrentUserEmail(config, config.UserAgent) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot get current usr: %s", err) + } + // create a folder to configure autokey config and resource folder + autokeyFolder := BootstrapFolder(t, defaultAutokeyTestFolderName) + parent := &cloudresourcemanager.ResourceId{ + Type: "folder", + Id: strings.Split(autokeyFolder.Name, "/")[1], + } + // create and setup kms project for hosting keyring and keys for autokey + kmsProject := resourcemanager.BootstrapProjectWithParent(t, defaultAutokeyTestKmsProject, envvar.GetTestBillingAccountFromEnv(t), parent, []string{CloudKmsSrviceName}) + kmsProjectID := fmt.Sprintf("projects/%s", kmsProject.ProjectId) + kmsSAEmail, err := GenerateCloudKmsServiceIdentity(config, fmt.Sprintf("%v", kmsProject.ProjectNumber)) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot create cloudkms service identity: %s", err) + } + err = addFolderBinding2(resourcemanagerv3.NewClient(config, config.UserAgent), autokeyFolder.Name, fmt.Sprintf("user:%s", curUserEmail), []string{"roles/cloudkms.admin"}) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot assign cloudkms.admin role to current user on autokey test folder: %s", err) + } + err = addProjectBinding(resourcemanagerv3.NewClient(config, config.UserAgent), kmsProjectID, fmt.Sprintf("user:%s", curUserEmail), []string{"roles/resourcemanager.projectIamAdmin", "roles/cloudkms.admin"}) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot assign cloudkms.admin and projectIamAdmin role to current user on kms project: %s", err) + } + err = addProjectBinding(resourcemanagerv3.NewClient(config, config.UserAgent), kmsProjectID, fmt.Sprintf("serviceAccount:%s", kmsSAEmail), []string{"roles/cloudkms.admin"}) + if err != nil { + t.Errorf("unable to bootstrap KMS keyHandle. Cannot assign cloudkms.admin role to cloudkms service identity on kms project: %s", err) + } + + // create and setup resource folder to host keyhandle + resourceProject := resourcemanager.BootstrapProjectWithParent(t, defaultAutokeyTestResourceProject, envvar.GetTestBillingAccountFromEnv(t), parent, []string{}) + return autokeyFolder, kmsProject, resourceProject +} + +// GenerateCloudKmsServiceIdentity generates cloud kms service identity within a project +func GenerateCloudKmsServiceIdentity(config *transport_tpg.Config, projectNum string) (string, error) { + url := fmt.Sprintf("https://serviceusage.googleapis.com/v1beta1/projects/%s/services/%s:generateServiceIdentity", projectNum, CloudKmsSrviceName) + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: projectNum, + RawURL: url, + UserAgent: config.UserAgent, + Timeout: time.Minute * 4, + }) + if err != nil { + return "", fmt.Errorf("error creating cloudkms service identity: %s", err) + } + + var opRes map[string]interface{} + err = tpgserviceusage.ServiceUsageOperationWaitTimeWithResponse( + config, res, &opRes, projectNum, "Creating cloudkms service identity", config.UserAgent, + time.Minute*4) + if err != nil { + return "", err + } + return fmt.Sprintf("service-%s@gcp-sa-cloudkms.iam.gserviceaccount.com", projectNum), nil +} + +func addProjectBinding(crmService *resourceManagerV3.Service, projectID string, member string, roles []string) error { + return addBinding(crmService, "project", projectID, member, roles) +} + +func addFolderBinding2(crmService *resourceManagerV3.Service, folderID string, member string, roles []string) error { + return addBinding(crmService, "folder", folderID, member, roles) +} + +// addBinding adds the member to the project's IAM policy +func addBinding(crmService *resourceManagerV3.Service, resourceType string, resourceID string, member string, roles []string) error { + + policy, err := getPolicy(crmService, resourceType, resourceID) + if err != nil { + return err + } + + // Find the policy binding for role. Only one binding can have the role. + var binding *resourceManagerV3.Binding + for _, role := range roles { + for _, b := range policy.Bindings { + if b.Role == role { + binding = b + break + } + } + + if binding != nil { + // If the binding exists, adds the member to the binding + binding.Members = append(binding.Members, member) + } else { + // If the binding does not exist, adds a new binding to the policy + binding = &resourceManagerV3.Binding{ + Role: role, + Members: []string{member}, + } + policy.Bindings = append(policy.Bindings, binding) + } + } + setPolicy(crmService, resourceType, resourceID, policy) + return nil +} + +// getPolicy gets the IAM policy on input resourceID +// resourceType can be "project" or "folder" +func getPolicy(crmService *resourceManagerV3.Service, resourceType string, resourceID string) (*resourceManagerV3.Policy, error) { + + ctx := context.Background() + + ctx, cancel := context.WithTimeout(ctx, time.Second*10) + defer cancel() + request := new(resourceManagerV3.GetIamPolicyRequest) + var policy *resourceManagerV3.Policy + var err error + if resourceType == "project" { + policy, err = crmService.Projects.GetIamPolicy(resourceID, request).Do() + } else if resourceType == "folder" { + policy, err = crmService.Folders.GetIamPolicy(resourceID, request).Do() + } else { + return nil, fmt.Errorf("invalid resourceType, supported values: project or folder") + } + if err != nil { + return nil, fmt.Errorf("error getting iam policy: %s", err) + } + return policy, nil +} + +// setPolicy sets the IAM policy on input resourceID +// resourceType can be "project" or "folder" +func setPolicy(crmService *resourceManagerV3.Service, resourceType string, resourceID string, policy *resourceManagerV3.Policy) error { + + ctx := context.Background() + + ctx, cancel := context.WithTimeout(ctx, time.Second*10) + defer cancel() + request := new(resourceManagerV3.SetIamPolicyRequest) + request.Policy = policy + var err error + if resourceType == "project" { + _, err = crmService.Projects.SetIamPolicy(resourceID, request).Do() + } else if resourceType == "folder" { + _, err = crmService.Folders.SetIamPolicy(resourceID, request).Do() + } else { + return fmt.Errorf("invalid resourceType, supported values: project or folder") + } + if err != nil { + return fmt.Errorf("error setting iam policy: %s", err) + } + return nil +} + +// BootstrapFolder creates or get a folder having a input folderDisplayName within a TestOrgEnv +func BootstrapFolder(t *testing.T, folderDisplayName string) *resourceManagerV3.Folder { + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return nil + } + + crmClient := resourcemanagerv3.NewClient(config, config.UserAgent) + searchQuery := fmt.Sprintf("displayName=%s", folderDisplayName) + folderSearchResp, err := crmClient.Folders.Search().Query(searchQuery).Do() + if err != nil { + t.Fatalf("error searching for folder with displayName: %s", folderDisplayName) + } + var folder *resourceManagerV3.Folder + if len(folderSearchResp.Folders) == 0 { + op, err := crmClient.Folders.Create(&resourceManagerV3.Folder{ + DisplayName: folderDisplayName, + Parent: fmt.Sprintf("organizations/%s", envvar.GetTestOrgFromEnv(t)), + }).Do() + if err != nil { + t.Fatalf("error bootstrapping test folder: %s", err) + } + + opAsMap, err := tpgresource.ConvertToMap(op) + if err != nil { + t.Fatalf("error converting folder operation map: %s", err) + } + var responseMap map[string]interface{} + err = resourcemanager.ResourceManagerOperationWaitTimeWithResponse(config, opAsMap, &responseMap, "creating folder", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("error waiting for create folder operation: %s", err) + } + folder, err = crmClient.Folders.Get(responseMap["name"].(string)).Do() + if err != nil { + t.Fatalf("error getting folder: %s", err) + } + } else { + folder = folderSearchResp.Folders[0] + } + + if folder.State == "DELETE_REQUESTED" { + _, err := crmClient.Folders.Undelete(folder.Name, &resourceManagerV3.UndeleteFolderRequest{}).Do() + if err != nil { + t.Fatalf("error undeleting folder: %s", err) + } + } + return folder +} + func TestAccDataSourceGoogleKmsAutokeyConfig_basic(t *testing.T) { - kmsAutokey := acctest.BootstrapKMSAutokeyKeyHandle(t) + kmsAutokey := BootstrapKMSAutokeyKeyHandle(t) folder := fmt.Sprintf("folders/%s", strings.Split(kmsAutokey.AutokeyConfig.Name, "/")[1]) acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version.go index e73d52f40b62..16a31b337d72 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version.go @@ -125,14 +125,14 @@ func dataSourceGoogleKmsLatestCryptoKeyVersionRead(d *schema.ResourceData, meta return fmt.Errorf("Error setting LatestCryptoKeyVersion: %s", err) } - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}/cryptoKeyVersions/{{version}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}/cryptoKeyVersions/{{version}}") if err != nil { return err } log.Printf("[DEBUG] Getting attributes for CryptoKeyVersion: %#v", url) - url, err = tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}") if err != nil { return err } @@ -150,7 +150,7 @@ func dataSourceGoogleKmsLatestCryptoKeyVersionRead(d *schema.ResourceData, meta } if res["purpose"] == "ASYMMETRIC_SIGN" || res["purpose"] == "ASYMMETRIC_DECRYPT" { - url, err = tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}/cryptoKeyVersions/{{version}}/publicKey") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}/cryptoKeyVersions/{{version}}/publicKey") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version_test.go index bab5dbea7ae0..53f12995de66 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_latest_version_test.go @@ -7,10 +7,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsCryptoKeyLatestVersion_basic(t *testing.T) { - asymSignKey := acctest.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") + asymSignKey := kms.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") id := asymSignKey.CryptoKey.Name + "/latestCryptoKeyVersion" diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_test.go index 024c63d51842..4f74fb33b14f 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_test.go @@ -8,13 +8,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsCryptoKey_basic(t *testing.T) { - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) // Name in the KMS client is in the format projects//locations//keyRings//cryptoKeys/ - keyParts := strings.Split(kms.CryptoKey.Name, "/") + keyParts := strings.Split(bootstrapped.CryptoKey.Name, "/") cryptoKeyId := keyParts[len(keyParts)-1] acctest.VcrTest(t, resource.TestCase{ @@ -22,8 +23,8 @@ func TestAccDataSourceGoogleKmsCryptoKey_basic(t *testing.T) { ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ { - Config: testAccDataSourceGoogleKmsCryptoKey_basic(kms.KeyRing.Name, cryptoKeyId), - Check: resource.TestMatchResourceAttr("data.google_kms_crypto_key.kms_crypto_key", "id", regexp.MustCompile(kms.CryptoKey.Name)), + Config: testAccDataSourceGoogleKmsCryptoKey_basic(bootstrapped.KeyRing.Name, cryptoKeyId), + Check: resource.TestMatchResourceAttr("data.google_kms_crypto_key.kms_crypto_key", "id", regexp.MustCompile(bootstrapped.CryptoKey.Name)), }, }, }) diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version.go index 2217376e7faa..11a35424fe9a 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version.go @@ -69,7 +69,7 @@ func dataSourceGoogleKmsCryptoKeyVersionRead(d *schema.ResourceData, meta interf return err } - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}/cryptoKeyVersions/{{version}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}/cryptoKeyVersions/{{version}}") if err != nil { return err } @@ -107,7 +107,7 @@ func dataSourceGoogleKmsCryptoKeyVersionRead(d *schema.ResourceData, meta interf return fmt.Errorf("Error setting CryptoKeyVersion: %s", err) } - url, err = tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}") if err != nil { return err } @@ -125,7 +125,7 @@ func dataSourceGoogleKmsCryptoKeyVersionRead(d *schema.ResourceData, meta interf } if res["purpose"] == "ASYMMETRIC_SIGN" || res["purpose"] == "ASYMMETRIC_DECRYPT" { - url, err = tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}/cryptoKeyVersions/{{version}}/publicKey") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}/cryptoKeyVersions/{{version}}/publicKey") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version_test.go index 8af020cffbed..1d303c77ac0a 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_version_test.go @@ -6,12 +6,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsCryptoKeyVersion_basic(t *testing.T) { - asymSignKey := acctest.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") - asymDecrKey := acctest.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_DECRYPT") - symKey := acctest.BootstrapKMSKey(t) + asymSignKey := kms.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") + asymDecrKey := kms.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_DECRYPT") + symKey := kms.BootstrapKMSKey(t) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions.go index e0c37c4065fa..8a63f1874717 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions.go @@ -108,7 +108,7 @@ func dataSourceGoogleKmsCryptoKeyVersionsRead(d *schema.ResourceData, meta inter return nil } - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}") if err != nil { return err } @@ -126,7 +126,7 @@ func dataSourceGoogleKmsCryptoKeyVersionsRead(d *schema.ResourceData, meta inter } if res["purpose"] == "ASYMMETRIC_SIGN" || res["purpose"] == "ASYMMETRIC_DECRYPT" { - url, err = tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{KMSBasePath}}{{crypto_key}}/cryptoKeyVersions/%d/publicKey", d.Get("versions.0.version"))) + url, err = tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}/cryptoKeyVersions/%d/publicKey", d.Get("versions.0.version"))) if err != nil { return err } @@ -158,7 +158,7 @@ func dataSourceGoogleKmsCryptoKeyVersionsRead(d *schema.ResourceData, meta inter func dataSourceKMSCryptoKeyVersionsList(d *schema.ResourceData, meta interface{}, cryptoKeyId string, userAgent string) ([]interface{}, error) { config := meta.(*transport_tpg.Config) - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{crypto_key}}/cryptoKeyVersions") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{crypto_key}}/cryptoKeyVersions") if err != nil { return nil, err } diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions_test.go index 52d19c613b83..9ee058d39da0 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_key_versions_test.go @@ -7,10 +7,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsCryptoKeyVersions_basic(t *testing.T) { - asymSignKey := acctest.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") + asymSignKey := kms.BootstrapKMSKeyWithPurpose(t, "ASYMMETRIC_SIGN") id := asymSignKey.CryptoKey.Name + "/cryptoKeyVersions" diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys.go index 5ac1515e5ca0..b8eeb3a354f7 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys.go @@ -103,7 +103,7 @@ func dataSourceKMSCryptoKeysList(d *schema.ResourceData, meta interface{}, keyRi return nil, err } - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}{{key_ring}}/cryptoKeys") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{key_ring}}/cryptoKeys") if err != nil { return nil, err } diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys_test.go index 1aa5025bbd41..6979a7eca7a5 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_crypto_keys_test.go @@ -7,12 +7,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsCryptoKeys_basic(t *testing.T) { - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) - id := kms.KeyRing.Name + "/cryptoKeys" + id := bootstrapped.KeyRing.Name + "/cryptoKeys" randomString := acctest.RandString(t, 10) filterNameFindSharedKeys := "name:tftest-shared-" @@ -22,7 +23,7 @@ func TestAccDataSourceGoogleKmsCryptoKeys_basic(t *testing.T) { findsNoKeysId := fmt.Sprintf("%s/filter=%s", id, filterNameFindsNoKeys) context := map[string]interface{}{ - "key_ring": kms.KeyRing.Name, + "key_ring": bootstrapped.KeyRing.Name, "filter": "", // Can be overridden using 2nd argument to config funcs } @@ -34,7 +35,7 @@ func TestAccDataSourceGoogleKmsCryptoKeys_basic(t *testing.T) { Config: testAccDataSourceGoogleKmsCryptoKeys_basic(context, ""), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "id", id), - resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "key_ring", kms.KeyRing.Name), + resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "key_ring", bootstrapped.KeyRing.Name), resource.TestMatchResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "keys.#", regexp.MustCompile("[1-9]+[0-9]*")), ), }, @@ -43,7 +44,7 @@ func TestAccDataSourceGoogleKmsCryptoKeys_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( // This filter should retrieve keys in the bootstrapped KMS key ring used by the test resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "id", findSharedKeysId), - resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "key_ring", kms.KeyRing.Name), + resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "key_ring", bootstrapped.KeyRing.Name), resource.TestMatchResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "keys.#", regexp.MustCompile("[1-9]+[0-9]*")), ), }, @@ -52,7 +53,7 @@ func TestAccDataSourceGoogleKmsCryptoKeys_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( // This filter should retrieve no keys resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "id", findsNoKeysId), - resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "key_ring", kms.KeyRing.Name), + resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "key_ring", bootstrapped.KeyRing.Name), resource.TestCheckResourceAttr("data.google_kms_crypto_keys.all_keys_in_ring", "keys.#", "0"), ), }, diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handle_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handle_test.go index 0a4fd012c720..00e02eac8da5 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handle_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handle_test.go @@ -11,7 +11,7 @@ import ( ) func TestAccDataSourceGoogleKmsKeyHandle_basic(t *testing.T) { - kmsAutokey := acctest.BootstrapKMSAutokeyKeyHandle(t) + kmsAutokey := BootstrapKMSAutokeyKeyHandle(t) keyParts := strings.Split(kmsAutokey.KeyHandle.Name, "/") project := keyParts[1] location := keyParts[3] diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles.go index a82423b56885..54f1d866a08f 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles.go @@ -78,7 +78,7 @@ func dataSourceGoogleKmsKeyHandlesRead(d *schema.ResourceData, meta interface{}) billingProject = bp } - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}projects/{{project}}/locations/{{location}}/keyHandles") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/keyHandles") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles_test.go index a7a4447886b6..c74bb3faf42f 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_handles_test.go @@ -13,7 +13,7 @@ import ( ) func TestAccDataSourceGoogleKmsKeyHandles_basic(t *testing.T) { - kmsAutokey := acctest.BootstrapKMSAutokeyKeyHandle(t) + kmsAutokey := BootstrapKMSAutokeyKeyHandle(t) keyParts := strings.Split(kmsAutokey.KeyHandle.Name, "/") project := keyParts[1] location := keyParts[3] diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_ring_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_ring_test.go index 0abfb6b83b85..ef68a9bc4320 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_ring_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_ring_test.go @@ -8,12 +8,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsKeyRing_basic(t *testing.T) { - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) - keyParts := strings.Split(kms.KeyRing.Name, "/") + keyParts := strings.Split(bootstrapped.KeyRing.Name, "/") keyRingId := keyParts[len(keyParts)-1] acctest.VcrTest(t, resource.TestCase{ @@ -22,7 +23,7 @@ func TestAccDataSourceGoogleKmsKeyRing_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccDataSourceGoogleKmsKeyRing_basic(keyRingId), - Check: resource.TestMatchResourceAttr("data.google_kms_key_ring.kms_key_ring", "id", regexp.MustCompile(kms.KeyRing.Name)), + Check: resource.TestMatchResourceAttr("data.google_kms_key_ring.kms_key_ring", "id", regexp.MustCompile(bootstrapped.KeyRing.Name)), }, }, }) diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings.go index 453e05228877..54d8b3a4df10 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings.go @@ -101,7 +101,7 @@ func dataSourceGoogleKmsKeyRingsRead(d *schema.ResourceData, meta interface{}) e } } - url, err := tpgresource.ReplaceVars(d, config, "{{KMSBasePath}}projects/{{project}}/locations/{{location}}/keyRings") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/keyRings") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings_test.go index c7cf30b87646..a3003beae003 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_key_rings_test.go @@ -8,11 +8,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataSourceGoogleKmsKeyRings_basic(t *testing.T) { - kms := acctest.BootstrapKMSKey(t) - idPath := strings.Split(kms.KeyRing.Name, "/") + bootstrapped := kms.BootstrapKMSKey(t) + idPath := strings.Split(bootstrapped.KeyRing.Name, "/") location := idPath[3] randomString := acctest.RandString(t, 10) filterNameFindSharedKeys := "name:tftest-shared-" diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_asymmetric_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_asymmetric_test.go index e6dd1bb88552..9153efb9cbb9 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_asymmetric_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_asymmetric_test.go @@ -16,6 +16,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccKmsSecretAsymmetricBasic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_ciphertext_test.go b/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_ciphertext_test.go index 1688ccd8a682..af49c37cdca5 100644 --- a/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_ciphertext_test.go +++ b/mmv1/third_party/terraform/services/kms/data_source_google_kms_secret_ciphertext_test.go @@ -7,12 +7,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccDataKmsSecretCiphertext_basic(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) plaintext := fmt.Sprintf("secret-%s", acctest.RandString(t, 10)) @@ -21,9 +22,9 @@ func TestAccDataKmsSecretCiphertext_basic(t *testing.T) { ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ { - Config: testGoogleKmsSecretCiphertext_datasource(kms.CryptoKey.Name, plaintext), + Config: testGoogleKmsSecretCiphertext_datasource(bootstrapped.CryptoKey.Name, plaintext), Check: func(s *terraform.State) error { - plaintext, err := testAccDecryptSecretDataWithCryptoKey(t, s, kms.CryptoKey.Name, "data.google_kms_secret_ciphertext.acceptance", "") + plaintext, err := testAccDecryptSecretDataWithCryptoKey(t, s, bootstrapped.CryptoKey.Name, "data.google_kms_secret_ciphertext.acceptance", "") if err != nil { return err diff --git a/mmv1/third_party/terraform/services/kms/iam_kms_crypto_key_test.go.tmpl b/mmv1/third_party/terraform/services/kms/iam_kms_crypto_key_test.go.tmpl index 4c728c24ac41..3e3ffc994da9 100644 --- a/mmv1/third_party/terraform/services/kms/iam_kms_crypto_key_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/iam_kms_crypto_key_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/kms" ) diff --git a/mmv1/third_party/terraform/services/kms/iam_kms_key_ring_test.go.tmpl b/mmv1/third_party/terraform/services/kms/iam_kms_key_ring_test.go.tmpl index e857d6d69871..6b9a67cd460e 100644 --- a/mmv1/third_party/terraform/services/kms/iam_kms_key_ring_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/iam_kms_key_ring_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/kms" ) diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_autokey_config_test.go.tmpl b/mmv1/third_party/terraform/services/kms/resource_kms_autokey_config_test.go.tmpl index 47c3c4dc1855..bb8a3afe6e1a 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_autokey_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/resource_kms_autokey_config_test.go.tmpl @@ -5,6 +5,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_test.go.tmpl b/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_test.go.tmpl index d38a0a7ccdf6..1e62f6db94ae 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_test.go.tmpl @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/kms" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_version_test.go b/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_version_test.go index 3b8210e7cce2..6445075c8fea 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_version_test.go +++ b/mmv1/third_party/terraform/services/kms/resource_kms_crypto_key_version_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_ekm_connection_test.go b/mmv1/third_party/terraform/services/kms/resource_kms_ekm_connection_test.go index e2e5f6061f3b..2aedf2243c00 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_ekm_connection_test.go +++ b/mmv1/third_party/terraform/services/kms/resource_kms_ekm_connection_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccKMSEkmConnection_kmsEkmConnectionBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_folder_kaj_policy_config_test.go.tmpl b/mmv1/third_party/terraform/services/kms/resource_kms_folder_kaj_policy_config_test.go.tmpl index 8e86996d1e59..3dd0f89182b3 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_folder_kaj_policy_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/resource_kms_folder_kaj_policy_config_test.go.tmpl @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_import_job_test.go b/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_import_job_test.go index 47d7ffaaadac..19382c3c036d 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_import_job_test.go +++ b/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_import_job_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccKmsKeyRingImportJob_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_test.go b/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_test.go index 35f3b31e7a33..87fe14122324 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_test.go +++ b/mmv1/third_party/terraform/services/kms/resource_kms_key_ring_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccKmsKeyRing_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_organization_kaj_policy_config_test.go.tmpl b/mmv1/third_party/terraform/services/kms/resource_kms_organization_kaj_policy_config_test.go.tmpl index 0dab0a142e68..2d2b02fc7bd1 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_organization_kaj_policy_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/resource_kms_organization_kaj_policy_config_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_project_kaj_policy_config_test.go.tmpl b/mmv1/third_party/terraform/services/kms/resource_kms_project_kaj_policy_config_test.go.tmpl index c359f2f36893..44d4ce9e64f1 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_project_kaj_policy_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/kms/resource_kms_project_kaj_policy_config_test.go.tmpl @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/kms/resource_kms_secret_ciphertext_test.go b/mmv1/third_party/terraform/services/kms/resource_kms_secret_ciphertext_test.go index 05a6e88e8f16..6f59ee72bf01 100644 --- a/mmv1/third_party/terraform/services/kms/resource_kms_secret_ciphertext_test.go +++ b/mmv1/third_party/terraform/services/kms/resource_kms_secret_ciphertext_test.go @@ -17,7 +17,7 @@ import ( func TestAccKmsSecretCiphertext_basic(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) plaintext := fmt.Sprintf("secret-%s", acctest.RandString(t, 10)) aad := "plainaad" @@ -27,9 +27,9 @@ func TestAccKmsSecretCiphertext_basic(t *testing.T) { ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ { - Config: testGoogleKmsSecretCiphertext(kms.CryptoKey.Name, plaintext), + Config: testGoogleKmsSecretCiphertext(bootstrapped.CryptoKey.Name, plaintext), Check: func(s *terraform.State) error { - plaintext, err := testAccDecryptSecretDataWithCryptoKey(t, s, kms.CryptoKey.Name, "google_kms_secret_ciphertext.acceptance", "") + plaintext, err := testAccDecryptSecretDataWithCryptoKey(t, s, bootstrapped.CryptoKey.Name, "google_kms_secret_ciphertext.acceptance", "") if err != nil { return err @@ -40,9 +40,9 @@ func TestAccKmsSecretCiphertext_basic(t *testing.T) { }, // With AAD { - Config: testGoogleKmsSecretCiphertext_withAAD(kms.CryptoKey.Name, plaintext, aad), + Config: testGoogleKmsSecretCiphertext_withAAD(bootstrapped.CryptoKey.Name, plaintext, aad), Check: func(s *terraform.State) error { - plaintext, err := testAccDecryptSecretDataWithCryptoKey(t, s, kms.CryptoKey.Name, "google_kms_secret_ciphertext.acceptance", aad) + plaintext, err := testAccDecryptSecretDataWithCryptoKey(t, s, bootstrapped.CryptoKey.Name, "google_kms_secret_ciphertext.acceptance", aad) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_folder_settings_test.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_folder_settings_test.go index 96443cbc4c69..335ab078cb88 100644 --- a/mmv1/third_party/terraform/services/logging/data_source_google_logging_folder_settings_test.go +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_folder_settings_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccLoggingFolderSettings_datasource(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_log_view.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_log_view.go new file mode 100644 index 000000000000..fcd8daeff9bb --- /dev/null +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_log_view.go @@ -0,0 +1,52 @@ +package logging + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-google/google/registry" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func DataSourceGoogleLoggingLogView() *schema.Resource { + dsSchema := tpgresource.DatasourceSchemaFromResourceSchema(ResourceLoggingLogView().Schema) + + tpgresource.AddRequiredFieldsToSchema(dsSchema, "parent", "location", "bucket", "name") + + return &schema.Resource{ + Read: dataSourceGoogleLoggingLogViewRead, + Schema: dsSchema, + } +} + +func dataSourceGoogleLoggingLogViewRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + + id, err := tpgresource.ReplaceVars(d, config, "{{parent}}/locations/{{location}}/buckets/{{bucket}}/views/{{name}}") + if err != nil { + return err + } + + d.SetId(id) + + err = resourceLoggingLogViewRead(d, meta) + if err != nil { + return err + } + + if d.Id() == "" { + return fmt.Errorf("%s not found", id) + } + + return nil +} + +func init() { + registry.Schema{ + Name: "google_logging_log_view", + ProductName: "logging", + Type: registry.SchemaTypeDataSource, + Schema: DataSourceGoogleLoggingLogView(), + }.Register() +} diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_log_view_test.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_log_view_test.go new file mode 100644 index 000000000000..0d5a2893529a --- /dev/null +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_log_view_test.go @@ -0,0 +1,70 @@ +package logging_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" +) + +func TestAccDataSourceGoogleLoggingLogView_basic(t *testing.T) { + t.Parallel() + + randomSuffix := acctest.RandString(t, 10) + + context := map[string]interface{}{ + "project": envvar.GetTestProjectFromEnv(), + "log_view_name": "tf-test-my-view" + randomSuffix, + "random_suffix": randomSuffix, + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckLoggingLogViewDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDataSourceGoogleLoggingLogView_basic(context), + Check: resource.ComposeTestCheckFunc( + acctest.CheckDataSourceStateMatchesResourceStateWithIgnores( + "data.google_logging_log_view.basic", + "google_logging_log_view.logging_log_view", + []string{ + "bucket", + "location", + "name", + "parent", + }, + ), + ), + }, + }, + }) +} + +func testAccDataSourceGoogleLoggingLogView_basic(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_logging_project_bucket_config" "logging_log_view" { + project = "%{project}" + location = "global" + retention_days = 30 + bucket_id = "_Default" +} + +resource "google_logging_log_view" "logging_log_view" { + name = "%{log_view_name}" + bucket = google_logging_project_bucket_config.logging_log_view.id + description = "A logging view configured with Terraform" + filter = "SOURCE(\"projects/myproject\") AND resource.type = \"gce_instance\" AND LOG_ID(\"stdout\")" +} + +data "google_logging_log_view" "basic" { + parent = google_logging_log_view.logging_log_view.parent + location = google_logging_log_view.logging_log_view.location + bucket = google_logging_log_view.logging_log_view.bucket + name = google_logging_log_view.logging_log_view.name +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_organization_settings_test.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_organization_settings_test.go index 2b8d9d913267..78e01cf2c52b 100644 --- a/mmv1/third_party/terraform/services/logging/data_source_google_logging_organization_settings_test.go +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_organization_settings_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccLoggingOrganizationSettings_datasource(t *testing.T) { @@ -15,7 +16,7 @@ func TestAccLoggingOrganizationSettings_datasource(t *testing.T) { context := map[string]interface{}{ "org_id": envvar.GetTestOrgFromEnv(t), - "original_key": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "original_key": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, } resourceName := "data.google_logging_organization_settings.settings" diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings.go index 89985d4f5b18..f86bdd1ed30a 100644 --- a/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings.go +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings.go @@ -60,7 +60,7 @@ func dataSourceGoogleLoggingProjectCmekSettingsRead(d *schema.ResourceData, meta return err } - url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}projects/{{project}}/cmekSettings") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/cmekSettings") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings_test.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings_test.go index 96a2d98a4cc7..7a3bab6c8ae0 100644 --- a/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings_test.go +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_cmek_settings_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccLoggingProjectCmekSettings_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_settings_test.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_settings_test.go index dc41e8468a77..335473ad9457 100644 --- a/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_settings_test.go +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_project_settings_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccLoggingProjectSettings_datasource(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/data_source_google_logging_sink_test.go b/mmv1/third_party/terraform/services/logging/data_source_google_logging_sink_test.go index 8a3872896fe1..d57b413c183c 100644 --- a/mmv1/third_party/terraform/services/logging/data_source_google_logging_sink_test.go +++ b/mmv1/third_party/terraform/services/logging/data_source_google_logging_sink_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceGoogleLoggingSink_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_bucket_config_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_bucket_config_meta.yaml index 6e63d27557f0..b000cffa09bc 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_bucket_config_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_bucket_config_meta.yaml @@ -19,3 +19,6 @@ fields: - field: 'location' - api_field: 'name' - api_field: 'retentionDays' + - field: 'deletion_policy' + provider_only: true + \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink.go b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink.go index c4a2e679e8ac..884a90a2c873 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink.go @@ -3,6 +3,7 @@ package logging import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -19,6 +20,9 @@ func ResourceLoggingBillingAccountSink() *schema.Resource { Importer: &schema.ResourceImporter{ State: resourceLoggingSinkImportState("billing_account"), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), UseJSONNumber: true, } schm.Schema["billing_account"] = &schema.Schema{ @@ -65,10 +69,19 @@ func resourceLoggingBillingAccountSinkRead(d *schema.ResourceData, meta interfac return err } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceLoggingBillingAccountSinkUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceLoggingBillingAccountSink) { + return ResourceLoggingBillingAccountSink().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -88,6 +101,13 @@ func resourceLoggingBillingAccountSinkUpdate(d *schema.ResourceData, meta interf } func resourceLoggingBillingAccountSinkDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_meta.yaml index b32994002366..5be76c2eeab0 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_meta.yaml @@ -18,3 +18,5 @@ fields: - api_field: 'filter' - api_field: 'name' - api_field: 'writerIdentity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_test.go index 337b6795571e..a7094f5d38e0 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_billing_account_sink_test.go @@ -8,7 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" logging_tpg "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" "google.golang.org/api/logging/v2" ) diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config.go b/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config.go index 6aa57eb95346..05c9a0a18163 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config.go @@ -112,6 +112,9 @@ For example: jsonPayload.request.status`, }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end } type loggingBucketConfigIDFunc func(d *schema.ResourceData, config *transport_tpg.Config) (string, error) @@ -130,6 +133,7 @@ func ResourceLoggingBucketConfig(parentType string, parentSpecificSchema map[str Schema: tpgresource.MergeSchemas(loggingBucketConfigSchema, parentSpecificSchema), UseJSONNumber: true, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), } @@ -193,7 +197,7 @@ func resourceLoggingBucketConfigAcquireOrCreate(parentType string, iDFunc loggin //logging bucket can be created only at the project level, in future api may allow for folder, org and other parent resources log.Printf("[DEBUG] Fetching logging bucket config: %#v", id) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", id)) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", id)) if err != nil { return err } @@ -232,7 +236,7 @@ func resourceLoggingBucketConfigCreate(d *schema.ResourceData, meta interface{}, obj["cmekSettings"] = expandCmekSettings(d.Get("cmek_settings")) obj["indexConfigs"] = expandIndexConfigs(d.Get("index_configs")) - url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}projects/{{project}}/locations/{{location}}/buckets?bucketId={{bucket_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/buckets?bucketId={{bucket_id}}") if err != nil { return err } @@ -280,7 +284,7 @@ func resourceLoggingBucketConfigRead(d *schema.ResourceData, meta interface{}) e log.Printf("[DEBUG] Fetching logging bucket config: %#v", d.Id()) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id())) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", d.Id())) if err != nil { return err } @@ -319,10 +323,29 @@ func resourceLoggingBucketConfigRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error setting index_configs: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceLoggingBucketConfigUpdate(d *schema.ResourceData, meta interface{}) error { + + //due to non standard resource function, Universal Deletion Policy pre-update code is included here in entirety + clientSideFields := map[string]bool{"deletion_policy": true} + clientSideOnly := true + for field := range loggingBucketConfigSchema { + if d.HasChange(field) && !clientSideFields[field] { + clientSideOnly = false + break + } + } + if clientSideOnly { + log.Print("[DEBUG] Only client-side changes detected. Cancelling update operation.") + return resourceLoggingBucketConfigRead(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -331,7 +354,7 @@ func resourceLoggingBucketConfigUpdate(d *schema.ResourceData, meta interface{}) obj := make(map[string]interface{}) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id())) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", d.Id())) if err != nil { return err } @@ -376,6 +399,13 @@ func resourceLoggingBucketConfigUpdate(d *schema.ResourceData, meta interface{}) } func resourceLoggingBucketConfigDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + name := d.Get("bucket_id") for _, restrictedName := range []string{"_Required", "_Default"} { if name == restrictedName { @@ -389,7 +419,7 @@ func resourceLoggingBucketConfigDelete(d *schema.ResourceData, meta interface{}) if err != nil { return err } - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id())) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", d.Id())) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config_test.go index 08ac905381b0..fed13d7e4a08 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_bucket_config_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccLoggingBucketConfigFolder_basic(t *testing.T) { @@ -18,7 +21,7 @@ func TestAccLoggingBucketConfigFolder_basic(t *testing.T) { "random_suffix": acctest.RandString(t, 10), "folder_name": "tf-test-" + acctest.RandString(t, 10), "org_id": envvar.GetTestOrgFromEnv(t), - "original_key": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "original_key": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_folder_bucket_config_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_folder_bucket_config_meta.yaml index ff41624155f3..5086c7b4208f 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_folder_bucket_config_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_folder_bucket_config_meta.yaml @@ -19,3 +19,5 @@ fields: - field: 'location' - api_field: 'name' - api_field: 'retentionDays' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_folder_exclusion_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_folder_exclusion_test.go index d2152dbe6ad7..23b93ee2a5de 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_folder_exclusion_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_folder_exclusion_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // Logging exclusions don't always work when making parallel requests, so run tests serially diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_folder_settings_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_folder_settings_test.go index 625ae6974984..d04c3307625c 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_folder_settings_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_folder_settings_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccLoggingFolderSettings_update(t *testing.T) { @@ -15,8 +18,8 @@ func TestAccLoggingFolderSettings_update(t *testing.T) { context := map[string]interface{}{ "org_id": envvar.GetTestOrgFromEnv(t), "random_suffix": acctest.RandString(t, 10), - "original_key": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, - "updated_key": acctest.BootstrapKMSKeyInLocation(t, "us-east1").CryptoKey.Name, + "original_key": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "updated_key": kms.BootstrapKMSKeyInLocation(t, "us-east1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink.go b/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink.go index 8adff2e77501..052514d90674 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" @@ -18,6 +19,9 @@ func ResourceLoggingFolderSink() *schema.Resource { Delete: resourceLoggingFolderSinkDelete, Update: resourceLoggingFolderSinkUpdate, Schema: resourceLoggingSinkSchema(), + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), Importer: &schema.ResourceImporter{ State: resourceLoggingSinkImportState("folder"), }, @@ -94,10 +98,19 @@ func resourceLoggingFolderSinkRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error setting intercept_children: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceLoggingFolderSinkUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceLoggingFolderSink) { + return ResourceLoggingFolderSink().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -117,6 +130,13 @@ func resourceLoggingFolderSinkUpdate(d *schema.ResourceData, meta interface{}) e } func resourceLoggingFolderSinkDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_meta.yaml index 35869fd00a44..6c2476e3a80e 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_meta.yaml @@ -20,3 +20,5 @@ fields: - api_field: 'interceptChildren' - api_field: 'name' - api_field: 'writerIdentity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_test.go index d79f324aef7b..7c0bbeb9d45b 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_folder_sink_test.go @@ -8,7 +8,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" logging_tpg "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_log_view_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_log_view_test.go index ee5b56710c3f..185a0251cfba 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_log_view_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_log_view_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" ) func TestAccLoggingLogView_loggingLogViewBasicExampleUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_metric_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_metric_test.go index c58c9bf8511f..9fcb55372a93 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_metric_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_metric_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" ) func TestAccLoggingMetric_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_organization_bucket_config_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_organization_bucket_config_meta.yaml index a1643a2c6f45..47c577d8d356 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_organization_bucket_config_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_organization_bucket_config_meta.yaml @@ -19,3 +19,5 @@ fields: - api_field: 'name' - field: 'organization' - api_field: 'retentionDays' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_organization_settings_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_organization_settings_test.go index 1f77465ed84a..3fee85ecec51 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_organization_settings_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_organization_settings_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" ) var orgSettingsMu sync.Mutex @@ -20,8 +22,8 @@ func TestAccLoggingOrganizationSettings_update(t *testing.T) { context := map[string]interface{}{ "org_id": envvar.GetTestOrgTargetFromEnv(t), "random_suffix": acctest.RandString(t, 10), - "original_key": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, - "updated_key": acctest.BootstrapKMSKeyInLocation(t, "us-east1").CryptoKey.Name, + "original_key": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "updated_key": kms.BootstrapKMSKeyInLocation(t, "us-east1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink.go b/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink.go index 213dceb7b353..61c83572daa9 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -17,6 +18,9 @@ func ResourceLoggingOrganizationSink() *schema.Resource { Delete: resourceLoggingOrganizationSinkDelete, Update: resourceLoggingOrganizationSinkUpdate, Schema: resourceLoggingSinkSchema(), + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), Importer: &schema.ResourceImporter{ State: resourceLoggingSinkImportState("org_id"), }, @@ -93,10 +97,19 @@ func resourceLoggingOrganizationSinkRead(d *schema.ResourceData, meta interface{ return fmt.Errorf("Error setting intercept_children: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceLoggingOrganizationSinkUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceLoggingOrganizationSink) { + return ResourceLoggingOrganizationSink().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -116,6 +129,13 @@ func resourceLoggingOrganizationSinkUpdate(d *schema.ResourceData, meta interfac } func resourceLoggingOrganizationSinkDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_meta.yaml index 07c08cd01e42..19610a15ffca 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_meta.yaml @@ -20,3 +20,5 @@ fields: - api_field: 'name' - field: 'org_id' - api_field: 'writerIdentity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_test.go index 62d18fd54c0b..16d83be03075 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_organization_sink_test.go @@ -10,7 +10,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" logging_tpg "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" "google.golang.org/api/logging/v2" ) diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config.go b/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config.go index 398fa48bfb0e..38129405aed9 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config.go @@ -129,6 +129,9 @@ For example: jsonPayload.request.status`, }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end } func projectBucketConfigID(d *schema.ResourceData, config *transport_tpg.Config) (string, error) { @@ -177,7 +180,7 @@ func resourceLoggingProjectBucketConfigAcquireOrCreate(parentType string, iDFunc //logging bucket can be created only at the project level, in future api may allow for folder, org and other parent resources log.Printf("[DEBUG] Fetching logging bucket config: %#v", id) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", id)) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", id)) if err != nil { return err } @@ -222,7 +225,7 @@ func resourceLoggingProjectBucketConfigCreate(d *schema.ResourceData, meta inter obj["cmekSettings"] = expandCmekSettings(d.Get("cmek_settings")) obj["indexConfigs"] = expandIndexConfigs(d.Get("index_configs")) - url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}projects/{{project}}/locations/{{location}}/buckets:createAsync?bucketId={{bucket_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/buckets:createAsync?bucketId={{bucket_id}}") if err != nil { return err } @@ -277,7 +280,7 @@ func resourceLoggingProjectBucketConfigRead(d *schema.ResourceData, meta interfa log.Printf("[DEBUG] Fetching logging bucket config: %#v", d.Id()) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id())) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", d.Id())) if err != nil { return err } @@ -334,7 +337,7 @@ func resourceLoggingProjectBucketConfigUpdate(d *schema.ResourceData, meta inter obj := make(map[string]interface{}) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id())) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"%s", d.Id())) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config_meta.yaml index 5345dfd58438..c7b5c3dd67f4 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_project_bucket_config_meta.yaml @@ -21,3 +21,6 @@ fields: - api_field: 'name' - field: 'project' - api_field: 'retentionDays' + - field: 'deletion_policy' + provider_only: true + \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_project_sink.go b/mmv1/third_party/terraform/services/logging/resource_logging_project_sink.go index 607238c5e267..c9fec7cf5da8 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_project_sink.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_project_sink.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -17,12 +18,15 @@ const nonUniqueWriterAccount = "serviceAccount:cloud-logs@system.gserviceaccount func ResourceLoggingProjectSink() *schema.Resource { schm := &schema.Resource{ - Create: resourceLoggingProjectSinkAcquireOrCreate, - Read: resourceLoggingProjectSinkRead, - Delete: resourceLoggingProjectSinkDelete, - Update: resourceLoggingProjectSinkUpdate, - Schema: resourceLoggingSinkSchema(), - CustomizeDiff: resourceLoggingProjectSinkCustomizeDiff, + Create: resourceLoggingProjectSinkAcquireOrCreate, + Read: resourceLoggingProjectSinkRead, + Delete: resourceLoggingProjectSinkDelete, + Update: resourceLoggingProjectSinkUpdate, + Schema: resourceLoggingSinkSchema(), + CustomizeDiff: customdiff.All( + resourceLoggingProjectSinkCustomizeDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), Importer: &schema.ResourceImporter{ State: resourceLoggingSinkImportState("project"), }, @@ -171,10 +175,20 @@ func resourceLoggingProjectSinkRead(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("Error setting unique_writer_identity: %s", err) } } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceLoggingProjectSinkUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceLoggingProjectSink) { + return ResourceLoggingProjectSink().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -205,6 +219,13 @@ func resourceLoggingProjectSinkUpdate(d *schema.ResourceData, meta interface{}) } func resourceLoggingProjectSinkDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + name := d.Get("name") for _, restrictedName := range []string{"_Required", "_Default"} { if name == restrictedName { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_meta.yaml b/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_meta.yaml index 92db479c651f..14a59668903e 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_meta.yaml +++ b/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_meta.yaml @@ -20,3 +20,5 @@ fields: - field: 'project' - field: 'unique_writer_identity' - api_field: 'writerIdentity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_test.go index eccec4779151..e0b96d005530 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_project_sink_test.go @@ -8,7 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" "github.com/hashicorp/terraform-provider-google/google/services/logging" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccLoggingProjectSink_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_saved_query_test.go b/mmv1/third_party/terraform/services/logging/resource_logging_saved_query_test.go index 9abc41a08a8e..611851c7686c 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_saved_query_test.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_saved_query_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/logging" ) func TestAccLoggingSavedQuery_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/logging/resource_logging_sink.go b/mmv1/third_party/terraform/services/logging/resource_logging_sink.go index 98a9ebf339cc..4553c12ce6c7 100644 --- a/mmv1/third_party/terraform/services/logging/resource_logging_sink.go +++ b/mmv1/third_party/terraform/services/logging/resource_logging_sink.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/api/logging/v2" ) @@ -100,6 +102,10 @@ func resourceLoggingSinkSchema() map[string]*schema.Schema { }, }, }, + + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end } } diff --git a/mmv1/third_party/terraform/services/looker/resource_looker_instance_test.go b/mmv1/third_party/terraform/services/looker/resource_looker_instance_test.go index 3d9a5950e980..25d3c38f155c 100644 --- a/mmv1/third_party/terraform/services/looker/resource_looker_instance_test.go +++ b/mmv1/third_party/terraform/services/looker/resource_looker_instance_test.go @@ -7,6 +7,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/looker" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccLookerInstance_update(t *testing.T) { @@ -147,7 +151,7 @@ func TestAccLookerInstance_updatePeriodicExport(t *testing.T) { "random_suffix": suffix, } - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { // For writing/managing the export files in GCS Member: "serviceAccount:service-{project_number}@gcp-sa-looker.iam.gserviceaccount.com", diff --git a/mmv1/third_party/terraform/services/lustre/data_source_lustre_instance_test.go b/mmv1/third_party/terraform/services/lustre/data_source_lustre_instance_test.go index e369beca67db..f70de96b8fb1 100644 --- a/mmv1/third_party/terraform/services/lustre/data_source_lustre_instance_test.go +++ b/mmv1/third_party/terraform/services/lustre/data_source_lustre_instance_test.go @@ -5,13 +5,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/lustre" ) func TestAccLustreInstanceDatasource_basic(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/lustre/resource_lustre_instance_test.go b/mmv1/third_party/terraform/services/lustre/resource_lustre_instance_test.go index 131891b82ddf..dd17733429e5 100644 --- a/mmv1/third_party/terraform/services/lustre/resource_lustre_instance_test.go +++ b/mmv1/third_party/terraform/services/lustre/resource_lustre_instance_test.go @@ -7,13 +7,16 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/lustre" ) func TestAccLustreInstance_withMaintenancePolicy(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), } @@ -93,7 +96,7 @@ func TestAccLustreInstance_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), } @@ -164,7 +167,7 @@ func TestAccLustreInstance_withAccessRulesOptions(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), } @@ -279,9 +282,9 @@ func TestAccLustreInstance_withKmsKey(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), - "kms": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "kms": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -371,7 +374,7 @@ func TestAccLustreInstance_withPlacementPolicy(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), } @@ -434,7 +437,7 @@ func TestAccLustreInstance_dynamicTier(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedTestNetwork(t, "default-vpc"), + "network_name": tpgcompute.BootstrapSharedTestNetwork(t, "default-vpc"), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_acl_test.go b/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_acl_test.go index b9dd9fc7a058..1eb09c090912 100644 --- a/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_acl_test.go +++ b/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_acl_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/managedkafka" ) func TestAccManagedKafkaAcl_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_cluster_test.go b/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_cluster_test.go index a597c6b90515..63cff1ad67d1 100644 --- a/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_cluster_test.go +++ b/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_cluster_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/managedkafka" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" ) func TestAccManagedKafkaCluster_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_topic_test.go b/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_topic_test.go index 2723b5acfbf9..4fea5edba9f4 100644 --- a/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_topic_test.go +++ b/mmv1/third_party/terraform/services/managedkafka/resource_managed_kafka_topic_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/managedkafka" ) func TestAccManagedKafkaTopic_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/memcache/data_source_memcache_instance_test.go b/mmv1/third_party/terraform/services/memcache/data_source_memcache_instance_test.go index 2d6e73f3f19f..660132fc4514 100644 --- a/mmv1/third_party/terraform/services/memcache/data_source_memcache_instance_test.go +++ b/mmv1/third_party/terraform/services/memcache/data_source_memcache_instance_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/memcache" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccMemcacheInstanceDatasourceConfig(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/memcache/resource_memcache_instance_test.go b/mmv1/third_party/terraform/services/memcache/resource_memcache_instance_test.go index b8d1c900954d..e467ef4773ac 100644 --- a/mmv1/third_party/terraform/services/memcache/resource_memcache_instance_test.go +++ b/mmv1/third_party/terraform/services/memcache/resource_memcache_instance_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/memcache" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccMemcacheInstance_update(t *testing.T) { @@ -14,7 +16,7 @@ func TestAccMemcacheInstance_update(t *testing.T) { prefix := fmt.Sprintf("%d", acctest.RandInt(t)) name := fmt.Sprintf("tf-test-%s", prefix) - network := acctest.BootstrapSharedServiceNetworkingConnection(t, "memcache-instance-update-1") + network := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "memcache-instance-update-1") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -104,7 +106,7 @@ func TestAccMemcacheInstance_deletionprotection(t *testing.T) { prefix := fmt.Sprintf("%d", acctest.RandInt(t)) name := fmt.Sprintf("tf-test-%s", prefix) - network := acctest.BootstrapSharedServiceNetworkingConnection(t, "memcache-instance-update-1") + network := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "memcache-instance-update-1") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/memorystore/data_source_memorystore_instance_test.go b/mmv1/third_party/terraform/services/memorystore/data_source_memorystore_instance_test.go index ac36d32b96cb..503fae67c4ce 100644 --- a/mmv1/third_party/terraform/services/memorystore/data_source_memorystore_instance_test.go +++ b/mmv1/third_party/terraform/services/memorystore/data_source_memorystore_instance_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/memorystore" ) func TestAccMemorystoreInstanceDatasourceConfig(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/memorystore/resource_memorystore_instance_test.go b/mmv1/third_party/terraform/services/memorystore/resource_memorystore_instance_test.go index d054e31ba60b..fde29b10eeea 100644 --- a/mmv1/third_party/terraform/services/memorystore/resource_memorystore_instance_test.go +++ b/mmv1/third_party/terraform/services/memorystore/resource_memorystore_instance_test.go @@ -10,7 +10,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/services/memorystore" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_group_test.go b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_group_test.go index 856ef0486371..93b4e674b120 100644 --- a/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_group_test.go +++ b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_group_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/migrationcenter" ) func TestAccMigrationCenterGroup_migrationGroupUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_preference_set_test.go b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_preference_set_test.go index 96d80b6620fd..587a1768e41f 100644 --- a/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_preference_set_test.go +++ b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_preference_set_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/migrationcenter" ) func TestAccMigrationCenterPreferenceSet_preferenceSetUpdate(t *testing.T) { @@ -29,6 +30,15 @@ func TestAccMigrationCenterPreferenceSet_preferenceSetUpdate(t *testing.T) { ImportStateVerify: true, ImportStateVerifyIgnore: []string{"location", "preference_set_id"}, }, + { + Config: testAccMigrationCenterPreferenceSet_preferenceSetUpdate(context), + }, + { + ResourceName: "google_migration_center_preference_set.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "preference_set_id"}, + }, }, }) } @@ -64,7 +74,9 @@ resource "google_migration_center_preference_set" "default" { } sizing_optimization_strategy = "SIZING_OPTIMIZATION_STRATEGY_MODERATE" commitment_plan = "COMMITMENT_PLAN_ONE_YEAR" - preferred_regions = ["us-central1"] + region_preferences { + preferred_regions = ["us-central1"] + } } } `, context) diff --git a/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_settings_test.go b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_settings_test.go new file mode 100644 index 000000000000..22c758569b86 --- /dev/null +++ b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_settings_test.go @@ -0,0 +1,149 @@ +package migrationcenter_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/migrationcenter" +) + +func TestAccMigrationCenterSettings_settingsUpdate(t *testing.T) { + t.Parallel() + + randomSuffix := acctest.RandString(t, 10) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: testAccMigrationCenterSettings_settingsStart(randomSuffix), + }, + { + ResourceName: "google_migration_center_settings.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location"}, + }, + { + Config: testAccMigrationCenterSettings_settingsUpdateFalse(randomSuffix), + }, + { + ResourceName: "google_migration_center_settings.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location"}, + }, + { + Config: testAccMigrationCenterSettings_settingsUpdateTrue(randomSuffix), + }, + { + ResourceName: "google_migration_center_settings.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location"}, + }, + { + Config: testAccMigrationCenterSettings_settingsUpdateCleanup(randomSuffix), + }, + }, + }) +} + +func testAccMigrationCenterSettings_settingsStart(randomSuffix string) string { + return fmt.Sprintf(` +resource "google_migration_center_settings" "default" { + location = "us-central1" + disable_cloud_logging = true + preference_set = google_migration_center_preference_set.default.id +} + +resource "google_migration_center_preference_set" "default" { + location = "us-central1" + preference_set_id = "tf-test-pref-set-settings-%s" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + virtual_machine_preferences { + vmware_engine_preferences { + cpu_overcommit_ratio = 1.5 + } + sizing_optimization_strategy = "SIZING_OPTIMIZATION_STRATEGY_SAME_AS_SOURCE" + target_product = "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE" + } +} +`, randomSuffix) +} + +func testAccMigrationCenterSettings_settingsUpdateFalse(randomSuffix string) string { + return fmt.Sprintf(` +resource "google_migration_center_settings" "default" { + location = "us-central1" + disable_cloud_logging = false + preference_set = google_migration_center_preference_set.default.id +} + +resource "google_migration_center_preference_set" "default" { + location = "us-central1" + preference_set_id = "tf-test-pref-set-settings-%s" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + virtual_machine_preferences { + vmware_engine_preferences { + cpu_overcommit_ratio = 1.5 + } + sizing_optimization_strategy = "SIZING_OPTIMIZATION_STRATEGY_SAME_AS_SOURCE" + target_product = "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE" + } +} +`, randomSuffix) +} + +func testAccMigrationCenterSettings_settingsUpdateTrue(randomSuffix string) string { + return fmt.Sprintf(` +resource "google_migration_center_settings" "default" { + location = "us-central1" + disable_cloud_logging = true + preference_set = google_migration_center_preference_set.default.id +} + +resource "google_migration_center_preference_set" "default" { + location = "us-central1" + preference_set_id = "tf-test-pref-set-settings-%s" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + virtual_machine_preferences { + vmware_engine_preferences { + cpu_overcommit_ratio = 1.5 + } + sizing_optimization_strategy = "SIZING_OPTIMIZATION_STRATEGY_SAME_AS_SOURCE" + target_product = "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE" + } +} +`, randomSuffix) +} + +func testAccMigrationCenterSettings_settingsUpdateCleanup(randomSuffix string) string { + return fmt.Sprintf(` +resource "google_migration_center_settings" "default" { + location = "us-central1" + disable_cloud_logging = true +} + +resource "google_migration_center_preference_set" "default" { + location = "us-central1" + preference_set_id = "tf-test-pref-set-settings-%s" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + virtual_machine_preferences { + vmware_engine_preferences { + cpu_overcommit_ratio = 1.5 + } + sizing_optimization_strategy = "SIZING_OPTIMIZATION_STRATEGY_SAME_AS_SOURCE" + target_product = "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE" + } +} +`, randomSuffix) +} diff --git a/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_source_test.go b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_source_test.go new file mode 100644 index 000000000000..02b90dd66886 --- /dev/null +++ b/mmv1/third_party/terraform/services/migrationcenter/resource_migration_center_source_test.go @@ -0,0 +1,75 @@ +package migrationcenter_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/migrationcenter" +) + +func TestAccMigrationCenterSource_migrationSourceUpdate(t *testing.T) { + t.Parallel() + + randomSuffix := acctest.RandString(t, 10) + + context := map[string]interface{}{ + "source_id": "tf-test-source-test" + randomSuffix, + "random_suffix": randomSuffix, + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckMigrationCenterSourceDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccMigrationCenterSource_migrationSourceStart(context), + }, + { + ResourceName: "google_migration_center_source.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "source_id"}, + }, + { + Config: testAccMigrationCenterSource_migrationSourceUpdate(context), + }, + { + ResourceName: "google_migration_center_source.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "source_id"}, + }, + }, + }) +} + +func testAccMigrationCenterSource_migrationSourceStart(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_migration_center_source" "default" { + location = "us-central1" + source_id = "%{source_id}" + description = "Terraform integration test description" + display_name = "Terraform integration test display" + priority = 10 + type = "SOURCE_TYPE_CUSTOM" + managed = false +} +`, context) +} + +func testAccMigrationCenterSource_migrationSourceUpdate(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_migration_center_source" "default" { + location = "us-central1" + source_id = "%{source_id}" + description = "Updated Terraform integration test description" + display_name = "Updated integration test display" + priority = 15 + type = "SOURCE_TYPE_CUSTOM" + managed = false +} +`, context) +} diff --git a/mmv1/third_party/terraform/services/modelarmor/resource_model_armor_template_test.go b/mmv1/third_party/terraform/services/modelarmor/resource_model_armor_template_test.go index e9a41f543703..ef369969a865 100644 --- a/mmv1/third_party/terraform/services/modelarmor/resource_model_armor_template_test.go +++ b/mmv1/third_party/terraform/services/modelarmor/resource_model_armor_template_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/modelarmor" ) func TestAccModelArmorTemplate_basic(t *testing.T) { @@ -43,10 +44,10 @@ resource "google_model_armor_template" "template-basic" { location = "%{location}" template_id = "%{templateId}" filter_config { - + } template_metadata { - + } }`, context) } @@ -139,6 +140,105 @@ func testAccModelArmorTemplate_initial(context map[string]interface{}) string { `, context) } +// TestAccModelArmorTemplate_noTemplateMetadataNoDrift verifies that creating +// a template without template_metadata does not cause a permadiff on the next +// plan. Regression test for https://github.com/hashicorp/terraform-provider-google/issues/23565 +func TestAccModelArmorTemplate_noTemplateMetadataNoDrift(t *testing.T) { + t.Parallel() + + templateId := fmt.Sprintf("modelarmor-test-nodrift-%s", acctest.RandString(t, 5)) + + context := map[string]interface{}{ + "location": "us-central1", + "templateId": templateId, + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckModelArmorTemplateDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccModelArmorTemplate_noTemplateMetadata(context), + }, + { + Config: testAccModelArmorTemplate_noTemplateMetadata(context), + PlanOnly: true, + ExpectNonEmptyPlan: false, + }, + }, + }) +} + +func testAccModelArmorTemplate_noTemplateMetadata(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_model_armor_template" "test-no-metadata" { + location = "%{location}" + template_id = "%{templateId}" + filter_config { + rai_settings { + rai_filters { + filter_type = "HATE_SPEECH" + confidence_level = "MEDIUM_AND_ABOVE" + } + } + } +}`, context) +} + +// TestAccModelArmorTemplate_removeTemplateMetadata verifies that updating a +// template to remove template_metadata does not fail with REQUEST_FIELD_MISSING. +// Regression test for https://github.com/hashicorp/terraform-provider-google/issues/23565 +func TestAccModelArmorTemplate_removeTemplateMetadata(t *testing.T) { + t.Parallel() + + templateId := fmt.Sprintf("modelarmor-test-remove-%s", acctest.RandString(t, 5)) + + context := map[string]interface{}{ + "location": "us-central1", + "templateId": templateId, + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckModelArmorTemplateDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccModelArmorTemplate_withTemplateMetadata(context), + }, + { + Config: testAccModelArmorTemplate_noTemplateMetadata(context), + }, + { + Config: testAccModelArmorTemplate_noTemplateMetadata(context), + PlanOnly: true, + ExpectNonEmptyPlan: false, + }, + }, + }) +} + +func testAccModelArmorTemplate_withTemplateMetadata(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_model_armor_template" "test-no-metadata" { + location = "%{location}" + template_id = "%{templateId}" + filter_config { + rai_settings { + rai_filters { + filter_type = "HATE_SPEECH" + confidence_level = "MEDIUM_AND_ABOVE" + } + } + } + template_metadata { + log_template_operations = true + log_sanitize_operations = true + } +}`, context) +} + func testAccModelArmorTemplate_update(context map[string]interface{}) string { return acctest.Nprintf(` resource "google_model_armor_template" "test-resource" { diff --git a/mmv1/third_party/terraform/services/modelarmorglobal/resource_model_armor_floorsetting_test.go b/mmv1/third_party/terraform/services/modelarmorglobal/resource_model_armor_floorsetting_test.go index 26205098df64..9e5a516d142f 100644 --- a/mmv1/third_party/terraform/services/modelarmorglobal/resource_model_armor_floorsetting_test.go +++ b/mmv1/third_party/terraform/services/modelarmorglobal/resource_model_armor_floorsetting_test.go @@ -4,19 +4,19 @@ import ( "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/modelarmorglobal" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccModelArmorGlobalFloorsetting_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "project_id": acctest.BootstrapProject(t, "tf-boot-magf-", envvar.GetTestBillingAccountFromEnv(t), []string{"modelarmor.googleapis.com"}).ProjectId, + "project_id": resourcemanager.BootstrapProject(t, "tf-boot-magf-", envvar.GetTestBillingAccountFromEnv(t), []string{"modelarmor.googleapis.com"}).ProjectId, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel.go b/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel.go index ea35fa4892e5..1a1d2911cd00 100644 --- a/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel.go +++ b/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel.go @@ -33,7 +33,7 @@ func dataSourceMonitoringNotificationChannelRead(d *schema.ResourceData, meta in return err } - url, err := tpgresource.ReplaceVars(d, config, "{{MonitoringBasePath}}v3/projects/{{project}}/notificationChannels") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"v3/projects/{{project}}/notificationChannels") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel_test.go b/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel_test.go index f8a52ffd9782..b7f6c3ebe6b2 100644 --- a/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel_test.go +++ b/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_notification_channel_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_service.go b/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_service.go index 0133a31743b5..713b66e98414 100644 --- a/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_service.go +++ b/mmv1/third_party/terraform/services/monitoring/data_source_monitoring_service.go @@ -54,7 +54,7 @@ func dataSourceMonitoringServiceTypeReadFromList(listFilter string, typeStateSet return err } - listUrlTmpl := "{{MonitoringBasePath}}v3/projects/{{project}}/services?filter=" + neturl.QueryEscape(filters) + listUrlTmpl := transport_tpg.BaseUrl(Product, config) + "v3/projects/{{project}}/services?filter=" + neturl.QueryEscape(filters) url, err := tpgresource.ReplaceVars(d, config, listUrlTmpl) if err != nil { return err diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_alert_policy_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_alert_policy_test.go index 832794319099..7dffb3dc4737 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_alert_policy_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_alert_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard.go index ca5bbcd94e7e..36e47f32f5a6 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard.go @@ -76,6 +76,7 @@ func ResourceMonitoringDashboard() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -97,6 +98,9 @@ func ResourceMonitoringDashboard() *schema.Resource { ForceNew: true, Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -119,7 +123,7 @@ func resourceMonitoringDashboardCreate(d *schema.ResourceData, meta interface{}) return err } - url, err := tpgresource.ReplaceVars(d, config, "{{MonitoringBasePath}}v1/projects/{{project}}/dashboards") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"v1/projects/{{project}}/dashboards") if err != nil { return err } @@ -184,10 +188,19 @@ func resourceMonitoringDashboardRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error reading Dashboard: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceMonitoringDashboardUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceMonitoringDashboard) { + return ResourceMonitoringDashboard().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -230,6 +243,13 @@ func resourceMonitoringDashboardUpdate(d *schema.ResourceData, meta interface{}) } func resourceMonitoringDashboardDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_meta.yaml b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_meta.yaml index de65faeba1cd..bd3a86441bab 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_meta.yaml +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_meta.yaml @@ -8,3 +8,5 @@ fields: api_field: '*' json: true - field: 'project' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_test.go index aaefae43bc7e..d8655690e42d 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_dashboard_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/monitoring" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -142,7 +143,7 @@ func testAccCheckMonitoringDashboardDestroyProducer(t *testing.T) func(s *terraf config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{MonitoringBasePath}}v1/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(monitoring.Product, config)+"v1/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_group_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_group_test.go index 777c3d708d3b..d40fbdfe7fd2 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_group_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_group_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" ) func TestAccMonitoringGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_metric_descriptor_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_metric_descriptor_test.go index 55f0f94b5c0b..0122e2acb9b8 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_metric_descriptor_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_metric_descriptor_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" ) func TestAccMonitoringMetricDescriptor_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_monitored_project_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_monitored_project_test.go index 15f9d8183d54..c1090b2c52e6 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_monitored_project_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_monitored_project_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/monitoring" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_notification_channel_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_notification_channel_test.go index e83b82d3f1d3..1de47d995230 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_notification_channel_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_notification_channel_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" ) func TestAccMonitoringNotificationChannel_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_service_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_service_test.go index a3a3eb1e36ca..2929d49c2b55 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_service_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_service_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" ) func TestAccMonitoringService_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_slo_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_slo_test.go index 689c2610ab0c..b1a69a23d502 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_slo_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_slo_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" ) func setTestCheckMonitoringSloId(res string, sloId *string) resource.TestCheckFunc { diff --git a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_uptime_check_config_test.go b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_uptime_check_config_test.go index 9533dcb2a002..02a079e146b4 100644 --- a/mmv1/third_party/terraform/services/monitoring/resource_monitoring_uptime_check_config_test.go +++ b/mmv1/third_party/terraform/services/monitoring/resource_monitoring_uptime_check_config_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/monitoring" ) func TestAccMonitoringUptimeCheckConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_active_directory_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_active_directory_test.go index a22b767b9008..4d24c2a06f7d 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_active_directory_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_active_directory_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" ) func TestAccNetappActiveDirectory_activeDirectory_FullUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_policy_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_policy_test.go index 5d28965b2afd..e615852c1b98 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_policy_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_policy_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" ) func TestAccNetappBackupPolicy_NetappBackupPolicyFullExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_test.go index afcc9c90f58c..82e28ad82507 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_test.go @@ -5,11 +5,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccNetappBackup_NetappBackupFull_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -81,15 +83,15 @@ resource "google_netapp_backup_vault" "default" { } resource "google_netapp_volume_snapshot" "default" { - depends_on = [google_netapp_volume.default] - location = google_netapp_volume.default.location - volume_name = google_netapp_volume.default.name - description = "This is a test description" - name = "testvolumesnap%{random_suffix}" - labels = { - key= "test" - value= "snapshot" - } + depends_on = [google_netapp_volume.default] + location = google_netapp_volume.default.location + volume_name = google_netapp_volume.default.name + description = "This is a test description" + name = "testvolumesnap%{random_suffix}" + labels = { + key= "test" + value= "snapshot" + } } resource "google_netapp_backup" "test_backup" { @@ -100,8 +102,8 @@ resource "google_netapp_backup" "test_backup" { vault_name = google_netapp_backup_vault.default.name source_snapshot = google_netapp_volume_snapshot.default.id labels = { - key= "test" - value= "backup" + key= "test" + value= "backup" } } `, context) @@ -145,15 +147,15 @@ resource "google_netapp_backup_vault" "default" { } resource "google_netapp_volume_snapshot" "default" { - depends_on = [google_netapp_volume.default] - location = google_netapp_volume.default.location - volume_name = google_netapp_volume.default.name - description = "This is a test description" - name = "testvolumesnap%{random_suffix}" - labels = { - key= "test" - value= "snapshot" - } + depends_on = [google_netapp_volume.default] + location = google_netapp_volume.default.location + volume_name = google_netapp_volume.default.name + description = "This is a test description" + name = "testvolumesnap%{random_suffix}" + labels = { + key= "test" + value= "snapshot" + } } resource "google_netapp_backup" "test_backup" { @@ -164,8 +166,8 @@ resource "google_netapp_backup" "test_backup" { vault_name = google_netapp_backup_vault.default.name source_snapshot = google_netapp_volume_snapshot.default.id labels = { - key= "test_update" - value= "backup_update" + key= "test_update" + value= "backup_update" } } `, context) @@ -173,7 +175,7 @@ resource "google_netapp_backup" "test_backup" { func TestAccNetappBackup_NetappFlexBackup(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -266,7 +268,7 @@ resource "google_netapp_backup" "test_backup" { func TestAccNetappBackup_NetappIntegratedBackup(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -353,7 +355,7 @@ resource "google_netapp_backup" "test_backup" { func TestAccNetappBackup_NetappImmutableBackup(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_vault_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_vault_test.go index 03961ff3ddd0..49f6c52f40e3 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_vault_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_backup_vault_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/netapp" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -127,7 +128,7 @@ func testAccCheckNetappBackupVaultDestroyProducer(t *testing.T) func(s *terrafor config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{NetappBasePath}}projects/{{project}}/locations/{{location}}/backupVaults/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(netapp.Product, config)+"projects/{{project}}/locations/{{location}}/backupVaults/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_host_group_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_host_group_test.go index 475e88a6786d..8a930b96667e 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_host_group_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_host_group_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" ) func TestAccNetappHostGroup_HostGroupCreateExample_Update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_kmsconfig_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_kmsconfig_test.go index 88854c31921f..e565c89bd518 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_kmsconfig_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_kmsconfig_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" ) func TestAccNetappkmsconfig_kmsConfigCreateExample_Update(t *testing.T) { @@ -13,7 +15,7 @@ func TestAccNetappkmsconfig_kmsConfigCreateExample_Update(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-bootstrap-netapp-kmsconfig-key2").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-bootstrap-netapp-kmsconfig-key2").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_storage_pool_test.go.tmpl b/mmv1/third_party/terraform/services/netapp/resource_netapp_storage_pool_test.go.tmpl index 2c7df3c27bcd..c01f143f9b43 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_storage_pool_test.go.tmpl +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_storage_pool_test.go.tmpl @@ -7,13 +7,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccNetappStoragePool_storagePoolCreateExample_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -97,7 +99,7 @@ resource "google_netapp_storage_pool" "test_pool" { func TestAccNetappStoragePool_autoTieredStoragePoolCreateExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -183,7 +185,7 @@ resource "google_netapp_storage_pool" "test_pool" { func TestAccNetappStoragePool_flexAutoTierStoragePoolCreateExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-2", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-2", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -318,7 +320,7 @@ resource "google_netapp_storage_pool" "test_pool" { func TestAccNetappStoragePool_FlexRegionalStoragePoolCreateExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -441,7 +443,7 @@ data "google_compute_network" "default" { func TestAccNetappStoragePool_FlexRegionalStoragePoolNoZone(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -489,7 +491,7 @@ data "google_compute_network" "default" { func TestAccNetappStoragePool_customPerformanceStoragePoolCreateExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -562,7 +564,7 @@ data "google_compute_network" "default" { func TestAccNetappStoragePool_customPerformanceEnabledStoragePoolCreateExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -634,7 +636,7 @@ data "google_compute_network" "default" { func TestAccNetappStoragePool_ManualQos(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -732,7 +734,7 @@ func TestAccNetappStoragePool_unifiedStoragePoolCreate(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -813,7 +815,7 @@ func TestAccNetappStoragePool_ontapMode(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -894,7 +896,7 @@ resource "google_netapp_storage_pool" "test_pool" { func TestAccNetappStoragePool_ScaleType(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -977,7 +979,7 @@ data "google_compute_network" "default" { {{- if ne $.TargetVersionName "ga" }} func TestAccNetappStoragePool_ScaleTier(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_quotaRule_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_quotaRule_test.go index 2679d3053f51..51d36fa5130c 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_quotaRule_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_quotaRule_test.go @@ -6,13 +6,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccNetappVolumeQuotaRule_netappVolumeQuotaRuleBasicExample_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_replication_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_replication_test.go index 82a6a3abc117..085236cfd463 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_replication_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_replication_test.go @@ -6,13 +6,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccNetappVolumeReplication_NetappVolumeReplicationCreateExample_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_snapshot_test.go b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_snapshot_test.go index 80025abd4c39..2e8c44f69519 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_snapshot_test.go +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_snapshot_test.go @@ -6,13 +6,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccNetappVolumeSnapshot_volumeSnapshotCreateExample_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_test.go.tmpl b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_test.go.tmpl index bceef1810526..d634a23099b9 100644 --- a/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_test.go.tmpl +++ b/mmv1/third_party/terraform/services/netapp/resource_netapp_volume_test.go.tmpl @@ -12,13 +12,14 @@ import ( "github.com/hashicorp/terraform-provider-google/google/services/netapp" "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) func TestAccNetappVolume_NetappVolumeBasicExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -659,7 +660,7 @@ func testAccNetappVolume_volumeBasicExample_cleanupScheduledBackup(t *testing.T, func TestAccNetappVolume_autoTieredNetappVolume_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -760,7 +761,7 @@ func testAccNetappVolume_autoTieredVolume_custom(context map[string]interface{}) func TestAccNetappVolume_flexAutoTierNetappVolume_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -864,7 +865,7 @@ func testAccNetappVolume_flexAutoTierVolume_update(context map[string]interface{ func TestAccNetappBlockVolume_NetappVolumeBasicExample_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -982,7 +983,7 @@ func testAccNetappBlockVolume_volumeBasicExample_update(context map[string]inter func TestAccNetappVolume_volumeExportPolicyWithSquashMode(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } acctest.VcrTest(t, resource.TestCase{ @@ -1329,7 +1330,7 @@ func testAccNetappVolume_volumeExportPolicyWithSquashMode_switchMutipleExportRul func TestAccNetappVolume_NetappVolumeNfsv4Example_update(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -1472,7 +1473,7 @@ func TestSuppressHasRootAccessDiff(t *testing.T) { func TestAccNetappVolume_LargeCapacityScaleTypeConfig(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -1574,7 +1575,7 @@ func testAccNetappVolume_LargeCapacityScaleTypeConfig_updated(context map[string {{- if ne $.TargetVersionName "ga" }} func TestAccNetappVolume_LargeCapacityScaleTierConfig(t *testing.T) { context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "gcnv-network-config-3", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_destination_test.go b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_destination_test.go index 56020b412efb..daeef1a0703f 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_destination_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_destination_test.go @@ -28,6 +28,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_gateway_advertised_route_test.go.tmpl b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_gateway_advertised_route_test.go.tmpl index 762eda7171f9..9cf415e8fad7 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_gateway_advertised_route_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_gateway_advertised_route_test.go.tmpl @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/plancheck" ) diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_group_test.go b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_group_test.go index 68b531193d0c..eac360f4ef56 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_group_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_group_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" ) func TestAccNetworkConnectivityGroup_BasicGroup(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_hub_test.go b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_hub_test.go index 5267c481c13f..a4ce95caf66c 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_hub_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_hub_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" ) func TestAccNetworkConnectivityHub_BasicHubLongForm(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_multicloud_data_transfer_config_test.go b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_multicloud_data_transfer_config_test.go index e7a8984cbd34..6b3a841d8e34 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_multicloud_data_transfer_config_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_multicloud_data_transfer_config_test.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_spoke_test.go b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_spoke_test.go index 357dc68e0593..b79da5168f06 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_spoke_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_spoke_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" ) func TestAccNetworkConnectivitySpoke_LinkedVPCNetworkHandWritten(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_transport_test.go.tmpl b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_transport_test.go similarity index 84% rename from mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_transport_test.go.tmpl rename to mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_transport_test.go index 0b576064ce74..a045ce87c039 100644 --- a/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_transport_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkconnectivity/resource_network_connectivity_transport_test.go @@ -1,10 +1,5 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - package networkconnectivity_test -{{- if ne $.TargetVersionName "ga" }} - import ( "fmt" "log" @@ -18,6 +13,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -47,7 +44,7 @@ func TestAccNetworkConnectivityTransport_networkConnectivityTransportBasicExampl acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), CheckDestroy: testAccCheckNetworkConnectivityTransportDestroyProducer(t), Steps: []resource.TestStep{ { @@ -74,22 +71,18 @@ func TestAccNetworkConnectivityTransport_networkConnectivityTransportBasicExampl func testAccNetworkConnectivityTransport_networkConnectivityTransportBasicExample_basic(context map[string]interface{}) string { return acctest.Nprintf(` -data "google_project" "project" { - provider = google-beta -} +data "google_project" "project" {} resource "google_compute_network" "primary-network" { - provider = google-beta name = "tf-test-my-vpc-network%{random_suffix}" auto_create_subnetworks = false } resource "google_network_connectivity_transport" "primary" { - provider = google-beta name = "tf-test-basic-transport%{random_suffix}" region = "us-east4" description = "A sample transport" - remote_profile = "https://networkconnectivity.googleapis.com/v1beta/${data.google_project.project.id}/locations/us-east4/remoteTransportProfiles/aws-us-east-1" + remote_profile = "https://networkconnectivity.googleapis.com/v1/${data.google_project.project.id}/locations/us-east4/remoteTransportProfiles/aws-us-east-1" network = google_compute_network.primary-network.name bandwidth = "BPS_1G" remote_account_id = "123" @@ -102,22 +95,18 @@ resource "google_network_connectivity_transport" "primary" { func testAccNetworkConnectivityTransport_networkConnectivityTransportBasicExample_update(context map[string]interface{}) string { return acctest.Nprintf(` -data "google_project" "project" { - provider = google-beta -} +data "google_project" "project" {} resource "google_compute_network" "primary-network" { - provider = google-beta name = "tf-test-my-vpc-network%{random_suffix}" auto_create_subnetworks = false } resource "google_network_connectivity_transport" "primary" { - provider = google-beta name = "tf-test-basic-transport%{random_suffix}" region = "us-east4" description = "New description" - remote_profile = "https://networkconnectivity.googleapis.com/v1beta/${data.google_project.project.id}/locations/us-east4/remoteTransportProfiles/aws-us-east-1" + remote_profile = "https://networkconnectivity.googleapis.com/v1/${data.google_project.project.id}/locations/us-east4/remoteTransportProfiles/aws-us-east-1" network = google_compute_network.primary-network.name bandwidth = "BPS_1G" remote_account_id = "123" @@ -127,5 +116,3 @@ resource "google_network_connectivity_transport" "primary" { } `, context) } - -{{- end }} diff --git a/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_internal_range_test.go b/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_internal_range_test.go index 96dbdbeca9e6..198af66ac3f1 100644 --- a/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_internal_range_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_internal_range_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" ) func TestAccNetworkConnectivityInternalRange_networkConnectivityInternalRangesBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_service_connection_policies_test.go b/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_service_connection_policies_test.go index 86061740b753..7038e56a88b0 100644 --- a/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_service_connection_policies_test.go +++ b/mmv1/third_party/terraform/services/networkconnectivityv1/resource_network_connectivity_service_connection_policies_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" ) func TestAccNetworkConnectivityServiceConnectionPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run.go b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run.go index 07c6ad8fbe44..e372cd5d801e 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run.go +++ b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run.go @@ -160,7 +160,7 @@ func dataSourceGoogleNetworkManagementTestRun(d *schema.ResourceData, meta inter obj["name"] = nameProp } - url, err := tpgresource.ReplaceVars(d, config, "{{NetworkManagementBasePath}}projects/{{project}}/locations/global/connectivityTests/{{name}}:rerun") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/global/connectivityTests/{{name}}:rerun") if err != nil { return err } @@ -223,7 +223,7 @@ func dataSourceGoogleNetworkManagementTestRunRead(d *schema.ResourceData, meta i return err } - url, err := tpgresource.ReplaceVars(d, config, "{{NetworkManagementBasePath}}projects/{{project}}/locations/global/connectivityTests/{{name}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/global/connectivityTests/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run_test.go b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run_test.go index e289e7e35975..e0fdaa9ea374 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run_test.go +++ b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_test_run_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkmanagement" ) func TestAccNetworkManagementConnectivityTestRun_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests.go b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests.go index 8bfcea1c320b..c8b368149f89 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests.go +++ b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests.go @@ -44,7 +44,7 @@ func dataSourceGoogleNetworkManagementConnectivityTests(d *schema.ResourceData, return err } - url, err := tpgresource.ReplaceVars(d, config, "{{NetworkManagementBasePath}}projects/{{project}}/locations/global/connectivityTests") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/global/connectivityTests") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests_test.go b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests_test.go index a75e3452e821..b51d41c7209f 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests_test.go +++ b/mmv1/third_party/terraform/services/networkmanagement/data_source_network_management_connectivity_tests_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkmanagement" ) func TestAccNetworkManagementConnectivityTests_basic(t *testing.T) { @@ -34,6 +36,7 @@ func TestAccNetworkManagementConnectivityTests_basic(t *testing.T) { "project": {}, "terraform_labels.%": {}, "terraform_labels.goog-terraform-provisioned": {}, + "deletion_policy": {}, }, ), ), @@ -49,6 +52,7 @@ func TestAccNetworkManagementConnectivityTests_basic(t *testing.T) { "project": {}, "terraform_labels.%": {}, "terraform_labels.goog-terraform-provisioned": {}, + "deletion_policy": {}, }, ), ), diff --git a/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_connectivity_test_resource_test.go b/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_connectivity_test_resource_test.go index 03589df2e11d..771a670c018c 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_connectivity_test_resource_test.go +++ b/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_connectivity_test_resource_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkmanagement" ) func TestAccNetworkManagementConnectivityTest_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_org_vpc_flow_logs_config_test.go b/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_org_vpc_flow_logs_config_test.go index 9b9b5aa4c9d8..492e7cd7859b 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_org_vpc_flow_logs_config_test.go +++ b/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_org_vpc_flow_logs_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkmanagement" ) func TestAccNetworkManagementOrganizationVpcFlowLogsConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go b/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go index fca69f37aa53..3bde7fcc5c7c 100644 --- a/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go +++ b/mmv1/third_party/terraform/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkmanagement" ) func TestAccNetworkManagementVpcFlowLogsConfig_updateInterconnect(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups.go b/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups.go index 40d0e34a437b..3b036e59ed52 100644 --- a/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups.go +++ b/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups.go @@ -82,7 +82,7 @@ func dataSourceNetworkSecurityAddressGroups(d *schema.ResourceData, meta interfa return err } - url, err = tpgresource.ReplaceVars(d, config, "{{NetworkSecurityBasePath}}projects/{{project}}/locations/{{location}}/addressGroups") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/addressGroups") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups_test.go b/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups_test.go index 0cc7f8291e6b..d3b6e26aedf2 100644 --- a/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/data_source_google_network_security_address_groups_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccDataSourceNetworkSecurityAddressGroups_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_address_group_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_address_group_test.go index 71df8852854b..73c0ecdd8b62 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_address_group_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_address_group_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityAddressGroups_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authorization_policy_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authorization_policy_test.go.tmpl index 3baa661bdd4f..e6ab620f49a4 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authorization_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authorization_policy_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityAuthorizationPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authz_policy_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authz_policy_test.go index 39ce9578fcc6..d2994bbb68e4 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authz_policy_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_authz_policy_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkSecurityAuthzPolicy_networkServicesAuthzPolicyHttpRules(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_backend_authentication_config_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_backend_authentication_config_test.go index 4c79cbc74ce7..02c2017be5cf 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_backend_authentication_config_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_backend_authentication_config_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityBackendAuthenticationConfig_networkSecurityBackendAuthenticationConfigFullExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_client_tls_policy_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_client_tls_policy_test.go.tmpl index e22f5dbeeb99..c912fcddb288 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_client_tls_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_client_tls_policy_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityClientTlsPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_dns_threat_detector_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_dns_threat_detector_test.go.tmpl index 2736d45df352..4df06771980e 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_dns_threat_detector_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_dns_threat_detector_test.go.tmpl @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go.tmpl index 7e4f7a699941..e6b7440c3e17 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go.tmpl @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "github.com/hashicorp/terraform-provider-google/google/envvar" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_test.go.tmpl index 5f9dab89ccd1..52bf0a4c084b 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_firewall_endpoint_test.go.tmpl @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" "github.com/hashicorp/terraform-provider-google/google/envvar" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/terraform-provider-google/google/tpgresource" diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_rule_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_rule_test.go index 22823730a924..f38dd9426ffd 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_rule_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_rule_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_test.go index 2582428544f1..4a978dc8f883 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_gateway_security_policy_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_group_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_group_test.go index 614a06f28b81..4a4c9e057019 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_group_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_group_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityInterceptDeploymentGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_test.go index 932d25f63a97..4a6599736df7 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_deployment_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityInterceptDeployment_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_association_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_association_test.go index 921ca4406600..161debcb5381 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_association_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_association_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityInterceptEndpointGroupAssociation_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_test.go index de889329df01..cb98509fdbfb 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_intercept_endpoint_group_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityInterceptEndpointGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_group_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_group_test.go index b8608d242e5c..fe4abbef71c5 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_group_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_group_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityMirroringDeploymentGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_test.go index 7fe81923e5f3..2e13c4cd3cfa 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_deployment_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityMirroringDeployment_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_association_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_association_test.go index 521fd6b69ebc..aef7ef744c27 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_association_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_association_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityMirroringEndpointGroupAssociation_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_test.go index 1c44e830a42c..fc15b6a1a72f 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_group_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityMirroringEndpointGroup_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_test.go index a32f11389cc5..f9781c595af6 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_mirroring_endpoint_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityMirroringEndpoint_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_group_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_group_test.go index cdeeb227b870..570d7dc2f08f 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_group_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_group_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecuritySecurityProfileGroups_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_test.go index 6d1a715909dc..3f8bd331c185 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_security_profile_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecuritySecurityProfiles_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_server_tls_policy_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_server_tls_policy_test.go.tmpl index 37eb9d94c01b..b7bc4552e7dc 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_server_tls_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_server_tls_policy_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" ) func TestAccNetworkSecurityServerTlsPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_tls_inspection_policy_test.go.tmpl b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_tls_inspection_policy_test.go.tmpl index 68f5629089b9..2654289f1151 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_tls_inspection_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_tls_inspection_policy_test.go.tmpl @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_url_lists_test.go b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_url_lists_test.go index f383b77b01e7..f23fafadef89 100644 --- a/mmv1/third_party/terraform/services/networksecurity/resource_network_security_url_lists_test.go +++ b/mmv1/third_party/terraform/services/networksecurity/resource_network_security_url_lists_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_agent_gateway_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_agent_gateway_test.go.tmpl index 5f22ba605f16..407d63f53258 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_agent_gateway_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_agent_gateway_test.go.tmpl @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_authz_extension_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_authz_extension_test.go index c0ffd27bfca2..9353aaeb15aa 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_authz_extension_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_authz_extension_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesAuthzExtension_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_keyset_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_keyset_test.go index d6dd406b5517..e12960e08ddb 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_keyset_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_keyset_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesEdgeCacheKeyset_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_origin_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_origin_test.go index 32de5a3a8d93..eb91105b1d0c 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_origin_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_origin_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesEdgeCacheOrigin_updateAndImport(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_service_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_service_test.go index 269b10fb2cf6..447dc8a1e2df 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_service_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_edge_cache_service_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccNetworkServicesEdgeCacheService_updateAndImport(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_endpoint_policy_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_endpoint_policy_test.go.tmpl index 1113312304aa..c61eb7396d60 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_endpoint_policy_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_endpoint_policy_test.go.tmpl @@ -4,6 +4,7 @@ package networkservices_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_gateway_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_gateway_test.go index 5b55d511543f..ff726d693ad2 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_gateway_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_gateway_test.go @@ -5,6 +5,12 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/certificatemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivity" + _ "github.com/hashicorp/terraform-provider-google/google/services/networksecurity" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_grpc_route_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_grpc_route_test.go.tmpl index 7176c2eea67e..76dd4c6bf643 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_grpc_route_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_grpc_route_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesGrpcRoute_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_http_route_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_http_route_test.go.tmpl index a4f80d3747d1..b6a83a28a511 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_http_route_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_http_route_test.go.tmpl @@ -4,6 +4,7 @@ package networkservices_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_edge_extension_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_edge_extension_test.go index 95afe04c87b0..7622d15dabc7 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_edge_extension_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_edge_extension_test.go @@ -11,6 +11,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -363,7 +365,7 @@ func testAccCheckNetworkServicesLbEdgeExtensionDestroyProducer(t *testing.T) fun config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{NetworkServicesBasePath}}projects/{{project}}/locations/{{location}}/lbEdgeExtensions/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(networkservices.Product, config)+"projects/{{project}}/locations/{{location}}/lbEdgeExtensions/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_route_extension_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_route_extension_test.go index 2d440d990139..c29dbf6bef77 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_route_extension_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_route_extension_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesLbRouteExtension_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_traffic_extension_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_traffic_extension_test.go index 36356a0faac6..940d1fc522f2 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_traffic_extension_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_lb_traffic_extension_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesLbTrafficExtension_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_mesh_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_mesh_test.go.tmpl index 98a0b1aa1ecf..628489c721d9 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_mesh_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_mesh_test.go.tmpl @@ -4,6 +4,7 @@ package networkservices_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_consumer_association_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_consumer_association_test.go index 1adcff911be3..bf6be8288319 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_consumer_association_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_consumer_association_test.go @@ -4,6 +4,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_activation_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_activation_test.go index f83ade2da6e2..0cc88913272d 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_activation_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_activation_test.go @@ -4,6 +4,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_group_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_group_test.go index 6dcb9d0c822d..6b4def04d0d0 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_group_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_group_test.go @@ -4,6 +4,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_test.go index ce452e5fcbbf..00fb3199fb52 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_domain_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesMulticastDomain_networkServicesMulticastDomainUpdateExample(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_consumer_activation_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_consumer_activation_test.go index 9efefa80bad5..d5735addafdc 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_consumer_activation_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_consumer_activation_test.go @@ -4,6 +4,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_producer_activation_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_producer_activation_test.go index 3bca1eb4c111..17d6e0c86a50 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_producer_activation_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_producer_activation_test.go @@ -4,6 +4,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_activation_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_activation_test.go index 7b778d2b6d74..067a2c913aab 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_activation_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_activation_test.go @@ -4,6 +4,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_test.go index 31a73834c055..f8fbe5e59f57 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_group_range_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" ) func TestAccNetworkServicesMulticastGroupRange_networkServicesMulticastGroupRangeUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_producer_association_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_producer_association_test.go index c7a9b39fdb30..064e9dd8d330 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_producer_association_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_multicast_producer_association_test.go @@ -4,6 +4,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_service_lb_policies_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_service_lb_policies_test.go.tmpl index bc0b35a6bcc0..283ad563dc6d 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_service_lb_policies_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_service_lb_policies_test.go.tmpl @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_tcp_route_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_tcp_route_test.go.tmpl index c968daa11159..e053b5f4a31c 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_tcp_route_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_tcp_route_test.go.tmpl @@ -4,6 +4,8 @@ package networkservices_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_tls_route_test.go.tmpl b/mmv1/third_party/terraform/services/networkservices/resource_network_services_tls_route_test.go.tmpl index 1cc894f7aa3d..efb20dfca6ec 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_tls_route_test.go.tmpl +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_tls_route_test.go.tmpl @@ -4,6 +4,8 @@ package networkservices_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkservices" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/networkservices/resource_network_services_wasm_plugin_test.go b/mmv1/third_party/terraform/services/networkservices/resource_network_services_wasm_plugin_test.go index 7f745a3fa23f..6273e29b1c78 100644 --- a/mmv1/third_party/terraform/services/networkservices/resource_network_services_wasm_plugin_test.go +++ b/mmv1/third_party/terraform/services/networkservices/resource_network_services_wasm_plugin_test.go @@ -18,6 +18,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" + "github.com/hashicorp/terraform-provider-google/google/services/networkservices" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "google.golang.org/api/googleapi" @@ -668,7 +670,7 @@ func testAccCheckNetworkServicesWasmPluginDestroyProducer(t *testing.T) func(s * config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{NetworkServicesBasePath}}projects/{{project}}/locations/{{location}}/wasmPlugins/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(networkservices.Product, config)+"projects/{{project}}/locations/{{location}}/wasmPlugins/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/notebooks/resource_notebooks_environment_test.go.tmpl b/mmv1/third_party/terraform/services/notebooks/resource_notebooks_environment_test.go.tmpl index cf60803086f3..03c05aa75b94 100644 --- a/mmv1/third_party/terraform/services/notebooks/resource_notebooks_environment_test.go.tmpl +++ b/mmv1/third_party/terraform/services/notebooks/resource_notebooks_environment_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/notebooks" ) func TestAccNotebooksEnvironment_create(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/notebooks/resource_notebooks_instance_test.go.tmpl b/mmv1/third_party/terraform/services/notebooks/resource_notebooks_instance_test.go.tmpl index 17e2f20656d7..2282c4bc1a64 100644 --- a/mmv1/third_party/terraform/services/notebooks/resource_notebooks_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/notebooks/resource_notebooks_instance_test.go.tmpl @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/notebooks" ) func TestAccNotebooksInstance_create_vm_image(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/notebooks/resource_notebooks_runtime_test.go b/mmv1/third_party/terraform/services/notebooks/resource_notebooks_runtime_test.go index de8cff548f05..e8ab59a98678 100644 --- a/mmv1/third_party/terraform/services/notebooks/resource_notebooks_runtime_test.go +++ b/mmv1/third_party/terraform/services/notebooks/resource_notebooks_runtime_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/notebooks" ) func TestAccNotebooksRuntime_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/observability/data_source_observability_folder_settings_test.go.tmpl b/mmv1/third_party/terraform/services/observability/data_source_observability_folder_settings_test.go.tmpl index 44775a1439a8..afce02d8d303 100644 --- a/mmv1/third_party/terraform/services/observability/data_source_observability_folder_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/observability/data_source_observability_folder_settings_test.go.tmpl @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/observability/data_source_observability_organization_settings_test.go.tmpl b/mmv1/third_party/terraform/services/observability/data_source_observability_organization_settings_test.go.tmpl index 44833cb2c9c4..e9b02ad04c6b 100644 --- a/mmv1/third_party/terraform/services/observability/data_source_observability_organization_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/observability/data_source_observability_organization_settings_test.go.tmpl @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/observability/data_source_observability_project_settings_test.go.tmpl b/mmv1/third_party/terraform/services/observability/data_source_observability_project_settings_test.go.tmpl index 3c017c872140..0c83af7570e3 100644 --- a/mmv1/third_party/terraform/services/observability/data_source_observability_project_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/observability/data_source_observability_project_settings_test.go.tmpl @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/observability/resource_observability_folder_settings_test.go.tmpl b/mmv1/third_party/terraform/services/observability/resource_observability_folder_settings_test.go.tmpl index e170a008e537..32456f06ae1f 100644 --- a/mmv1/third_party/terraform/services/observability/resource_observability_folder_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/observability/resource_observability_folder_settings_test.go.tmpl @@ -9,7 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccObservabilityFolderSettings_update(t *testing.T) { @@ -17,7 +20,7 @@ func TestAccObservabilityFolderSettings_update(t *testing.T) { context := map[string]interface{}{ "org_id": envvar.GetTestOrgFromEnv(t), - "kms_key_name": acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/observability/resource_observability_organization_settings_test.go.tmpl b/mmv1/third_party/terraform/services/observability/resource_observability_organization_settings_test.go.tmpl index fc14bab32d2c..cddd570d5d96 100644 --- a/mmv1/third_party/terraform/services/observability/resource_observability_organization_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/observability/resource_observability_organization_settings_test.go.tmpl @@ -9,14 +9,16 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccObservabilityOrganizationSettings_update(t *testing.T) { context := map[string]interface{}{ "org_id": envvar.GetTestOrgFromEnv(t), - "kms_key_name": acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/observability/resource_observability_project_settings_test.go.tmpl b/mmv1/third_party/terraform/services/observability/resource_observability_project_settings_test.go.tmpl index 26d666fdcc00..53390dcb5363 100644 --- a/mmv1/third_party/terraform/services/observability/resource_observability_project_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/observability/resource_observability_project_settings_test.go.tmpl @@ -9,7 +9,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccObservabilityProjectSettings_update(t *testing.T) { @@ -17,7 +20,7 @@ func TestAccObservabilityProjectSettings_update(t *testing.T) { context := map[string]interface{}{ "org_id": envvar.GetTestOrgFromEnv(t), - "kms_key_name": acctest.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyInLocation(t, "us").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/observability/resource_observability_trace_scope_test.go b/mmv1/third_party/terraform/services/observability/resource_observability_trace_scope_test.go index 02e56ca1ade9..79958c2241f4 100644 --- a/mmv1/third_party/terraform/services/observability/resource_observability_trace_scope_test.go +++ b/mmv1/third_party/terraform/services/observability/resource_observability_trace_scope_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/observability" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "testing" ) diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_autonomous_databases.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_autonomous_databases.go index cddcd18aba81..f14dd9e71fae 100644 --- a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_autonomous_databases.go +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_autonomous_databases.go @@ -43,7 +43,7 @@ func dataSourceOracleDatabaseAutonomousDatabasesRead(d *schema.ResourceData, met return err } - url, err := tpgresource.ReplaceVars(d, config, "{{OracleDatabaseBasePath}}projects/{{project}}/locations/{{location}}/autonomousDatabases") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/autonomousDatabases") if err != nil { return fmt.Errorf("Error constructing id: %s", err) } diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_exadata_infrastructures.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_exadata_infrastructures.go index dae13639e1ac..1589d6fbde75 100644 --- a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_exadata_infrastructures.go +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_exadata_infrastructures.go @@ -43,7 +43,7 @@ func dataSourceOracleDatabaseCloudExadataInfrastructuresRead(d *schema.ResourceD return err } - url, err := tpgresource.ReplaceVars(d, config, "{{OracleDatabaseBasePath}}projects/{{project}}/locations/{{location}}/cloudExadataInfrastructures") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/cloudExadataInfrastructures") if err != nil { return fmt.Errorf("Error constructing id: %s", err) } diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_cluster_test.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_cluster_test.go index 28060abefafa..cd7fd381f7da 100644 --- a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_cluster_test.go +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_cluster_test.go @@ -19,9 +19,11 @@ func TestAccOracleDatabaseCloudVmCluster_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "display_name"), resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "exadata_infrastructure"), - resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "cidr"), resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "properties.#"), resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "properties.0.cpu_core_count"), + resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "identity_connector.#"), + resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "identity_connector.0.service_agent_email"), + resource.TestCheckResourceAttrSet("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "identity_connector.0.connection_state"), resource.TestCheckResourceAttr("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "gcp_oracle_zone", "us-east4-b-r1"), resource.TestCheckResourceAttr("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "properties.0.node_count", "2"), resource.TestCheckResourceAttr("data.google_oracle_database_cloud_vm_cluster.my-vmcluster", "properties.0.state", "AVAILABLE"), diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_clusters.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_clusters.go index 6eeebc658833..442d12886e65 100644 --- a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_clusters.go +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_cloud_vm_clusters.go @@ -43,7 +43,7 @@ func dataSourceOracleDatabaseCloudVmClustersRead(d *schema.ResourceData, meta in return err } - url, err := tpgresource.ReplaceVars(d, config, "{{OracleDatabaseBasePath}}projects/{{project}}/locations/{{location}}/cloudVmClusters") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/cloudVmClusters") if err != nil { return fmt.Errorf("Error constructing id: %s", err) } diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_nodes.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_nodes.go index 811373a9966c..dddac6bbe906 100644 --- a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_nodes.go +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_nodes.go @@ -100,7 +100,7 @@ func DataSourceOracleDatabaseDbNodesRead(d *schema.ResourceData, meta interface{ if err != nil { return err } - url, err := tpgresource.ReplaceVars(d, config, "{{OracleDatabaseBasePath}}projects/{{project}}/locations/{{location}}/cloudVmClusters/{{cloud_vm_cluster}}/dbNodes") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/cloudVmClusters/{{cloud_vm_cluster}}/dbNodes") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_servers.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_servers.go index 0a286c18a059..768a9ea16be5 100644 --- a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_servers.go +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_db_servers.go @@ -126,7 +126,7 @@ func DataSourceOracleDatabaseDbServersRead(d *schema.ResourceData, meta interfac billingProject = bp } - url, err := tpgresource.ReplaceVars(d, config, "{{OracleDatabaseBasePath}}projects/{{project}}/locations/{{location}}/cloudExadataInfrastructures/{{cloud_exadata_infrastructure}}/dbServers") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/cloudExadataInfrastructures/{{cloud_exadata_infrastructure}}/dbServers") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_goldengate_deployment_environments.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_goldengate_deployment_environments.go new file mode 100644 index 000000000000..1f5719c76159 --- /dev/null +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_goldengate_deployment_environments.go @@ -0,0 +1,172 @@ +package oracledatabase + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-google/google/registry" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func DataSourceOracleDatabaseGoldengateDeploymentEnvironments() *schema.Resource { + dsSchema := map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the project in which the resource is located. If it is not provided, the provider project is used.", + }, + "location": { + Type: schema.TypeString, + Required: true, + Description: "The location of the resource.", + }, + "goldengate_deployment_environments": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the Goldengate Deployment Environment resource.", + }, + "category": { + Type: schema.TypeString, + Computed: true, + Description: "The category of the Goldengate Deployment Environment resource.", + }, + "display_name": { + Type: schema.TypeString, + Computed: true, + Description: "The display name of the Goldengate Deployment Environment resource.", + }, + "default_cpu_core_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The default CPU core count of the Goldengate Deployment Environment resource.", + }, + "environment_type": { + Type: schema.TypeString, + Computed: true, + Description: "The environment type of the Goldengate Deployment Environment resource.", + }, + "auto_scaling_enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Whether auto scaling is enabled by default for the Goldengate Deployment Environment resource.", + }, + "max_cpu_core_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The max CPU core count of the Goldengate Deployment Environment resource.", + }, + "memory_gb_per_cpu_core": { + Type: schema.TypeInt, + Computed: true, + Description: "The memory per CPU core in GBs of the Goldengate Deployment Environment resource.", + }, + "min_cpu_core_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The min CPU core count of the Goldengate Deployment Environment resource.", + }, + "network_bandwidth_gbps_per_cpu_core": { + Type: schema.TypeInt, + Computed: true, + Description: "The network bandwidth per CPU core in Gbps of the Goldengate Deployment Environment resource.", + }, + "storage_usage_limit_gb_per_cpu_core": { + Type: schema.TypeInt, + Computed: true, + Description: "The storage usage limit per CPU core in GBs of the Goldengate Deployment Environment resource.", + }, + }, + }, + }, + } + return &schema.Resource{ + Read: DataSourceOracleDatabaseGoldengateDeploymentEnvironmentsRead, + Schema: dsSchema, + } +} + +func DataSourceOracleDatabaseGoldengateDeploymentEnvironmentsRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + url, err := tpgresource.ReplaceVars(d, config, "{{OracleDatabaseBasePath}}projects/{{project}}/locations/{{location}}/goldengateDeploymentEnvironments") + if err != nil { + return err + } + billingProject := "" + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for GoldengateDeploymentEnvironments: %s", err) + } + billingProject = project + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + }) + + if err != nil { + return fmt.Errorf("Error reading GoldengateDeploymentEnvironments: %s", err) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error setting project: %s", err) + } + if err := d.Set("goldengate_deployment_environments", flattenGoldengateDeploymentEnvironments(res["goldengateDeploymentEnvironments"], d, config)); err != nil { + return fmt.Errorf("Error setting goldengate_deployment_environments: %s", err) + } + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/goldengateDeploymentEnvironments") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + return nil +} + +func flattenGoldengateDeploymentEnvironments(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) []map[string]interface{} { + if v == nil { + return nil + } + l := v.([]interface{}) + transformed := make([]map[string]interface{}, 0) + for _, raw := range l { + original := raw.(map[string]interface{}) + transformed = append(transformed, map[string]interface{}{ + "name": original["name"], + "category": original["category"], + "display_name": original["displayName"], + "default_cpu_core_count": original["defaultCpuCoreCount"], + "environment_type": original["environmentType"], + "auto_scaling_enabled": original["autoScalingEnabled"], + "max_cpu_core_count": original["maxCpuCoreCount"], + "memory_gb_per_cpu_core": original["memoryGbPerCpuCore"], + "min_cpu_core_count": original["minCpuCoreCount"], + "network_bandwidth_gbps_per_cpu_core": original["networkBandwidthGbpsPerCpuCore"], + "storage_usage_limit_gb_per_cpu_core": original["storageUsageLimitGbPerCpuCore"], + }) + } + + return transformed +} + +func init() { + registry.Schema{ + Name: "google_oracle_database_goldengate_deployment_environments", + ProductName: "oracledatabase", + Type: registry.SchemaTypeDataSource, + Schema: DataSourceOracleDatabaseGoldengateDeploymentEnvironments(), + }.Register() +} diff --git a/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_goldengate_deployment_environments_test.go b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_goldengate_deployment_environments_test.go new file mode 100644 index 000000000000..2466a3cc42ca --- /dev/null +++ b/mmv1/third_party/terraform/services/oracledatabase/data_source_oracle_database_goldengate_deployment_environments_test.go @@ -0,0 +1,35 @@ +package oracledatabase_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" +) + +func TestAccOracleDatabaseGoldengateDeploymentEnvironments_basic(t *testing.T) { + t.Parallel() + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: testAccOracleDatabaseGoldengateDeploymentEnvironmentsConfig(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.google_oracle_database_goldengate_deployment_environments.my_deployment_environments", "goldengate_deployment_environments.#"), + resource.TestCheckResourceAttrSet("data.google_oracle_database_goldengate_deployment_environments.my_deployment_environments", "goldengate_deployment_environments.0.environment_type"), + ), + }, + }, + }) +} + +func testAccOracleDatabaseGoldengateDeploymentEnvironmentsConfig() string { + return fmt.Sprintf(` +data "google_oracle_database_goldengate_deployment_environments" "my_deployment_environments" { + location = "us-east4" + project = "oci-terraform-testing-prod" +} +`) +} diff --git a/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_custom_constraint_test.go b/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_custom_constraint_test.go index 5cec92191a61..fc1ac2bfe0fb 100644 --- a/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_custom_constraint_test.go +++ b/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_custom_constraint_test.go @@ -3,6 +3,7 @@ package orgpolicy_test import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/orgpolicy" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_policy_test.go b/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_policy_test.go index e5053bedb49b..669e0303f1a4 100644 --- a/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_policy_test.go +++ b/mmv1/third_party/terraform/services/orgpolicy/resource_org_policy_policy_test.go @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/orgpolicy" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -457,7 +459,7 @@ func testAccCheckOrgPolicyPolicyDestroyProducer(t *testing.T) func(s *terraform. config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{OrgPolicyBasePath}}{{parent}}/policies/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(orgpolicy.Product, config)+"{{parent}}/policies/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment.go b/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment.go index cf379c41699e..7c7c59493d6c 100644 --- a/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment.go +++ b/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment.go @@ -34,6 +34,7 @@ func ResourceOSConfigOSPolicyAssignment() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -1064,6 +1065,9 @@ For a given OS policy assignment, there is only one revision with a value of 'tr DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, Description: "The project for the resource", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -1112,7 +1116,7 @@ func resourceOSConfigOSPolicyAssignmentCreate(d *schema.ResourceData, meta inter // Shorten long form project id to short form. billingProject = tpgresource.GetResourceNameFromSelfLink(project) - url, err := tpgresource.ReplaceVars(d, config, "{{OSConfigBasePath}}projects/{{project}}/locations/{{location}}/osPolicyAssignments?osPolicyAssignmentId={{name}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/osPolicyAssignments?osPolicyAssignmentId={{name}}") if err != nil { return err } @@ -1197,7 +1201,7 @@ func resourceOSConfigOSPolicyAssignmentRead(d *schema.ResourceData, meta interfa // Shorten long form project id to short form billingProject = tpgresource.GetResourceNameFromSelfLink(project) - url, err := tpgresource.ReplaceVars(d, config, "{{OSConfigBasePath}}projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}}") if err != nil { return err } @@ -1272,10 +1276,19 @@ func resourceOSConfigOSPolicyAssignmentRead(d *schema.ResourceData, meta interfa return fmt.Errorf("Error reading OSPolicyAssignment: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceOSConfigOSPolicyAssignmentUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceOSConfigOSPolicyAssignment) { + return ResourceOSConfigOSPolicyAssignment().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1317,7 +1330,7 @@ func resourceOSConfigOSPolicyAssignmentUpdate(d *schema.ResourceData, meta inter obj["rollout"] = rolloutProp } - url, err := tpgresource.ReplaceVars(d, config, "{{OSConfigBasePath}}projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}}") if err != nil { return err } @@ -1386,6 +1399,13 @@ func resourceOSConfigOSPolicyAssignmentUpdate(d *schema.ResourceData, meta inter } func resourceOSConfigOSPolicyAssignmentDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1401,7 +1421,7 @@ func resourceOSConfigOSPolicyAssignmentDelete(d *schema.ResourceData, meta inter // Shorten long form project id to short form billingProject = tpgresource.GetResourceNameFromSelfLink(project) - url, err := tpgresource.ReplaceVars(d, config, "{{OSConfigBasePath}}projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/osPolicyAssignments/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_meta.yaml b/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_meta.yaml index bc32a0ba5f6c..499fe16bc059 100644 --- a/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_meta.yaml +++ b/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_meta.yaml @@ -109,3 +109,5 @@ fields: - api_field: 'rolloutState' - field: 'skip_await_rollout' - api_field: 'uid' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_test.go.tmpl b/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_test.go.tmpl index 88af9004da34..138ac5c57882 100644 --- a/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_test.go.tmpl +++ b/mmv1/third_party/terraform/services/osconfig/resource_os_config_os_policy_assignment_test.go.tmpl @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/osconfig" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/osconfig/resource_os_config_patch_deployment_test.go b/mmv1/third_party/terraform/services/osconfig/resource_os_config_patch_deployment_test.go index 3b2e93158de8..432b99d6480c 100644 --- a/mmv1/third_party/terraform/services/osconfig/resource_os_config_patch_deployment_test.go +++ b/mmv1/third_party/terraform/services/osconfig/resource_os_config_patch_deployment_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/osconfig" ) func TestAccOSConfigPatchDeployment_osConfigPatchDeployment_yum_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_folder_test.go.tmpl b/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_folder_test.go.tmpl index 7f071363c4f3..2c2f5e202bd8 100644 --- a/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_folder_test.go.tmpl +++ b/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_folder_test.go.tmpl @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/osconfigv2" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_organization_test.go b/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_organization_test.go index e34839ff36e1..90080d83c9b6 100644 --- a/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_organization_test.go +++ b/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_for_organization_test.go @@ -6,10 +6,12 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/osconfigv2" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccOSConfigV2PolicyOrchestratorForOrganization_basic(t *testing.T) { - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-org-{organization_id}@gcp-sa-osconfig.iam.gserviceaccount.com", Role: "roles/osconfig.serviceAgent", diff --git a/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_test.go b/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_test.go index 4aed5eeac4ef..03e24d94ce7e 100644 --- a/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_test.go +++ b/mmv1/third_party/terraform/services/osconfigv2/resource_os_config_v2_policy_orchestrator_test.go @@ -6,12 +6,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/osconfigv2" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccOSConfigV2PolicyOrchestrator_basic(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-osconfig.iam.gserviceaccount.com", Role: "roles/osconfig.serviceAgent", diff --git a/mmv1/third_party/terraform/services/oslogin/resource_os_login_ssh_public_key_test.go b/mmv1/third_party/terraform/services/oslogin/resource_os_login_ssh_public_key_test.go index b83dd0628ebd..08709a644270 100644 --- a/mmv1/third_party/terraform/services/oslogin/resource_os_login_ssh_public_key_test.go +++ b/mmv1/third_party/terraform/services/oslogin/resource_os_login_ssh_public_key_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/oslogin" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccOSLoginSSHPublicKey_osLoginSshKeyExpiry(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parallelstore/resource_parallelstore_instance_test.go.tmpl b/mmv1/third_party/terraform/services/parallelstore/resource_parallelstore_instance_test.go.tmpl index 62f2654865a4..2dab7ad14453 100644 --- a/mmv1/third_party/terraform/services/parallelstore/resource_parallelstore_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/parallelstore/resource_parallelstore_instance_test.go.tmpl @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parallelstore" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccParallelstoreInstance_parallelstoreInstanceBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_test.go b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_test.go index 566389d4e6a6..1310c406f162 100644 --- a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_test.go +++ b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanager" ) func TestAccDataSourceParameterManagerParameter_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_render_test.go b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_render_test.go index cdb0abfe0c3a..18be420bd8cf 100644 --- a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_render_test.go +++ b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_render_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccDataSourceParameterManagerParameterVersionRender_basicWithResourceReference(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_test.go b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_test.go index 581fb8758070..893d27a9d395 100644 --- a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_test.go +++ b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameter_version_test.go @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanager" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceParameterManagerParameterVersion_basicWithResourceReference(t *testing.T) { @@ -190,7 +193,7 @@ data "google_parameter_manager_parameter_version" "parameter-version-with-yaml-d func TestAccDataSourceParameterManagerParameterVersion_withKmsKey(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pm.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -198,7 +201,7 @@ func TestAccDataSourceParameterManagerParameterVersion_withKmsKey(t *testing.T) }) context := map[string]interface{}{ - "kms_key": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-parameter-manager-managed-1").CryptoKey.Name, + "kms_key": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-parameter-manager-managed-1").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameters_test.go b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameters_test.go index bcb8c8f0cc3a..99b5bc92f027 100644 --- a/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameters_test.go +++ b/mmv1/third_party/terraform/services/parametermanager/data_source_parameter_manager_parameters_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanager" ) func TestAccDataSourceParameterManagerParameters_basic(t *testing.T) { @@ -30,8 +31,9 @@ func TestAccDataSourceParameterManagerParameters_basic(t *testing.T) { "data.google_parameter_manager_parameters.parameters-datasource", "google_parameter_manager_parameter.parameters", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), @@ -87,8 +89,9 @@ func TestAccDataSourceParameterManagerParameters_filter(t *testing.T) { "google_parameter_manager_parameter.parameters-1", "google_parameter_manager_parameter.parameters-2", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), diff --git a/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_test.go b/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_test.go index 627cf6d03178..5841ef042e1a 100644 --- a/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_test.go +++ b/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanager" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccParameterManagerParameter_labelsUpdate(t *testing.T) { @@ -105,7 +108,7 @@ resource "google_parameter_manager_parameter" "parameter-with-labels" { func TestAccParameterManagerParameter_kmsKeyUpdate(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pm.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -113,8 +116,8 @@ func TestAccParameterManagerParameter_kmsKeyUpdate(t *testing.T) { }) context := map[string]interface{}{ - "kms_key": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-parameter-manager-managed-1").CryptoKey.Name, - "kms_key_other": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-parameter-manager-managed-2").CryptoKey.Name, + "kms_key": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-parameter-manager-managed-1").CryptoKey.Name, + "kms_key_other": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-parameter-manager-managed-2").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_version_test.go b/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_version_test.go index 2383e63cbb32..26dedfac0f7d 100644 --- a/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_version_test.go +++ b/mmv1/third_party/terraform/services/parametermanager/resource_parameter_manager_parameter_version_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanager" ) func TestAccParameterManagerParameterVersion_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_test.go b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_test.go index c1d96be884fd..74bf79dc1cca 100644 --- a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_test.go +++ b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanagerregional" ) func TestAccDataSourceParameterManagerRegionalRegionalParameter_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_render_test.go b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_render_test.go index 0f6ef4784c5f..1c703e921a1f 100644 --- a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_render_test.go +++ b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_render_test.go @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanagerregional" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" ) func TestAccDataSourceParameterManagerRegionalRegionalParameterVersionRender_basicWithResourceReference(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_test.go b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_test.go index 28ba96aa4166..d27cee3be9b6 100644 --- a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_test.go +++ b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameter_version_test.go @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanagerregional" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceParameterManagerRegionalRegionalParameterVersion_basicWithResourceReference(t *testing.T) { @@ -196,7 +199,7 @@ data "google_parameter_manager_regional_parameter_version" "regional-parameter-v func TestAccDataSourceParameterManagerRegionalRegionalParameterVersion_withKmsKey(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pm.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -204,7 +207,7 @@ func TestAccDataSourceParameterManagerRegionalRegionalParameterVersion_withKmsKe }) context := map[string]interface{}{ - "kms_key": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-parameter-manager-managed-central-key1").CryptoKey.Name, + "kms_key": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-parameter-manager-managed-central-key1").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameters_test.go b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameters_test.go index 5a21fbc6cde4..d060190012bc 100644 --- a/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameters_test.go +++ b/mmv1/third_party/terraform/services/parametermanagerregional/data_source_parameter_manager_regional_parameters_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanagerregional" ) func TestAccDataSourceParameterManagerRegionalRegionalParameters_basic(t *testing.T) { @@ -30,8 +31,9 @@ func TestAccDataSourceParameterManagerRegionalRegionalParameters_basic(t *testin "data.google_parameter_manager_regional_parameters.regional-parameters-datasource", "google_parameter_manager_regional_parameter.regional-parameters", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), @@ -89,8 +91,9 @@ func TestAccDataSourceParameterManagerRegionalRegionalParameters_filter(t *testi "google_parameter_manager_regional_parameter.regional-parameters-1", "google_parameter_manager_regional_parameter.regional-parameters-2", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), diff --git a/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_test.go b/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_test.go index b49304df14ef..c2a7682326c7 100644 --- a/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_test.go +++ b/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanagerregional" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccParameterManagerRegionalRegionalParameter_import(t *testing.T) { @@ -152,7 +155,7 @@ resource "google_parameter_manager_regional_parameter" "regional-parameter-with- func TestAccParameterManagerRegionalRegionalParameter_kmskeyUpdate(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pm.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -160,8 +163,8 @@ func TestAccParameterManagerRegionalRegionalParameter_kmskeyUpdate(t *testing.T) }) context := map[string]interface{}{ - "kms_key": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-parameter-manager-managed-central-key1").CryptoKey.Name, - "kms_key_other": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-parameter-manager-managed-central-key2").CryptoKey.Name, + "kms_key": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-parameter-manager-managed-central-key1").CryptoKey.Name, + "kms_key_other": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-parameter-manager-managed-central-key2").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_version_test.go b/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_version_test.go index 06b2eb58cf38..15ed6234256e 100644 --- a/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_version_test.go +++ b/mmv1/third_party/terraform/services/parametermanagerregional/resource_parameter_manager_regional_parameter_version_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/parametermanagerregional" ) func TestAccParameterManagerRegionalRegionalParameterVersion_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority.go b/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority.go index ade17ac4c475..631a016e73ed 100644 --- a/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority.go +++ b/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority.go @@ -52,7 +52,7 @@ func dataSourcePrivatecaCertificateAuthorityRead(d *schema.ResourceData, meta in // pem_csr is only applicable for SUBORDINATE CertificateAuthorities when their state is AWAITING_USER_ACTIVATION if d.Get("type") == "SUBORDINATE" && d.Get("state") == "AWAITING_USER_ACTIVATION" { - url, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:fetch") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:fetch") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority_test.go b/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority_test.go index 75bfaba6c452..c8682b0c3948 100644 --- a/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority_test.go +++ b/mmv1/third_party/terraform/services/privateca/data_source_certificate_authority_test.go @@ -5,13 +5,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" ) func TestAccDataSourcePrivatecaCertificateAuthority_privatecaCertificateAuthorityBasicExample(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "pool_name": acctest.BootstrapSharedCaPoolInLocation(t, "us-central1"), + "pool_name": BootstrapSharedCaPoolInLocation(t, "us-central1"), "pool_location": "us-central1", "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/privateca/privateca_ca_utils.go b/mmv1/third_party/terraform/services/privateca/privateca_ca_utils.go index b5fa4dda7876..41b2822a96f8 100644 --- a/mmv1/third_party/terraform/services/privateca/privateca_ca_utils.go +++ b/mmv1/third_party/terraform/services/privateca/privateca_ca_utils.go @@ -16,7 +16,7 @@ import ( // CA related utilities. func enableCA(config *transport_tpg.Config, d *schema.ResourceData, project string, billingProject string, userAgent string) error { - enableUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:enable") + enableUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:enable") if err != nil { return err } @@ -45,7 +45,7 @@ func enableCA(config *transport_tpg.Config, d *schema.ResourceData, project stri } func disableCA(config *transport_tpg.Config, d *schema.ResourceData, project string, billingProject string, userAgent string) error { - disableUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:disable") + disableUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:disable") if err != nil { return err } @@ -106,7 +106,7 @@ func activateSubCAWithThirdPartyIssuer(config *transport_tpg.Config, d *schema.R activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"] = make(map[string]interface{}) activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"].(map[string]interface{})["pemCertificates"] = pemIssuerChain - activateUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:activate") + activateUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:activate") if err != nil { return err } @@ -151,7 +151,7 @@ func activateSubCAWithFirstPartyIssuer(config *transport_tpg.Config, d *schema.R issuer := ca.(string) // 2. fetch CSR - fetchCSRUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:fetch") + fetchCSRUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:fetch") if err != nil { return err } @@ -204,7 +204,7 @@ func activateSubCAWithFirstPartyIssuer(config *transport_tpg.Config, d *schema.R return err } - PrivatecaBasePath, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}") + PrivatecaBasePath, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)) if err != nil { return err } @@ -237,7 +237,7 @@ func activateSubCAWithFirstPartyIssuer(config *transport_tpg.Config, d *schema.R activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"] = make(map[string]interface{}) activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"].(map[string]interface{})["pemCertificates"] = signerCertChain - activateUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:activate") + activateUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:activate") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/privateca/resource_privateca_ca_pool_test.go b/mmv1/third_party/terraform/services/privateca/resource_privateca_ca_pool_test.go index cc93168fecca..8943fcb74150 100644 --- a/mmv1/third_party/terraform/services/privateca/resource_privateca_ca_pool_test.go +++ b/mmv1/third_party/terraform/services/privateca/resource_privateca_ca_pool_test.go @@ -1,12 +1,80 @@ package privateca_test import ( + "fmt" + "log" "testing" + "time" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/privateca" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) +func BootstrapSharedCaPoolInLocation(t *testing.T, location string) string { + project := envvar.GetTestProjectFromEnv() + poolName := "static-ca-pool" + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + log.Printf("[DEBUG] Getting shared CA pool %q", poolName) + url := fmt.Sprintf("%sprojects/%s/locations/%s/caPools/%s", transport_tpg.BaseUrl(privateca.Product, config), project, location, poolName) + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) + if err != nil { + log.Printf("[DEBUG] CA pool %q not found, bootstrapping", poolName) + poolObj := map[string]interface{}{ + "tier": "ENTERPRISE", + } + createUrl := fmt.Sprintf("%sprojects/%s/locations/%s/caPools?caPoolId=%s", transport_tpg.BaseUrl(privateca.Product, config), project, location, poolName) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: createUrl, + UserAgent: config.UserAgent, + Body: poolObj, + Timeout: 4 * time.Minute, + }) + if err != nil { + t.Fatalf("Error bootstrapping shared CA pool %q: %s", poolName, err) + } + + log.Printf("[DEBUG] Waiting for CA pool creation to finish") + var opRes map[string]interface{} + err = privateca.PrivatecaOperationWaitTimeWithResponse( + config, res, &opRes, project, "Creating CA pool", config.UserAgent, + 4*time.Minute) + if err != nil { + t.Errorf("Error getting shared CA pool %q: %s", poolName, err) + } + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: url, + UserAgent: config.UserAgent, + }) + if err != nil { + t.Errorf("Error getting shared CA pool %q: %s", poolName, err) + } + } + return poolName +} + func TestAccPrivatecaCaPool_privatecaCapoolUpdate(t *testing.T) { t.Parallel() @@ -447,7 +515,7 @@ resource "google_privateca_ca_pool" "default" { func TestAccPrivatecaCaPool_CmekKeyUpdate(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-privateca.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -455,8 +523,8 @@ func TestAccPrivatecaCaPool_CmekKeyUpdate(t *testing.T) { }) context := map[string]interface{}{ - "kms_key1": acctest.BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", "us-central1").CryptoKey.Name, - "kms_key2": acctest.BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", "us-central1").CryptoKey.Name, + "kms_key1": kms.BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", "us-central1").CryptoKey.Name, + "kms_key2": kms.BootstrapKMSKeyWithPurposeInLocation(t, "ENCRYPT_DECRYPT", "us-central1").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_sweeper.go b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_sweeper.go index ef9d9c543425..d5080786c9ac 100644 --- a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_sweeper.go +++ b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_sweeper.go @@ -40,7 +40,7 @@ func testSweepCertificateAuthority(region string) error { }, } - caPoolsUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools") + caPoolsUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/caPools") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_test.go b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_test.go index fac616afad3a..2d14b2c525a2 100644 --- a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_test.go +++ b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_authority_test.go @@ -5,13 +5,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" ) func TestAccPrivatecaCertificateAuthority_privatecaCertificateAuthorityUpdate(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "pool_name": acctest.BootstrapSharedCaPoolInLocation(t, "us-central1"), + "pool_name": BootstrapSharedCaPoolInLocation(t, "us-central1"), "pool_location": "us-central1", "deletion_protection": false, "random_suffix": acctest.RandString(t, 10), @@ -63,7 +64,7 @@ func TestAccPrivatecaCertificateAuthority_rootCaManageDesiredState(t *testing.T) random_suffix := acctest.RandString(t, 10) context_staged := map[string]interface{}{ - "pool_name": acctest.BootstrapSharedCaPoolInLocation(t, "us-central1"), + "pool_name": BootstrapSharedCaPoolInLocation(t, "us-central1"), "pool_location": "us-central1", "deletion_protection": false, "random_suffix": random_suffix, @@ -71,7 +72,7 @@ func TestAccPrivatecaCertificateAuthority_rootCaManageDesiredState(t *testing.T) } context_enabled := map[string]interface{}{ - "pool_name": acctest.BootstrapSharedCaPoolInLocation(t, "us-central1"), + "pool_name": BootstrapSharedCaPoolInLocation(t, "us-central1"), "pool_location": "us-central1", "deletion_protection": false, "random_suffix": random_suffix, @@ -79,7 +80,7 @@ func TestAccPrivatecaCertificateAuthority_rootCaManageDesiredState(t *testing.T) } context_disabled := map[string]interface{}{ - "pool_name": acctest.BootstrapSharedCaPoolInLocation(t, "us-central1"), + "pool_name": BootstrapSharedCaPoolInLocation(t, "us-central1"), "pool_location": "us-central1", "deletion_protection": false, "random_suffix": random_suffix, diff --git a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_template_test.go b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_template_test.go index ff7e486ee91c..06538c02779f 100644 --- a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_template_test.go +++ b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_template_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" ) func TestAccPrivatecaCertificateTemplate_BasicCertificateTemplate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_test.go b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_test.go index 3652a1e02441..61c54d6ff2c9 100644 --- a/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_test.go +++ b/mmv1/third_party/terraform/services/privateca/resource_privateca_certificate_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" ) func TestAccPrivatecaCertificate_privatecaCertificateUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/privilegedaccessmanager/data_source_privileged_access_manager_entitlement_test.go b/mmv1/third_party/terraform/services/privilegedaccessmanager/data_source_privileged_access_manager_entitlement_test.go index 159619cc3670..fc693c87ed78 100644 --- a/mmv1/third_party/terraform/services/privilegedaccessmanager/data_source_privileged_access_manager_entitlement_test.go +++ b/mmv1/third_party/terraform/services/privilegedaccessmanager/data_source_privileged_access_manager_entitlement_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privilegedaccessmanager" ) func TestAccDataSourceGooglePrivilegedAccessManagerEntitlement_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_entitlement_test.go.tmpl b/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_entitlement_test.go.tmpl index ae9942e534b7..e5ae3f989288 100644 --- a/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_entitlement_test.go.tmpl +++ b/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_entitlement_test.go.tmpl @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/privilegedaccessmanager" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_settings_test.go.tmpl b/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_settings_test.go.tmpl index d3e8254c9cd0..df47d4ed423a 100644 --- a/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_settings_test.go.tmpl +++ b/mmv1/third_party/terraform/services/privilegedaccessmanager/resource_privileged_access_manager_settings_test.go.tmpl @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/privilegedaccessmanager" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/publicca/resource_public_ca_external_account_key_test.go b/mmv1/third_party/terraform/services/publicca/resource_public_ca_external_account_key_test.go index 266a14d61f4e..7ed1fd2f5673 100644 --- a/mmv1/third_party/terraform/services/publicca/resource_public_ca_external_account_key_test.go +++ b/mmv1/third_party/terraform/services/publicca/resource_public_ca_external_account_key_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/publicca" ) func TestAccPublicCAExternalAccountKey_publicCaExternalAccountKey(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_subscription_test.go b/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_subscription_test.go index a2a55a334a05..fec3d2996304 100644 --- a/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_subscription_test.go +++ b/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_subscription_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" ) func TestAccDataSourceGooglePubsubSubscription_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_topic_test.go b/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_topic_test.go index 53a67d30f107..a291bced289d 100644 --- a/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_topic_test.go +++ b/mmv1/third_party/terraform/services/pubsub/data_source_pubsub_topic_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" ) func TestAccDataSourceGooglePubsubTopic_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/pubsub/iam_pubsub_subscription_test.go b/mmv1/third_party/terraform/services/pubsub/iam_pubsub_subscription_test.go index f5efd5390fc5..bae64cfd9806 100644 --- a/mmv1/third_party/terraform/services/pubsub/iam_pubsub_subscription_test.go +++ b/mmv1/third_party/terraform/services/pubsub/iam_pubsub_subscription_test.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccPubsubSubscriptionIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/pubsub/iam_pubsub_topic_test.go b/mmv1/third_party/terraform/services/pubsub/iam_pubsub_topic_test.go index 09c1846ea281..2b37142b688f 100644 --- a/mmv1/third_party/terraform/services/pubsub/iam_pubsub_topic_test.go +++ b/mmv1/third_party/terraform/services/pubsub/iam_pubsub_topic_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/pubsub/resource_pubsub_schema_test.go b/mmv1/third_party/terraform/services/pubsub/resource_pubsub_schema_test.go index 202a373d4dff..e53f19b521e0 100644 --- a/mmv1/third_party/terraform/services/pubsub/resource_pubsub_schema_test.go +++ b/mmv1/third_party/terraform/services/pubsub/resource_pubsub_schema_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" ) func TestAccPubsubSchema_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/pubsub/resource_pubsub_subscription_test.go b/mmv1/third_party/terraform/services/pubsub/resource_pubsub_subscription_test.go index 98bb8686137d..14ba4689604f 100644 --- a/mmv1/third_party/terraform/services/pubsub/resource_pubsub_subscription_test.go +++ b/mmv1/third_party/terraform/services/pubsub/resource_pubsub_subscription_test.go @@ -8,7 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/services/tags" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -244,7 +247,7 @@ func TestAccPubsubSubscriptionBigQuery_serviceAccount(t *testing.T) { serviceAccount := fmt.Sprintf("bq-test-sa-%s", acctest.RandString(t, 10)) serviceAccount2 := fmt.Sprintf("bq-test-sa2-%s", acctest.RandString(t, 10)) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com", Role: "roles/bigquery.dataEditor", diff --git a/mmv1/third_party/terraform/services/pubsub/resource_pubsub_topic_test.go b/mmv1/third_party/terraform/services/pubsub/resource_pubsub_topic_test.go index 0269e0a6591b..cbb311ec1c93 100644 --- a/mmv1/third_party/terraform/services/pubsub/resource_pubsub_topic_test.go +++ b/mmv1/third_party/terraform/services/pubsub/resource_pubsub_topic_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/tags" ) @@ -47,10 +50,10 @@ func TestAccPubsubTopic_update(t *testing.T) { func TestAccPubsubTopic_cmek(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKey(t) + bootstrapped := kms.BootstrapKMSKey(t) topicName := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -63,7 +66,7 @@ func TestAccPubsubTopic_cmek(t *testing.T) { CheckDestroy: testAccCheckPubsubTopicDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccPubsubTopic_cmek(topicName, kms.CryptoKey.Name), + Config: testAccPubsubTopic_cmek(topicName, bootstrapped.CryptoKey.Name), }, { ResourceName: "google_pubsub_topic.topic", diff --git a/mmv1/third_party/terraform/services/pubsublite/fw_resource_pubsub_lite_reservation.go b/mmv1/third_party/terraform/services/pubsublite/fw_resource_pubsub_lite_reservation.go deleted file mode 100644 index adfb5a863999..000000000000 --- a/mmv1/third_party/terraform/services/pubsublite/fw_resource_pubsub_lite_reservation.go +++ /dev/null @@ -1,386 +0,0 @@ -package pubsublite - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-log/tflog" - - "github.com/hashicorp/terraform-provider-google/google/fwmodels" - "github.com/hashicorp/terraform-provider-google/google/fwresource" - "github.com/hashicorp/terraform-provider-google/google/fwtransport" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - "google.golang.org/api/pubsublite/v1" -) - -//resource is non-functional, preserved for reference with ongoing fwprovider work -//any changes to `google_pubsublite_reservation` should be performed at mmv1/products/pubsublite/Reservation.yaml - -// Ensure the implementation satisfies the expected interfaces. -var ( - _ resource.Resource = &GooglePubsubLiteReservationFWResource{} - _ resource.ResourceWithConfigure = &GooglePubsubLiteReservationFWResource{} -) - -// NewGooglePubsubLiteReservationResource is a helper function to simplify the provider implementation. -func NewGooglePubsubLiteReservationFWResource() resource.Resource { - return &GooglePubsubLiteReservationFWResource{} -} - -// GooglePubsubLiteReservationResource is the resource implementation. -type GooglePubsubLiteReservationFWResource struct { - client *pubsublite.Service - providerConfig *transport_tpg.Config -} - -type GooglePubsubLiteReservationModel struct { - Id types.String `tfsdk:"id"` - Project types.String `tfsdk:"project"` - Region types.String `tfsdk:"region"` - Name types.String `tfsdk:"name"` - ThroughputCapacity types.Int64 `tfsdk:"throughput_capacity"` -} - -// Metadata returns the resource type name. -func (d *GooglePubsubLiteReservationFWResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_fwprovider_pubsub_lite_reservation" -} - -func (d *GooglePubsubLiteReservationFWResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - p, ok := req.ProviderData.(*transport_tpg.Config) - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *transport_tpg.Config, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - return - } - - d.providerConfig = p -} - -// Schema defines the schema for the data source. -func (d *GooglePubsubLiteReservationFWResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Pubsub Lite Reservation resource description", - - Attributes: map[string]schema.Attribute{ - "project": schema.StringAttribute{ - Description: "The project id of the Pubsub Lite Reservation.", - MarkdownDescription: "The project id of the Pubsub Lite Reservation.", - Required: true, - }, - "region": schema.StringAttribute{ - Description: "The region of the Pubsub Lite Reservation.", - MarkdownDescription: "The region of the Pubsub Lite Reservation.", - Required: true, - }, - "name": schema.StringAttribute{ - Description: `The display name of the project.`, - MarkdownDescription: `The display name of the project.`, - Required: true, - }, - "throughput_capacity": schema.Int64Attribute{ - Description: `The reserved throughput capacity. Every unit of throughput capacity is equivalent to 1 MiB/s of published messages or 2 MiB/s of subscribed messages.`, - MarkdownDescription: `The reserved throughput capacity. Every unit of throughput capacity is equivalent to 1 MiB/s of published messages or 2 MiB/s of subscribed messages.`, - Required: true, - }, - // This is included for backwards compatibility with the original, SDK-implemented data source. - "id": schema.StringAttribute{ - Description: "Project identifier", - MarkdownDescription: "Project identifier", - Computed: true, - }, - }, - } -} - -func (d *GooglePubsubLiteReservationFWResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data GooglePubsubLiteReservationModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - - // Use provider_meta to set User-Agent - userAgent := fwtransport.GenerateFrameworkUserAgentString(metaData, d.providerConfig.UserAgent) - - obj := make(map[string]interface{}) - - obj["throughputCapacity"] = data.ThroughputCapacity.ValueInt64() - - data.Project = fwresource.GetProjectFramework(data.Project, types.StringValue(d.providerConfig.Project), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - data.Region = fwresource.GetRegionFramework(data.Region, types.StringValue(d.providerConfig.Region), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - billingProject := data.Project - - var schemaDefaultVals fwtransport.DefaultVars - schemaDefaultVals.Project = data.Project - schemaDefaultVals.Region = data.Region - - url := fwtransport.ReplaceVars(ctx, req, &resp.Diagnostics, schemaDefaultVals, d.providerConfig, "{{PubsubLiteBasePath}}projects/{{project}}/locations/{{region}}/reservations?reservationId={{name}}") - if resp.Diagnostics.HasError() { - return - } - tflog.Trace(ctx, fmt.Sprintf("[DEBUG] Creating new Reservation: %#v", obj)) - - headers := make(http.Header) - res, _ := fwtransport.SendRequest(fwtransport.SendRequestOptions{ - Config: d.providerConfig, - Method: "POST", - Project: billingProject.ValueString(), - RawURL: url, - UserAgent: userAgent, - Body: obj, - Headers: headers, - }, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - tflog.Trace(ctx, "create fwprovider google_pubsub_lite resource") - - // Put data in model - data.Id = types.StringValue(fmt.Sprintf("projects/%s/locations/%s/reservations/%s", data.Project.ValueString(), data.Region.ValueString(), data.Name.ValueString())) - data.ThroughputCapacity = types.Int64Value(res["throughputCapacity"].(int64)) - - // Save data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -// Read refreshes the Terraform state with the latest data. -func (d *GooglePubsubLiteReservationFWResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data GooglePubsubLiteReservationModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.State.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - - // Use provider_meta to set User-Agent - userAgent := fwtransport.GenerateFrameworkUserAgentString(metaData, d.providerConfig.UserAgent) - - data.Project = fwresource.GetProjectFramework(data.Project, types.StringValue(d.providerConfig.Project), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - data.Region = fwresource.GetRegionFramework(data.Region, types.StringValue(d.providerConfig.Region), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - billingProject := data.Project - - var schemaDefaultVals fwtransport.DefaultVars - schemaDefaultVals.Project = data.Project - schemaDefaultVals.Region = data.Region - - url := fwtransport.ReplaceVars(ctx, req, &resp.Diagnostics, schemaDefaultVals, d.providerConfig, "{{PubSubLiteBasePath}}projects/{{project}}/locations/{{region}}/instances/{{name}}") - - if resp.Diagnostics.HasError() { - return - } - - headers := make(http.Header) - res, _ := fwtransport.SendRequest(fwtransport.SendRequestOptions{ - Config: d.providerConfig, - Method: "GET", - Project: billingProject.ValueString(), - RawURL: url, - UserAgent: userAgent, - Headers: headers, - }, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - tflog.Trace(ctx, "read fwprovider google_pubsub_lite resource") - - // Put data in model - data.Id = types.StringValue(fmt.Sprintf("projects/%s/locations/%s/instances/%s", data.Project.ValueString(), data.Region.ValueString(), data.Name.ValueString())) - data.ThroughputCapacity = types.Int64Value(res["throughputCapacity"].(int64)) - - // Save data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (d *GooglePubsubLiteReservationFWResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var plan, state GooglePubsubLiteReservationModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.State.Get(ctx, &state)...) - if resp.Diagnostics.HasError() { - return - } - - // Use provider_meta to set User-Agent - userAgent := fwtransport.GenerateFrameworkUserAgentString(metaData, d.providerConfig.UserAgent) - - obj := make(map[string]interface{}) - - obj["throughputCapacity"] = plan.ThroughputCapacity.ValueInt64() - - plan.Project = fwresource.GetProjectFramework(plan.Project, types.StringValue(d.providerConfig.Project), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - plan.Region = fwresource.GetRegionFramework(plan.Region, types.StringValue(d.providerConfig.Region), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - billingProject := plan.Project - - var schemaDefaultVals fwtransport.DefaultVars - schemaDefaultVals.Project = plan.Project - schemaDefaultVals.Region = plan.Region - - url := fwtransport.ReplaceVars(ctx, req, &resp.Diagnostics, schemaDefaultVals, d.providerConfig, "{{PubSubLiteBasePath}}projects/{{project}}/locations/{{region}}/instances/{{name}}") - - if resp.Diagnostics.HasError() { - return - } - tflog.Trace(ctx, fmt.Sprintf("[DEBUG] Updating Reservation: %#v", obj)) - - headers := make(http.Header) - - updateMask := []string{} - if !plan.ThroughputCapacity.Equal(state.ThroughputCapacity) { - updateMask = append(updateMask, "throughputCapacity") - } - - // updateMask is a URL parameter but not present in the schema, so ReplaceVars - // won't set it - var err error - url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) - if err != nil { - resp.Diagnostics.AddError("Error when sending HTTP request: ", err.Error()) - return - } - - res, _ := fwtransport.SendRequest(fwtransport.SendRequestOptions{ - Config: d.providerConfig, - Method: "PATCH", - Project: billingProject.ValueString(), - RawURL: url, - UserAgent: userAgent, - Body: obj, - Headers: headers, - }, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - tflog.Trace(ctx, "update fwprovider google_pubsub_lite resource") - - // Put data in model - plan.Id = types.StringValue(fmt.Sprintf("projects/%s/locations/%s/instances/%s", plan.Project.ValueString(), plan.Region.ValueString(), plan.Name.ValueString())) - plan.ThroughputCapacity = types.Int64Value(res["throughputCapacity"].(int64)) - - // Save data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) -} -func (d *GooglePubsubLiteReservationFWResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data GooglePubsubLiteReservationModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.State.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - // Use provider_meta to set User-Agent - userAgent := fwtransport.GenerateFrameworkUserAgentString(metaData, d.providerConfig.UserAgent) - - obj := make(map[string]interface{}) - - data.Project = fwresource.GetProjectFramework(data.Project, types.StringValue(d.providerConfig.Project), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - data.Region = fwresource.GetRegionFramework(data.Region, types.StringValue(d.providerConfig.Region), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - billingProject := data.Project - - var schemaDefaultVals fwtransport.DefaultVars - schemaDefaultVals.Project = data.Project - schemaDefaultVals.Region = data.Region - - url := fwtransport.ReplaceVars(ctx, req, &resp.Diagnostics, schemaDefaultVals, d.providerConfig, "{{PubSubLiteBasePath}}projects/{{project}}/locations/{{region}}/instances/{{name}}") - - if resp.Diagnostics.HasError() { - return - } - tflog.Trace(ctx, fmt.Sprintf("[DEBUG] Deleting Reservation: %#v", obj)) - - headers := make(http.Header) - res, _ := fwtransport.SendRequest(fwtransport.SendRequestOptions{ - Config: d.providerConfig, - Method: "DELETE", - Project: billingProject.ValueString(), - RawURL: url, - UserAgent: userAgent, - Body: obj, - Headers: headers, - }, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - tflog.Trace(ctx, fmt.Sprintf("[DEBUG] Deleted Reservation: %#v", res)) -} diff --git a/mmv1/third_party/terraform/services/pubsublite/fw_resource_pubsub_lite_reservation_test.go b/mmv1/third_party/terraform/services/pubsublite/fw_resource_pubsub_lite_reservation_test.go deleted file mode 100644 index e642be5341ff..000000000000 --- a/mmv1/third_party/terraform/services/pubsublite/fw_resource_pubsub_lite_reservation_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package pubsublite_test - -import ( - "testing" - - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-provider-google/google/acctest" -) - -func TestAccResourceFWPubsubLiteReservation_basic(t *testing.T) { - //tests and resource are non-functional, preserved for reference with ongoing fwprovider work - t.Skip() - t.Parallel() - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - } - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - Steps: []resource.TestStep{ - { - Config: testAccResourceFWPubsubLiteReservation_basic(context), - }, - { - Config: testAccResourceFWPubsubLiteReservation_upgrade(context), - }, - }, - }) -} - -func testAccResourceFWPubsubLiteReservation_basic(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_fwprovider_pubsub_lite_reservation" "basic" { - name = "tf-test-example-reservation%{random_suffix}" - region = "us-central1" - project = data.google_project.project.number - throughput_capacity = 2 -} - -data "google_project" "project" { -} -`, context) -} - -func testAccResourceFWPubsubLiteReservation_upgrade(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_fwprovider_pubsub_lite_reservation" "basic" { - name = "tf-test-example-reservation%{random_suffix}" - region = "us-central1" - project = data.google_project.project.number - throughput_capacity = 3 -} - -data "google_project" "project" { -} -`, context) -} diff --git a/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_subscription_test.go b/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_subscription_test.go index c88cf2abb178..d75074ea09a4 100644 --- a/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_subscription_test.go +++ b/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_subscription_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsublite" ) func TestAccPubsubLiteSubscription_pubsubLiteSubscription_deliveryRequirement_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_topic_test.go b/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_topic_test.go index f9df101add44..eca40a8e64ba 100644 --- a/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_topic_test.go +++ b/mmv1/third_party/terraform/services/pubsublite/resource_pubsub_lite_topic_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsublite" ) func TestAccPubsubLiteTopic_pubsubLiteTopic_count_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key.go b/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key.go index 90dc53350a54..6e7b91bb458d 100644 --- a/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key.go +++ b/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key.go @@ -36,6 +36,7 @@ func ResourceRecaptchaEnterpriseKey() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, tpgresource.SetLabelsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -129,6 +130,9 @@ func ResourceRecaptchaEnterpriseKey() *schema.Resource { Computed: true, Description: "The combination of labels configured directly on the resource and default labels configured on the provider.", }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } @@ -455,9 +459,18 @@ func resourceRecaptchaEnterpriseKeyRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("error setting terraform_labels in state: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceRecaptchaEnterpriseKeyUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceRecaptchaEnterpriseKey) { + return ResourceRecaptchaEnterpriseKey().Read(d, meta) + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { @@ -509,6 +522,13 @@ func resourceRecaptchaEnterpriseKeyUpdate(d *schema.ResourceData, meta interface } func resourceRecaptchaEnterpriseKeyDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) project, err := tpgresource.GetProject(d, config) if err != nil { diff --git a/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key_meta.yaml b/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key_meta.yaml index 90e52b25a5a9..bc9b9ae86b73 100644 --- a/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key_meta.yaml +++ b/mmv1/third_party/terraform/services/recaptchaenterprise/resource_recaptcha_enterprise_key_meta.yaml @@ -26,6 +26,8 @@ fields: - api_field: 'webSettings.allowedDomains' - api_field: 'webSettings.challengeSecurityPreference' - api_field: 'webSettings.integrationType' + - field: 'deletion_policy' + provider_only: true - api_field: 'webSettings.challengeSettings.defaultSettings.scoreThreshold' - field: 'web_settings.challenge_settings.action_settings.action' provider_only: true diff --git a/mmv1/third_party/terraform/services/redis/data_source_redis_cluster_test.go b/mmv1/third_party/terraform/services/redis/data_source_redis_cluster_test.go index 96a6843297a0..2f7b5575177b 100644 --- a/mmv1/third_party/terraform/services/redis/data_source_redis_cluster_test.go +++ b/mmv1/third_party/terraform/services/redis/data_source_redis_cluster_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/redis" ) func TestAccRedisClusterDatasource(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/redis/data_source_redis_instance_test.go b/mmv1/third_party/terraform/services/redis/data_source_redis_instance_test.go index e50eed765216..091be2811394 100644 --- a/mmv1/third_party/terraform/services/redis/data_source_redis_instance_test.go +++ b/mmv1/third_party/terraform/services/redis/data_source_redis_instance_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/redis" ) func TestAccRedisInstanceDatasource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/redis/resource_redis_cluster_test.go b/mmv1/third_party/terraform/services/redis/resource_redis_cluster_test.go index 67cf96c37e26..adb17dfcb4f4 100644 --- a/mmv1/third_party/terraform/services/redis/resource_redis_cluster_test.go +++ b/mmv1/third_party/terraform/services/redis/resource_redis_cluster_test.go @@ -11,7 +11,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/networkconnectivityv1" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" "github.com/hashicorp/terraform-provider-google/google/services/redis" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/redis/resource_redis_instance_test.go b/mmv1/third_party/terraform/services/redis/resource_redis_instance_test.go index 3881c2381603..3e1a0fcc130e 100644 --- a/mmv1/third_party/terraform/services/redis/resource_redis_instance_test.go +++ b/mmv1/third_party/terraform/services/redis/resource_redis_instance_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/redis" ) func TestAccRedisInstance_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/acctest/bootstrap_iam_test_utils.go b/mmv1/third_party/terraform/services/resourcemanager/bootstrap_iam_test_utils.go similarity index 99% rename from mmv1/third_party/terraform/acctest/bootstrap_iam_test_utils.go rename to mmv1/third_party/terraform/services/resourcemanager/bootstrap_iam_test_utils.go index adf9373cbd6a..1759a7234cab 100644 --- a/mmv1/third_party/terraform/acctest/bootstrap_iam_test_utils.go +++ b/mmv1/third_party/terraform/services/resourcemanager/bootstrap_iam_test_utils.go @@ -1,4 +1,4 @@ -package acctest +package resourcemanager import ( "strconv" diff --git a/mmv1/third_party/terraform/services/resourcemanager/bootstrap_test_utils.go b/mmv1/third_party/terraform/services/resourcemanager/bootstrap_test_utils.go new file mode 100644 index 000000000000..b289bdf63e23 --- /dev/null +++ b/mmv1/third_party/terraform/services/resourcemanager/bootstrap_test_utils.go @@ -0,0 +1,132 @@ +package resourcemanager + +import ( + "strings" + "testing" + "time" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcloudbilling "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" + rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + "google.golang.org/api/cloudbilling/v1" + cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1" +) + +// BootstrapProject will create or get a project named +// "" that will persist across test runs, +// where projectIDSuffix is based off of getTestProjectFromEnv(). The reason +// for the naming is to isolate bootstrapped projects by test environment. +// Given the existing projects being used by our team, the prefix provided to +// this function can be no longer than 18 characters. +func BootstrapProject(t *testing.T, projectIDPrefix, billingAccount string, services []string) *cloudresourcemanager.Project { + org := envvar.GetTestOrgFromEnv(t) + parent := &cloudresourcemanager.ResourceId{ + Type: "organization", + Id: org, + } + projectIDSuffix := strings.Replace(envvar.GetTestProjectFromEnv(), "ci-test-project-", "", 1) + projectID := projectIDPrefix + projectIDSuffix + + return BootstrapProjectWithParent(t, projectID, billingAccount, parent, services) +} + +func BootstrapProjectWithParent(t *testing.T, projectID string, billingAccount string, parent *cloudresourcemanager.ResourceId, services []string) *cloudresourcemanager.Project { + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return nil + } + crmClient := rmClient.NewClient(config, config.UserAgent) + + project, err := crmClient.Projects.Get(projectID).Do() + if err != nil { + if !transport_tpg.IsGoogleApiErrorWithCode(err, 403) { + t.Fatalf("Error getting bootstrapped project: %s", err) + } + op, err := crmClient.Projects.Create(&cloudresourcemanager.Project{ + ProjectId: projectID, + Name: "Bootstrapped Test Project", + Parent: parent, + }).Do() + if err != nil { + t.Fatalf("Error creating bootstrapped test project: %s", err) + } + + opAsMap, err := tpgresource.ConvertToMap(op) + if err != nil { + t.Fatalf("Error converting create project operation to map: %s", err) + } + + err = ResourceManagerOperationWaitTime(config, opAsMap, "creating project", config.UserAgent, 4*time.Minute) + if err != nil { + t.Fatalf("Error waiting for create project operation: %s", err) + } + + project, err = crmClient.Projects.Get(projectID).Do() + if err != nil { + t.Fatalf("Error getting bootstrapped project: %s", err) + } + + } + + if project.LifecycleState == "DELETE_REQUESTED" { + _, err := crmClient.Projects.Undelete(projectID, &cloudresourcemanager.UndeleteProjectRequest{}).Do() + if err != nil { + t.Fatalf("Error undeleting bootstrapped project: %s", err) + } + } + + if billingAccount != "" { + billingClient := tpgcloudbilling.NewClient(config, config.UserAgent) + var pbi *cloudbilling.ProjectBillingInfo + err = transport_tpg.Retry(transport_tpg.RetryOptions{ + RetryFunc: func() error { + var reqErr error + pbi, reqErr = billingClient.Projects.GetBillingInfo(PrefixedProject(projectID)).Do() + return reqErr + }, + Timeout: 30 * time.Second, + }) + if err != nil { + t.Fatalf("Error getting billing info for project %q: %v", projectID, err) + } + if strings.TrimPrefix(pbi.BillingAccountName, "billingAccounts/") != billingAccount { + pbi.BillingAccountName = "billingAccounts/" + billingAccount + err := transport_tpg.Retry(transport_tpg.RetryOptions{ + RetryFunc: func() error { + _, err := tpgcloudbilling.NewClient(config, config.UserAgent).Projects.UpdateBillingInfo(PrefixedProject(projectID), pbi).Do() + return err + }, + Timeout: 2 * time.Minute, + }) + if err != nil { + t.Fatalf("Error setting billing account for project %q to %q: %s", projectID, billingAccount, err) + } + } + } + + if len(services) > 0 { + + enabledServices, err := ListCurrentlyEnabledServices(projectID, "", config.UserAgent, config, 1*time.Minute) + if err != nil { + t.Fatalf("Error listing services for project %q: %s", projectID, err) + } + + servicesToEnable := make([]string, 0, len(services)) + for _, service := range services { + if _, ok := enabledServices[service]; !ok { + servicesToEnable = append(servicesToEnable, service) + } + } + + if len(servicesToEnable) > 0 { + if err := EnableServiceUsageProjectServices(servicesToEnable, projectID, "", config.UserAgent, config, 10*time.Minute); err != nil { + t.Fatalf("Error enabling services for project %q: %s", projectID, err) + } + } + } + + return project +} diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_active_folder_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_active_folder_test.go index 3a65b6587f70..e256b8fe7571 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_active_folder_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_active_folder_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleActiveFolder_default(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder.go index ce15202be784..cfe239473558 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder.go @@ -64,6 +64,10 @@ func DataSourceGoogleFolder() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "deletion_policy": { + Type: schema.TypeString, + Computed: true, + }, }, } } diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_organization_policy_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_organization_policy_test.go index 998a0664879b..90c2bfa4db46 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_organization_policy_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_organization_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleFolderOrganizationPolicy_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_test.go index 79ae8c9da658..f5fc1f11f8ba 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folder_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folders_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folders_test.go index 88e59cccd32f..2fbc6a9994a1 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folders_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_folders_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleFolders_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_role_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_role_test.go index 7ea8db8fb14d..a758594e717f 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_role_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_role_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleOrganizationIamCustomRole_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_roles_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_roles_test.go index 4889291fe260..048b004dd256 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_roles_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_organization_iam_custom_roles_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleOrganizationIamCustomRoles_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_ancestry_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_ancestry_test.go index f1037373e10f..054a8518d8db 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_ancestry_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_ancestry_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleProjectAncestry_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_role_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_role_test.go index 5f58af6508de..c966322a524e 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_role_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_role_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleProjectIamCustomRole_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_roles_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_roles_test.go index b304bc5faaf2..9f85b06e0684 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_roles_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_iam_custom_roles_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleProjectIamCustomRoles_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_organization_policy_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_organization_policy_test.go index 3df058a3117b..32cb696b6b1f 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_organization_policy_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_organization_policy_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleProjectOrganizationPolicy_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_service_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_service_test.go index 600e08064826..1313f7e82327 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_service_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_service_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleProjectService_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_test.go index 5fff12bdb4c7..26d593188b9a 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_project_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleProject_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_access_token_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_access_token_test.go index a32115ce5dee..48b0044a3433 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_access_token_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_access_token_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -34,7 +35,7 @@ func TestAccDataSourceGoogleServiceAccountAccessToken_basic(t *testing.T) { resourceName := "data.google_service_account_access_token.default" serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "acctoken", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "acctoken", serviceAccount) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_id_token_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_id_token_test.go index 6b5e3598b5b0..443c81a2a60d 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_id_token_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_id_token_test.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" ) const targetAudience = "https://foo.bar/" @@ -73,7 +74,7 @@ func TestAccDataSourceGoogleServiceAccountIdToken_impersonation(t *testing.T) { resourceName := "data.google_service_account_id_token.default" serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "idtoken-imp", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "idtoken-imp", serviceAccount) resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_jwt_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_jwt_test.go index 0f9acee03abd..167a458b933d 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_jwt_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_jwt_test.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) @@ -100,7 +101,7 @@ func TestAccDataSourceGoogleServiceAccountJwt(t *testing.T) { resourceName := "data.google_service_account_jwt.default" serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "jwt", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "jwt", serviceAccount) staticTime := time.Now() diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_key_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_key_test.go index b5a03755159d..48867cd0f220 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_key_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_key_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_test.go index ffb22244691f..5e84f5e6e7ce 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_account_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDatasourceGoogleServiceAccount_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_accounts_test.go b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_accounts_test.go index 95db97448fc8..493838f9649e 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_accounts_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/data_source_google_service_accounts_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccDataSourceGoogleServiceAccounts_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_client_config_test.go b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_client_config_test.go index 65e813e4cf9f..6a609f856b03 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_client_config_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_client_config_test.go @@ -11,7 +11,7 @@ import ( func TestAccEphemeralGoogleClientConfig_basic(t *testing.T) { t.Parallel() - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -29,7 +29,7 @@ func TestAccEphemeralGoogleClientConfig_omitLocation(t *testing.T) { t.Setenv("GOOGLE_REGION", "") t.Setenv("GOOGLE_ZONE", "") - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ { @@ -46,7 +46,7 @@ func TestAccEphemeralGoogleClientConfig_invalidCredentials(t *testing.T) { badCreds := acctest.GenerateFakeCredentialsJson("test") t.Setenv("GOOGLE_CREDENTIALS", badCreds) - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -61,7 +61,7 @@ func TestAccEphemeralGoogleClientConfig_invalidCredentials(t *testing.T) { func TestAccEphemeralGoogleClientConfig_usedInProvider(t *testing.T) { t.Parallel() - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ diff --git a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_access_token_test.go b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_access_token_test.go index 8451e2fce30e..43afd0e41fa4 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_access_token_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_access_token_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" ) var defaultMaxLifetime string = "3600s" @@ -14,7 +15,7 @@ func TestAccEphemeralServiceAccountToken_basic(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "basic", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "basic", serviceAccount) context := map[string]interface{}{ "ephemeral_resource_name": "token", @@ -23,7 +24,7 @@ func TestAccEphemeralServiceAccountToken_basic(t *testing.T) { "scope_1": "https://www.googleapis.com/auth/cloud-platform", } - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), @@ -47,9 +48,9 @@ func TestAccEphemeralServiceAccountToken_withDelegates(t *testing.T) { t.Parallel() initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - delegateServiceAccountEmailOne := acctest.BootstrapServiceAccount(t, "delegate1", initialServiceAccount) // SA_2 - delegateServiceAccountEmailTwo := acctest.BootstrapServiceAccount(t, "delegate2", delegateServiceAccountEmailOne) // SA_3 - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "target", delegateServiceAccountEmailTwo) // SA_4 + delegateServiceAccountEmailOne := iambeta.BootstrapServiceAccount(t, "delegate1", initialServiceAccount) // SA_2 + delegateServiceAccountEmailTwo := iambeta.BootstrapServiceAccount(t, "delegate2", delegateServiceAccountEmailOne) // SA_3 + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "target", delegateServiceAccountEmailTwo) // SA_4 context := map[string]interface{}{ "ephemeral_resource_name": "token", @@ -59,7 +60,7 @@ func TestAccEphemeralServiceAccountToken_withDelegates(t *testing.T) { "delegate_2": delegateServiceAccountEmailTwo, } - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), @@ -82,7 +83,7 @@ func TestAccEphemeralServiceAccountToken_withCustomLifetime(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "lifetime", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "lifetime", serviceAccount) context := map[string]interface{}{ "ephemeral_resource_name": "token", @@ -91,7 +92,7 @@ func TestAccEphemeralServiceAccountToken_withCustomLifetime(t *testing.T) { "lifetime": "3600s", } - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), diff --git a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_id_token_test.go b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_id_token_test.go index ed3812140c2b..33e0ad0c48dc 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_id_token_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_id_token_test.go @@ -7,15 +7,16 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" ) func TestAccEphemeralServiceAccountIdToken_basic(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "idtoken", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "idtoken", serviceAccount) - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -30,11 +31,11 @@ func TestAccEphemeralServiceAccountIdToken_withDelegates(t *testing.T) { t.Parallel() initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - delegateServiceAccountEmailOne := acctest.BootstrapServiceAccount(t, "id-delegate1", initialServiceAccount) // SA_2 - delegateServiceAccountEmailTwo := acctest.BootstrapServiceAccount(t, "id-delegate2", delegateServiceAccountEmailOne) // SA_3 - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "id-target", delegateServiceAccountEmailTwo) // SA_4 + delegateServiceAccountEmailOne := iambeta.BootstrapServiceAccount(t, "id-delegate1", initialServiceAccount) // SA_2 + delegateServiceAccountEmailTwo := iambeta.BootstrapServiceAccount(t, "id-delegate2", delegateServiceAccountEmailOne) // SA_3 + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "id-target", delegateServiceAccountEmailTwo) // SA_4 - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -49,9 +50,9 @@ func TestAccEphemeralServiceAccountIdToken_withEmptyDelegates(t *testing.T) { t.Parallel() initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "no-del", initialServiceAccount) // SA_4 + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "no-del", initialServiceAccount) // SA_4 - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ExternalProviders: map[string]resource.ExternalProvider{ @@ -69,9 +70,9 @@ func TestAccEphemeralServiceAccountIdToken_withIncludeEmail(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "idtoken-email", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "idtoken-email", serviceAccount) - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ diff --git a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_jwt_test.go b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_jwt_test.go index f31beed7b903..6db804a583d6 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_jwt_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_jwt_test.go @@ -6,13 +6,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" ) func TestAccEphemeralServiceAccountJwt_basic(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "jwt-basic", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "jwt-basic", serviceAccount) context := map[string]interface{}{ "ephemeral_resource_name": "jwt", @@ -21,7 +22,7 @@ func TestAccEphemeralServiceAccountJwt_basic(t *testing.T) { "sub": targetServiceAccountEmail, } - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), @@ -45,9 +46,9 @@ func TestAccEphemeralServiceAccountJwt_withDelegates(t *testing.T) { t.Parallel() initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t) - delegateServiceAccountEmailOne := acctest.BootstrapServiceAccount(t, "jwt-delegate1", initialServiceAccount) // SA_2 - delegateServiceAccountEmailTwo := acctest.BootstrapServiceAccount(t, "jwt-delegate2", delegateServiceAccountEmailOne) // SA_3 - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "jwt-target", delegateServiceAccountEmailTwo) // SA_4 + delegateServiceAccountEmailOne := iambeta.BootstrapServiceAccount(t, "jwt-delegate1", initialServiceAccount) // SA_2 + delegateServiceAccountEmailTwo := iambeta.BootstrapServiceAccount(t, "jwt-delegate2", delegateServiceAccountEmailOne) // SA_3 + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "jwt-target", delegateServiceAccountEmailTwo) // SA_4 context := map[string]interface{}{ "ephemeral_resource_name": "jwt", @@ -58,7 +59,7 @@ func TestAccEphemeralServiceAccountJwt_withDelegates(t *testing.T) { "sub": targetServiceAccountEmail, } - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), @@ -81,7 +82,7 @@ func TestAccEphemeralServiceAccountJwt_withExpiresIn(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "expiry", serviceAccount) + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "expiry", serviceAccount) context := map[string]interface{}{ "ephemeral_resource_name": "jwt", @@ -91,7 +92,7 @@ func TestAccEphemeralServiceAccountJwt_withExpiresIn(t *testing.T) { "expires_in": "3600", } - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), diff --git a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_key_test.go b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_key_test.go index 474476cb0888..514263fbdc10 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_key_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/ephemeral_google_service_account_key_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccEphemeralServiceAccountKey_create(t *testing.T) { @@ -17,10 +19,13 @@ func TestAccEphemeralServiceAccountKey_create(t *testing.T) { project := envvar.GetTestProjectFromEnv() expectedServiceAccountEmail := fmt.Sprintf("%s@%s.iam.gserviceaccount.com", accountID, project) - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), + ExternalProviders: map[string]resource.ExternalProvider{ + "time": {}, + }, Steps: []resource.TestStep{ { Config: testAccEphemeralServiceAccountKey_create_setup(accountID, displayName), @@ -44,6 +49,11 @@ resource "google_service_account" "service_account" { display_name = "%s" } +resource "time_sleep" "wait_60_seconds" { + create_duration = "60s" + depends_on = [google_service_account.service_account] +} + `, accountID, displayName) } @@ -54,6 +64,11 @@ resource "google_service_account" "service_account" { display_name = "%s" } +resource "time_sleep" "wait_60_seconds" { + create_duration = "60s" + depends_on = [google_service_account.service_account] +} + ephemeral "google_service_account_key" "key" { service_account_id = google_service_account.service_account.email public_key_type = "TYPE_X509_PEM_FILE" @@ -69,7 +84,7 @@ func TestAccEphemeralServiceAccountKey_upload(t *testing.T) { project := envvar.GetTestProjectFromEnv() expectedServiceAccountEmail := fmt.Sprintf("%s@%s.iam.gserviceaccount.com", accountID, project) - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), @@ -98,8 +113,8 @@ resource "google_service_account" "service_account" { account_id = "%s" display_name = "%s" } -resource "time_sleep" "wait_30_seconds" { - create_duration = "30s" +resource "time_sleep" "wait_60_seconds" { + create_duration = "60s" depends_on = [google_service_account.service_account] } `, accountID, displayName) @@ -111,8 +126,8 @@ resource "google_service_account" "service_account" { account_id = "%s" display_name = "%s" } -resource "time_sleep" "wait_30_seconds" { - create_duration = "30s" +resource "time_sleep" "wait_60_seconds" { + create_duration = "60s" depends_on = [google_service_account.service_account] } @@ -127,8 +142,8 @@ func TestAccEphemeralServiceAccountKey_fetch(t *testing.T) { t.Parallel() serviceAccount := envvar.GetTestServiceAccountFromEnv(t) - targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "key-basic", serviceAccount) - resource.Test(t, resource.TestCase{ + targetServiceAccountEmail := iambeta.BootstrapServiceAccount(t, "key-basic", serviceAccount) + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(t), diff --git a/mmv1/third_party/terraform/services/resourcemanager/iam_folder.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/iam_folder.go.tmpl index b91a72b5882e..9530a5b94593 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/iam_folder.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/iam_folder.go.tmpl @@ -49,6 +49,19 @@ func FolderIdParseFunc(d *schema.ResourceData, _ *transport_tpg.Config) error { return nil } +// FolderIamParentResourceIdentityParser returns the parent folder's id +func FolderIamParentResourceIdentityParser(d *schema.ResourceData, identity *schema.IdentityData, _ *transport_tpg.Config) (string, error) { + v, ok := identity.GetOk("folder") + if !ok { + return "", fmt.Errorf("import identity is missing attribute %q", "folder") + } + s, ok := v.(string) + if !ok || s == "" { + return "", fmt.Errorf("import identity attribute %q must be a non-empty string", "folder") + } + return CanonicalFolderId(s), nil +} + func (u *FolderIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { userAgent, err := tpgresource.GenerateUserAgentString(u.d, u.Config.UserAgent) if err != nil { @@ -158,7 +171,7 @@ func init() { Name: "google_folder_iam_member", ProductName: "resourcemanager", Type: registry.SchemaTypeIAMResource, - Schema: tpgiamresource.ResourceIamMember(IamFolderSchema, NewFolderIamUpdater, FolderIdParseFunc), + Schema: tpgiamresource.ResourceIamMember(IamFolderSchema, NewFolderIamUpdater, FolderIdParseFunc, tpgiamresource.IamWithBatching, tpgiamresource.IamWithParentResourceIdentity(FolderIamParentResourceIdentityParser)), }.Register() registry.Schema{ Name: "google_folder_iam_policy", diff --git a/mmv1/third_party/terraform/services/resourcemanager/iam_project.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/iam_project.go.tmpl index 6c481c2b15a1..6a011b062036 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/iam_project.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/iam_project.go.tmpl @@ -45,6 +45,19 @@ func ProjectIdParseFunc(d *schema.ResourceData, _ *transport_tpg.Config) error { return nil } +// ProjectIamParentParentResourceIdentityParser returns the parent project's id +func ProjectIamParentResourceIdentityParser(d *schema.ResourceData, identity *schema.IdentityData, _ *transport_tpg.Config) (string, error) { + v, ok := identity.GetOk("project") + if !ok { + return "", fmt.Errorf("import identity is missing attribute %q", "project") + } + s, ok := v.(string) + if !ok || s == "" { + return "", fmt.Errorf("import identity attribute %q must be a non-empty string", "project") + } + return s, nil +} + func (u *ProjectIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { projectId := tpgresource.GetResourceNameFromSelfLink(u.resourceId) @@ -121,19 +134,19 @@ func init() { Name: "google_project_iam_member", ProductName: "resourcemanager", Type: registry.SchemaTypeIAMResource, - Schema: tpgiamresource.ResourceIamMember(IamProjectSchema, NewProjectIamUpdater, ProjectIdParseFunc, tpgiamresource.IamWithBatching), + Schema: tpgiamresource.ResourceIamMember(IamProjectSchema, NewProjectIamUpdater, ProjectIdParseFunc, tpgiamresource.IamWithBatching, tpgiamresource.IamWithParentResourceIdentity(ProjectIamParentResourceIdentityParser)), }.Register() registry.Schema{ Name: "google_project_iam_binding", ProductName: "resourcemanager", Type: registry.SchemaTypeIAMResource, - Schema: tpgiamresource.ResourceIamBinding(IamProjectSchema, NewProjectIamUpdater, ProjectIdParseFunc, tpgiamresource.IamWithBatching), + Schema: tpgiamresource.ResourceIamBinding(IamProjectSchema, NewProjectIamUpdater, ProjectIdParseFunc, tpgiamresource.IamWithBatching, tpgiamresource.IamWithParentResourceIdentity(ProjectIamParentResourceIdentityParser)), }.Register() registry.Schema{ Name: "google_project_iam_policy", ProductName: "resourcemanager", Type: registry.SchemaTypeIAMResource, - Schema: tpgiamresource.ResourceIamPolicy(IamProjectSchema, NewProjectIamUpdater, ProjectIdParseFunc), + Schema: tpgiamresource.ResourceIamPolicy(IamProjectSchema, NewProjectIamUpdater, ProjectIdParseFunc, tpgiamresource.IamWithParentResourceIdentity(ProjectIamParentResourceIdentityParser)), }.Register() registry.Schema{ Name: "google_project_iam_policy", diff --git a/mmv1/third_party/terraform/services/resourcemanager/list_google_service_account.go b/mmv1/third_party/terraform/services/resourcemanager/list_google_service_account.go index 0caba8bd657d..9a5315f39834 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/list_google_service_account.go +++ b/mmv1/third_party/terraform/services/resourcemanager/list_google_service_account.go @@ -17,6 +17,7 @@ import ( "google.golang.org/api/iam/v1" "github.com/hashicorp/terraform-provider-google/google/registry" + "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -91,7 +92,7 @@ func flattenGoogleServiceAccountListItem(res map[string]interface{}, d *schema.R return err } d.SetId(sa.Name) - return populateResourceData(d, &sa) + return populateResourceData(d, &sa, config) } func ListServiceAccounts(config *transport_tpg.Config, project string, callback func(rd *schema.ResourceData) error) error { @@ -104,7 +105,7 @@ func ListServiceAccounts(config *transport_tpg.Config, project string, callback return fmt.Errorf("error setting project on temporary resource data: %w", err) } } - url, err := tpgresource.ReplaceVars(d, config, "{{IAMBetaBasePath}}projects/{{project}}/serviceAccounts") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(iambeta.Product, config)+"projects/{{project}}/serviceAccounts") if err != nil { return err } @@ -125,6 +126,7 @@ func ListServiceAccounts(config *transport_tpg.Config, project string, callback return transport_tpg.ListPages(transport_tpg.ListPagesOptions{ Config: config, TempData: d, + Resource: ResourceGoogleServiceAccount(), ListURL: url, BillingProject: billingProject, UserAgent: userAgent, diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_folder_service_identity_test.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/resource_folder_service_identity_test.go.tmpl index e2073df44189..8f35bdba8e4c 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_folder_service_identity_test.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_folder_service_identity_test.go.tmpl @@ -6,6 +6,7 @@ import ( "strings" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount.go index 79a43f868613..4534d73c7366 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount.go @@ -5,8 +5,8 @@ import ( "strings" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-google/google/registry" cloudbilling_tpg "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" @@ -26,6 +26,10 @@ func ResourceBillingSubaccount() *schema.Resource { State: schema.ImportStatePassthrough, }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy(""), + ), + Schema: map[string]*schema.Schema{ "display_name": { Type: schema.TypeString, @@ -37,12 +41,9 @@ func ResourceBillingSubaccount() *schema.Resource { ForceNew: true, DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, }, - "deletion_policy": { - Type: schema.TypeString, - Optional: true, - Default: "", - ValidateFunc: validation.StringInSlice([]string{"RENAME_ON_DESTROY", ""}, false), - }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry(""), + //UDP schema end "billing_account_id": { Type: schema.TypeString, Computed: true, @@ -115,10 +116,19 @@ func resourceBillingSubaccountRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error setting billing_account_id: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, ""); err != nil { + return err + } + return nil } func resourceBillingSubaccountUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceBillingSubaccount) { + return ResourceBillingSubaccount().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -138,6 +148,13 @@ func resourceBillingSubaccountUpdate(d *schema.ResourceData, meta interface{}) e } func resourceBillingSubaccountDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_meta.yaml index 54acc37b05a3..9f80ce507521 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_meta.yaml @@ -6,7 +6,9 @@ api_resource_type_kind: 'BillingAccount' fields: - field: 'billing_account_id' - field: 'deletion_policy' + provider_only: true - api_field: 'displayName' - api_field: 'masterBillingAccount' - api_field: 'name' - api_field: 'open' + diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_test.go index 30650569fa14..e215478e5dec 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_billing_subaccount_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/cloudbilling" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder.go index 5e5845f7f1ad..e8871624a68a 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" @@ -27,6 +28,10 @@ func ResourceGoogleFolder() *schema.Resource { State: resourceGoogleFolderImportState, }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(4 * time.Minute), Update: schema.DefaultTimeout(4 * time.Minute), @@ -93,6 +98,9 @@ func ResourceGoogleFolder() *schema.Resource { Computed: true, Description: `The Management Project associated with the folder's configured capabilities.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -201,6 +209,10 @@ func resourceGoogleFolderRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error setting management_project: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -211,7 +223,7 @@ func resourceGoogleFolderUpdate(d *schema.ResourceData, meta interface{}) error return err } - clientSideFields := map[string]bool{"deletion_protection": true} + clientSideFields := map[string]bool{"deletion_protection": true, "deletion_policy": true} clientSideOnly := true for field := range ResourceGoogleFolder().Schema { if d.HasChange(field) && !clientSideFields[field] { @@ -274,6 +286,13 @@ func resourceGoogleFolderUpdate(d *schema.ResourceData, meta interface{}) error } func resourceGoogleFolderDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_audit_config_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_audit_config_test.go index 30358b6b0a59..075948afc872 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_audit_config_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_audit_config_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_member_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_member_test.go index c9f305e81f2a..38f2add6a4db 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_member_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_member_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "google.golang.org/api/cloudresourcemanager/v1" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_policy_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_policy_test.go index 2ab726397133..fb6c6fcc53d2 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_policy_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_iam_policy_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/resourcemanagerv3" cloudresourcemanagerv3 "google.golang.org/api/cloudresourcemanager/v3" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_meta.yaml index 467d4c9b6159..5e23a436ec84 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_meta.yaml @@ -14,3 +14,5 @@ fields: - api_field: 'name' - api_field: 'parent' - api_field: 'tags' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy.go index 928111d35b10..7be4c2ce86e6 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy.go @@ -4,6 +4,7 @@ import ( "fmt" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" @@ -30,6 +31,10 @@ func ResourceGoogleFolderOrganizationPolicy() *schema.Resource { Delete: schema.DefaultTimeout(4 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: tpgresource.MergeSchemas( schemaOrganizationPolicy, map[string]*schema.Schema{ @@ -39,6 +44,9 @@ func ResourceGoogleFolderOrganizationPolicy() *schema.Resource { ForceNew: true, Description: `The resource name of the folder to set the policy for. Its format is folders/{folder_id}.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, ), UseJSONNumber: true, @@ -125,10 +133,19 @@ func resourceGoogleFolderOrganizationPolicyRead(d *schema.ResourceData, meta int return fmt.Errorf("Error setting update_time: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceGoogleFolderOrganizationPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGoogleFolderOrganizationPolicy) { + return ResourceGoogleFolderOrganizationPolicy().Read(d, meta) + } + if isOrganizationPolicyUnset(d) { return resourceGoogleFolderOrganizationPolicyDelete(d, meta) } @@ -141,6 +158,13 @@ func resourceGoogleFolderOrganizationPolicyUpdate(d *schema.ResourceData, meta i } func resourceGoogleFolderOrganizationPolicyDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy_meta.yaml index 6c28890c3407..5ffcc0aa1d6a 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_organization_policy_meta.yaml @@ -17,3 +17,5 @@ fields: - field: 'restore_policy.default' - api_field: 'updateTime' - field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_test.go index 566aebb4de8c..22125f2fe219 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_folder_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/resourcemanagerv3" "github.com/hashicorp/terraform-provider-google/google/services/tags" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_audit_config_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_audit_config_test.go index e92e205c67c5..cf206145c60b 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_audit_config_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_audit_config_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role.go index 98251ec9d56e..8138fc2b152d 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role.go @@ -3,6 +3,7 @@ package resourcemanager import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-google/google/registry" @@ -33,6 +34,10 @@ func ResourceGoogleOrganizationIamCustomRole() *schema.Resource { State: schema.ImportStatePassthrough, }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "role_id": { Type: schema.TypeString, @@ -82,6 +87,9 @@ func ResourceGoogleOrganizationIamCustomRole() *schema.Resource { Computed: true, Description: `The name of the role in the format organizations/{{org_id}}/roles/{{role_id}}. Like id, this field can be used as a reference in other resources such as IAM role bindings.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -180,10 +188,19 @@ func resourceGoogleOrganizationIamCustomRoleRead(d *schema.ResourceData, meta in return fmt.Errorf("Error setting deleted: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceGoogleOrganizationIamCustomRoleUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGoogleOrganizationIamCustomRole) { + return ResourceGoogleOrganizationIamCustomRole().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -224,6 +241,13 @@ func resourceGoogleOrganizationIamCustomRoleUpdate(d *schema.ResourceData, meta } func resourceGoogleOrganizationIamCustomRoleDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_meta.yaml index 4752a35a2b44..478e57f9aa19 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_meta.yaml @@ -12,3 +12,5 @@ fields: - field: 'role_id' - api_field: 'stage' - api_field: 'title' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_test.go index e668b6289f5b..08800145590f 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_custom_role_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_test.go index 8fd896105af0..c7b461e3f222 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_iam_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" "github.com/hashicorp/terraform-provider-google/google/tpgiamresource" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy.go index 43d119933ec1..6a74ecfae172 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy.go @@ -5,6 +5,7 @@ import ( "strings" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" @@ -165,6 +166,10 @@ func ResourceGoogleOrganizationPolicy() *schema.Resource { Delete: schema.DefaultTimeout(4 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: tpgresource.MergeSchemas( schemaOrganizationPolicy, map[string]*schema.Schema{ @@ -173,6 +178,9 @@ func ResourceGoogleOrganizationPolicy() *schema.Resource { Required: true, ForceNew: true, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }), UseJSONNumber: true, } @@ -235,10 +243,19 @@ func resourceGoogleOrganizationPolicyRead(d *schema.ResourceData, meta interface return fmt.Errorf("Error setting restore_policy: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceGoogleOrganizationPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGoogleOrganizationPolicy) { + return ResourceGoogleOrganizationPolicy().Read(d, meta) + } + if isOrganizationPolicyUnset(d) { return resourceGoogleOrganizationPolicyDelete(d, meta) } @@ -251,6 +268,13 @@ func resourceGoogleOrganizationPolicyUpdate(d *schema.ResourceData, meta interfa } func resourceGoogleOrganizationPolicyDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy_meta.yaml index b91c4f6ba9ab..7b126dac08a5 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_organization_policy_meta.yaml @@ -17,3 +17,5 @@ fields: - field: 'restore_policy.default' - api_field: 'updateTime' - field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project.go index c025fb368b78..10a8f08c23eb 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project.go @@ -46,6 +46,7 @@ func ResourceGoogleProject() *schema.Resource { Delete: resourceGoogleProjectDelete, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("PREVENT"), tpgresource.SetLabelsDiff, ), @@ -72,8 +73,8 @@ func ResourceGoogleProject() *schema.Resource { }, "deletion_policy": { Type: schema.TypeString, + Computed: true, Optional: true, - Default: "PREVENT", Description: `The deletion policy for the Project. Setting PREVENT will protect the project against any destroy actions caused by a terraform apply or terraform destroy. Setting ABANDON allows the resource to be abandoned rather than deleted. Possible values are: "PREVENT", "ABANDON", "DELETE"`, ValidateFunc: validation.StringInSlice([]string{"PREVENT", "ABANDON", "DELETE"}, false), @@ -323,11 +324,11 @@ func resourceGoogleProjectRead(d *schema.ResourceData, meta interface{}) error { return nil } // Explicitly set client-side fields to default values if unset - if _, ok := d.GetOkExists("deletion_policy"); !ok { - if err := d.Set("deletion_policy", "PREVENT"); err != nil { - return fmt.Errorf("Error setting deletion_policy: %s", err) - } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "PREVENT"); err != nil { + return err } + if err := d.Set("project_id", pid); err != nil { return fmt.Errorf("Error setting project_id: %s", err) } diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_audit_config_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_audit_config_test.go index 5b8dd41cf342..cf951e1b4552 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_audit_config_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_audit_config_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_binding_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_binding_test.go index 31b935ca707a..7fea52ae0e02 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_binding_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_binding_test.go @@ -4,10 +4,12 @@ import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "regexp" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/tfversion" ) func projectIamBindingImportStep(resourceName, pid, role string) resource.TestStep { @@ -28,6 +30,9 @@ func TestAccProjectIamBinding_basic(t *testing.T) { role := "roles/compute.instanceAdmin" member := "user:admin@hashicorptest.com" acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.SkipBelow(tfversion.Version1_12_0), + }, PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -43,6 +48,11 @@ func TestAccProjectIamBinding_basic(t *testing.T) { Config: testAccProjectAssociateBindingBasic(pid, org, role, member), }, projectIamBindingImportStep("google_project_iam_binding.acceptance", pid, role), + { + ResourceName: "google_project_iam_binding.acceptance", + ImportState: true, + ImportStateKind: resource.ImportBlockWithResourceIdentity, + }, }, }) } diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role.go index 7b04cf48c4ba..f6314b8a26c0 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role.go @@ -28,6 +28,7 @@ func ResourceGoogleProjectIamCustomRole() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -80,6 +81,9 @@ func ResourceGoogleProjectIamCustomRole() *schema.Resource { Computed: true, Description: `The name of the role in the format projects/{{project}}/roles/{{role_id}}. Like id, this field can be used as a reference in other resources such as IAM role bindings.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -180,10 +184,19 @@ func resourceGoogleProjectIamCustomRoleRead(d *schema.ResourceData, meta interfa return fmt.Errorf("Error setting project: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceGoogleProjectIamCustomRoleUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGoogleProjectIamCustomRole) { + return ResourceGoogleProjectIamCustomRole().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -223,6 +236,13 @@ func resourceGoogleProjectIamCustomRoleUpdate(d *schema.ResourceData, meta inter } func resourceGoogleProjectIamCustomRoleDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_meta.yaml index 8b73e1e6340c..d34bfdd5abe5 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_meta.yaml @@ -12,3 +12,5 @@ fields: - field: 'role_id' - api_field: 'stage' - api_field: 'title' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_test.go index 575b489d1f96..aa9dc9bad323 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_custom_role_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccProjectIamCustomRole_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_remove_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_remove_test.go index fd8b00f89060..58c8f62e1a5a 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_remove_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_remove_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_test.go index 443f1f6febc6..c56c694af000 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_member_test.go @@ -2,12 +2,15 @@ package resourcemanager_test import ( "fmt" - "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/envvar" "regexp" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/tfversion" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func projectIamMemberImportStep(resourceName, pid, role, member string) resource.TestStep { @@ -19,6 +22,20 @@ func projectIamMemberImportStep(resourceName, pid, role, member string) resource } } +func projectIamMemberIdentityImportStep(resourceName string) resource.TestStep { + return resource.TestStep{ + ResourceName: resourceName, + ImportState: true, + ImportStateKind: resource.ImportBlockWithResourceIdentity, + } +} + +func projectIamMemberTerraformVersionChecks() []tfversion.TerraformVersionCheck { + return []tfversion.TerraformVersionCheck{ + tfversion.SkipBelow(tfversion.Version1_12_0), + } +} + // Test that an IAM binding can be applied to a project func TestAccProjectIamMember_basic(t *testing.T) { t.Parallel() @@ -29,6 +46,7 @@ func TestAccProjectIamMember_basic(t *testing.T) { role := "roles/compute.instanceAdmin" member := "user:admin@hashicorptest.com" acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: projectIamMemberTerraformVersionChecks(), PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -44,6 +62,7 @@ func TestAccProjectIamMember_basic(t *testing.T) { Config: testAccProjectAssociateMemberBasic(pid, org, role, member), }, projectIamMemberImportStep(resourceName, pid, role, member), + projectIamMemberIdentityImportStep(resourceName), }, }) } @@ -65,6 +84,7 @@ func TestAccProjectIamMember_multiple(t *testing.T) { member2 := "user:gterraformtest1@gmail.com" acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: projectIamMemberTerraformVersionChecks(), PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -80,13 +100,16 @@ func TestAccProjectIamMember_multiple(t *testing.T) { Config: testAccProjectAssociateMemberBasic(pid, org, role, member), }, projectIamMemberImportStep(resourceName, pid, role, member), + projectIamMemberIdentityImportStep(resourceName), // Apply another IAM binding { Config: testAccProjectAssociateMemberMultiple(pid, org, role, member, role, member2), }, projectIamMemberImportStep(resourceName, pid, role, member), + projectIamMemberIdentityImportStep(resourceName), projectIamMemberImportStep(resourceName2, pid, role, member2), + projectIamMemberIdentityImportStep(resourceName2), }, }) } @@ -107,6 +130,7 @@ func TestAccProjectIamMember_remove(t *testing.T) { member2 := "user:gterraformtest1@gmail.com" acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: projectIamMemberTerraformVersionChecks(), PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -123,7 +147,9 @@ func TestAccProjectIamMember_remove(t *testing.T) { Config: testAccProjectAssociateMemberMultiple(pid, org, role, member, role, member2), }, projectIamMemberImportStep(resourceName, pid, role, member), + projectIamMemberIdentityImportStep(resourceName), projectIamMemberImportStep(resourceName, pid, role, member2), + projectIamMemberIdentityImportStep(resourceName), // Remove the bindings { @@ -146,6 +172,7 @@ func TestAccProjectIamMember_withCondition(t *testing.T) { member := "user:admin@hashicorptest.com" conditionTitle := "expires_after_2019_12_31" acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: projectIamMemberTerraformVersionChecks(), PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -166,6 +193,7 @@ func TestAccProjectIamMember_withCondition(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + projectIamMemberIdentityImportStep(resourceName), }, }) } diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_policy_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_policy_test.go index fadec307ccd0..461fee52a22a 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_policy_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_iam_policy_test.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-plugin-testing/tfversion" "google.golang.org/api/cloudresourcemanager/v1" ) @@ -24,6 +25,9 @@ func TestAccProjectIamPolicy_basic(t *testing.T) { pid := fmt.Sprintf("tf-test-%d", acctest.RandInt(t)) member := "user:evanbrown@google.com" acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.SkipBelow(tfversion.Version1_12_0), + }, PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -44,6 +48,11 @@ func TestAccProjectIamPolicy_basic(t *testing.T) { ResourceName: "google_project_iam_policy.acceptance", ImportState: true, }, + { + ResourceName: "google_project_iam_policy.acceptance", + ImportState: true, + ImportStateKind: resource.ImportBlockWithResourceIdentity, + }, }, }) } diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy.go index 29f7b4239d94..0a25e5c486c9 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy.go @@ -4,6 +4,7 @@ import ( "fmt" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" @@ -30,6 +31,10 @@ func ResourceGoogleProjectOrganizationPolicy() *schema.Resource { Delete: schema.DefaultTimeout(4 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: tpgresource.MergeSchemas( schemaOrganizationPolicy, map[string]*schema.Schema{ @@ -39,6 +44,9 @@ func ResourceGoogleProjectOrganizationPolicy() *schema.Resource { ForceNew: true, Description: `The project ID.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, ), UseJSONNumber: true, @@ -122,10 +130,19 @@ func resourceGoogleProjectOrganizationPolicyRead(d *schema.ResourceData, meta in return fmt.Errorf("Error setting update_time: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceGoogleProjectOrganizationPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGoogleProjectOrganizationPolicy) { + return ResourceGoogleProjectOrganizationPolicy().Read(d, meta) + } + if isOrganizationPolicyUnset(d) { return resourceGoogleProjectOrganizationPolicyDelete(d, meta) } @@ -138,6 +155,13 @@ func resourceGoogleProjectOrganizationPolicyUpdate(d *schema.ResourceData, meta } func resourceGoogleProjectOrganizationPolicyDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy_meta.yaml index 8195fa41dd15..89d3d6d6fa64 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_organization_policy_meta.yaml @@ -17,3 +17,5 @@ fields: - field: 'restore_policy.default' - api_field: 'updateTime' - field: 'version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service.go.tmpl index 953927755435..425f4ea82f26 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service.go.tmpl @@ -95,6 +95,7 @@ func ResourceGoogleProjectService() *schema.Resource { }, CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), tpgresource.DefaultProviderProject, ), @@ -128,6 +129,9 @@ func ResourceGoogleProjectService() *schema.Resource { Optional: true, }, {{- end }} + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -236,8 +240,12 @@ func resourceGoogleProjectServiceRead(d *schema.ResourceData, meta interface{}) if err := d.Set("service", srv); err != nil { return fmt.Errorf("Error setting service: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } return nil } + log.Printf("[DEBUG] service %s not in enabled services for project %s, removing from state", srv, project) d.SetId("") @@ -245,6 +253,13 @@ func resourceGoogleProjectServiceRead(d *schema.ResourceData, meta interface{}) } func resourceGoogleProjectServiceDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) if disable := d.Get("disable_on_destroy"); !(disable.(bool)) { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service_meta.yaml.tmpl b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service_meta.yaml.tmpl index 6ba459f1c3f6..3c31df6a8582 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_project_service_meta.yaml.tmpl @@ -13,3 +13,5 @@ fields: - field: 'disable_on_destroy' - field: 'project' - field: 'service' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account.go index 8a36837e81ea..36d4a42cf61d 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account.go @@ -2,6 +2,7 @@ package resourcemanager import ( "context" + "errors" "fmt" "log" "strings" @@ -35,6 +36,7 @@ func ResourceGoogleServiceAccount() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, resourceServiceAccountCustomDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Identity: &schema.ResourceIdentity{ @@ -111,6 +113,9 @@ func ResourceGoogleServiceAccount() *schema.Resource { Computed: false, Description: `If set to true, skip service account creation if a service account with the same email already exists.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -157,7 +162,7 @@ func resourceGoogleServiceAccountCreate(d *schema.ResourceData, meta interface{} } d.SetId(sa.Name) - return populateResourceData(d, sa) + return populateResourceData(d, sa, config) }, Timeout: d.Timeout(schema.TimeoutCreate), ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{ @@ -172,7 +177,7 @@ func resourceGoogleServiceAccountCreate(d *schema.ResourceData, meta interface{} } d.SetId(sa.Name) - populateResourceData(d, sa) + populateResourceData(d, sa, config) // We poll until the resource is found due to eventual consistency issue // on part of the api https://cloud.google.com/iam/docs/overview#consistency. @@ -205,12 +210,21 @@ func resourceServiceAccountPollRead(d *schema.ResourceData, meta interface{}) tr } // Confirm the service account exists - _, err = iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Get(d.Id()).Do() + sa, err := iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Get(d.Id()).Do() if err != nil { return nil, err } - return nil, nil + resp := map[string]interface{}{ + "email": sa.Email, + "unique_id": sa.UniqueId, + "project": sa.ProjectId, + "name": sa.Name, + "display_name": sa.DisplayName, + "description": sa.Description, + "disabled": sa.Disabled, + } + return resp, nil } } @@ -227,10 +241,10 @@ func resourceGoogleServiceAccountRead(d *schema.ResourceData, meta interface{}) return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Service Account %q", d.Id())) } - return populateResourceData(d, sa) + return populateResourceData(d, sa, config) } -func populateResourceData(d *schema.ResourceData, sa *iam.ServiceAccount) error { +func populateResourceData(d *schema.ResourceData, sa *iam.ServiceAccount, config *transport_tpg.Config) error { if err := d.Set("email", sa.Email); err != nil { return fmt.Errorf("Error setting email: %s", err) } @@ -259,6 +273,10 @@ func populateResourceData(d *schema.ResourceData, sa *iam.ServiceAccount) error return fmt.Errorf("Error setting member: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return tpgresource.SetResourceIdentityAttributes(d, map[string]interface{}{ "email": sa.Email, "project": sa.ProjectId, @@ -266,6 +284,13 @@ func populateResourceData(d *schema.ResourceData, sa *iam.ServiceAccount) error } func resourceGoogleServiceAccountDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -285,6 +310,11 @@ func resourceGoogleServiceAccountDelete(d *schema.ResourceData, meta interface{} } func resourceGoogleServiceAccountUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceGoogleServiceAccount) { + return ResourceGoogleServiceAccount().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -295,30 +325,39 @@ func resourceGoogleServiceAccountUpdate(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error retrieving service account %q: %s", d.Id(), err) } updateMask := make([]string, 0) + updatedFields := make(map[string]interface{}) if d.HasChange("description") { updateMask = append(updateMask, "description") + updatedFields["description"] = d.Get("description") } if d.HasChange("display_name") { updateMask = append(updateMask, "display_name") + updatedFields["display_name"] = d.Get("display_name") } // We want to skip the Patch Call below if only the disabled field has been changed - if d.HasChange("disabled") && !d.Get("disabled").(bool) { - _, err = iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Enable(d.Id(), - &iam.EnableServiceAccountRequest{}).Do() - if err != nil { - return err - } - } else if d.HasChange("disabled") && d.Get("disabled").(bool) { - _, err = iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Disable(d.Id(), - &iam.DisableServiceAccountRequest{}).Do() - if err != nil { - return err + if d.HasChange("disabled") { + updatedFields["display_name"] = d.Get("disabled") + if !d.Get("disabled").(bool) { + _, err = iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Enable(d.Id(), + &iam.EnableServiceAccountRequest{}).Do() + if err != nil { + return err + } + } else { + _, err = iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Disable(d.Id(), + &iam.DisableServiceAccountRequest{}).Do() + if err != nil { + return err + } } } if len(updateMask) == 0 { - return nil + return tpgresource.SetResourceIdentityAttributes(d, map[string]interface{}{ + "email": sa.Email, + "project": sa.ProjectId, + }) } _, err = iambeta.NewClient(config, userAgent).Projects.ServiceAccounts.Patch(d.Id(), @@ -333,6 +372,22 @@ func resourceGoogleServiceAccountUpdate(d *schema.ResourceData, meta interface{} if err != nil { return err } + + // We poll until the updated resource is found due to eventual consistency issue + // on part of the api https://cloud.google.com/iam/docs/overview#consistency. + // Wait for at least 3 successful responses in a row to ensure result is consistent. + err = transport_tpg.PollingWaitTime( + resourceServiceAccountPollRead(d, meta), + pollCheckForUpdates(updatedFields), + "Updating Service Account", + 1*time.Minute, + 3, // Number of consecutive occurences. + ) + + if err != nil { + return err + } + // This API is meant to be synchronous, but in practice it shows the old value for // a few milliseconds after the update goes through. 5 seconds is more than enough // time to ensure following reads are correct. @@ -344,6 +399,33 @@ func resourceGoogleServiceAccountUpdate(d *schema.ResourceData, meta interface{} }) } +func pollCheckForUpdates(updates map[string]interface{}) transport_tpg.PollCheckResponseFunc { + return func(resp map[string]interface{}, respErr error) transport_tpg.PollResult { + if respErr != nil { + return transport_tpg.ErrorPollResult(respErr) + } + + if resp == nil { + return transport_tpg.ErrorPollResult(errors.New("Polling did not return a response")) + } + + for key, updatedValue := range updates { + currentValue, exists := resp[key] + if !exists { + return transport_tpg.ErrorPollResult(fmt.Errorf("Field '%s' was not included in the response", key)) + } + + if currentValue != updatedValue { + return transport_tpg.PendingStatusPollResult( + fmt.Sprintf("Field '%s' is not updated. Expected '%s' but was '%s'", + key, updatedValue, currentValue)) + } + } + + return transport_tpg.SuccessPollResult() + } +} + func resourceGoogleServiceAccountImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { config := meta.(*transport_tpg.Config) if err := tpgresource.ParseImportId([]string{ diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_iam_test.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_iam_test.go.tmpl index e636e7cfeab0..85cd080dc9d8 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_iam_test.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_iam_test.go.tmpl @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/services/iambeta" "github.com/hashicorp/terraform-provider-google/google/tpgiamresource" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key.go index 1f0dced69c39..0efbe3851323 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "google.golang.org/api/iam/v1" @@ -19,7 +20,13 @@ func ResourceGoogleServiceAccountKey() *schema.Resource { return &schema.Resource{ Create: resourceGoogleServiceAccountKeyCreate, Read: resourceGoogleServiceAccountKeyRead, + Update: resourceGoogleServiceAccountKeyUpdate, Delete: resourceGoogleServiceAccountKeyDelete, + + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ // Required "service_account_id": { @@ -93,6 +100,9 @@ func ResourceGoogleServiceAccountKey() *schema.Resource { Computed: true, Description: `The key can be used before this timestamp. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z".`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -191,10 +201,30 @@ func resourceGoogleServiceAccountKeyRead(d *schema.ResourceData, meta interface{ if err := d.Set("public_key", sak.PublicKeyData); err != nil { return fmt.Errorf("Error setting public_key: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceGoogleServiceAccountKeyUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceGoogleServiceAccountKeyRead(d, meta) +} + +//UDP update end + func resourceGoogleServiceAccountKeyDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_meta.yaml index cd9d8dde4c7c..7b1cb130f82b 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_meta.yaml @@ -15,3 +15,5 @@ fields: - field: 'service_account_id' - field: 'valid_after' - field: 'valid_before' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_test.go index 2b17b56c6c10..663f22ae200c 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_key_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/services/iambeta" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) // Test that a service account key can be created and destroyed diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_meta.yaml b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_meta.yaml index d08cb722b1e3..74c39593e4f5 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_meta.yaml +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_google_service_account_meta.yaml @@ -16,3 +16,5 @@ fields: - api_field: 'name' - field: 'project' - api_field: 'uniqueId' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_organization_service_identity_test.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/resource_organization_service_identity_test.go.tmpl index aa189bea36de..4965a9109d57 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_organization_service_identity_test.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_organization_service_identity_test.go.tmpl @@ -6,6 +6,7 @@ import ( "strings" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_project_service_identity_test.go.tmpl b/mmv1/third_party/terraform/services/resourcemanager/resource_project_service_identity_test.go.tmpl index 0f77cbabb84b..188d3d04632a 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_project_service_identity_test.go.tmpl +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_project_service_identity_test.go.tmpl @@ -6,6 +6,7 @@ import ( "strings" "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/resourcemanager/resource_resourcemanager_lien_test.go b/mmv1/third_party/terraform/services/resourcemanager/resource_resourcemanager_lien_test.go index 1db2cf5ec517..897e3b37c95c 100644 --- a/mmv1/third_party/terraform/services/resourcemanager/resource_resourcemanager_lien_test.go +++ b/mmv1/third_party/terraform/services/resourcemanager/resource_resourcemanager_lien_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/resourcemanagerv3/resource_resource_manager_capability_test.go b/mmv1/third_party/terraform/services/resourcemanagerv3/resource_resource_manager_capability_test.go index 587c72d9e33b..dee2c8503e67 100644 --- a/mmv1/third_party/terraform/services/resourcemanagerv3/resource_resource_manager_capability_test.go +++ b/mmv1/third_party/terraform/services/resourcemanagerv3/resource_resource_manager_capability_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanagerv3" ) func TestAccResourceManagerCapability_resourceManagerCapabilityExample_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_config_test.go.tmpl b/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_config_test.go.tmpl index d0805bb801f3..94ba1e99cd42 100644 --- a/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_config_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/runtimeconfig" ) func TestAccRuntimeconfigConfigDatasource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_variable_test.go.tmpl b/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_variable_test.go.tmpl index 43fad694550d..57f4e0da4966 100644 --- a/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_variable_test.go.tmpl +++ b/mmv1/third_party/terraform/services/runtimeconfig/data_source_runtimeconfig_variable_test.go.tmpl @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/runtimeconfig" ) func TestAccRuntimeconfigVariableDatasource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config.go.tmpl b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config.go.tmpl index e0d66c629462..c86f807310c0 100644 --- a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config.go.tmpl +++ b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config.go.tmpl @@ -30,6 +30,7 @@ func ResourceRuntimeconfigConfig() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -54,6 +55,9 @@ func ResourceRuntimeconfigConfig() *schema.Resource { ForceNew: true, Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -128,11 +132,21 @@ func resourceRuntimeconfigConfigRead(d *schema.ResourceData, meta interface{}) e if err := d.Set("project", project); err != nil { return fmt.Errorf("Error setting project: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } func resourceRuntimeconfigConfigUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceRuntimeconfigConfig) { + return ResourceRuntimeconfigConfig().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -158,6 +172,13 @@ func resourceRuntimeconfigConfigUpdate(d *schema.ResourceData, meta interface{}) } func resourceRuntimeconfigConfigDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config_meta.yaml.tmpl b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config_meta.yaml.tmpl index e1494d0f17f8..d08f7bb79a88 100644 --- a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_config_meta.yaml.tmpl @@ -8,4 +8,6 @@ fields: - api_field: 'description' - api_field: 'name' - field: 'project' + - field: 'deletion_policy' + provider_only: true {{ end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable.go.tmpl b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable.go.tmpl index efd2cbcde7c3..cbf4463df35d 100644 --- a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable.go.tmpl +++ b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable.go.tmpl @@ -27,6 +27,7 @@ func ResourceRuntimeconfigVariable() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -71,6 +72,10 @@ func ResourceRuntimeconfigVariable() *schema.Resource { Computed: true, Description: `The timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds, representing when the variable was last updated. Example: "2016-10-09T12:33:37.578138407Z".`, }, + + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -114,11 +119,21 @@ func resourceRuntimeconfigVariableRead(d *schema.ResourceData, meta interface{}) if err != nil { return err } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return setRuntimeConfigVariableToResourceData(d, *createdVariable) } func resourceRuntimeconfigVariableUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceRuntimeconfigVariable) { + return ResourceRuntimeconfigVariable().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -147,6 +162,13 @@ func resourceRuntimeconfigVariableUpdate(d *schema.ResourceData, meta interface{ } func resourceRuntimeconfigVariableDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable_meta.yaml.tmpl b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable_meta.yaml.tmpl index 4eb70ab23814..6f9e36f73d3f 100644 --- a/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/runtimeconfig/resource_runtimeconfig_variable_meta.yaml.tmpl @@ -11,4 +11,6 @@ fields: - api_field: 'text' - api_field: 'updateTime' - api_field: 'value' + - field: 'deletion_policy' + provider_only: true {{ end }} \ No newline at end of file diff --git a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_release_test.go.tmpl b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_release_test.go.tmpl index d6f37ef0a683..e47eefc707ea 100644 --- a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_release_test.go.tmpl +++ b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_release_test.go.tmpl @@ -9,12 +9,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/saasruntime" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSaasRuntimeRelease_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-saasservicemgmt.iam.gserviceaccount.com", Role: "roles/saasservicemgmt.serviceAgent", diff --git a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_rollout_kind_test.go.tmpl b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_rollout_kind_test.go.tmpl index db8350e21493..49c9ec990c68 100644 --- a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_rollout_kind_test.go.tmpl +++ b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_rollout_kind_test.go.tmpl @@ -9,11 +9,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/saasruntime" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSaasRuntimeRolloutKind_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-saasservicemgmt.iam.gserviceaccount.com", Role: "roles/saasservicemgmt.serviceAgent", diff --git a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_saas_test.go.tmpl b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_saas_test.go.tmpl index 1d9c30460336..d6736e9e3eec 100644 --- a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_saas_test.go.tmpl +++ b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_saas_test.go.tmpl @@ -9,11 +9,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/saasruntime" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSaasRuntimeSaas_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-saasservicemgmt.iam.gserviceaccount.com", Role: "roles/saasservicemgmt.serviceAgent", diff --git a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_tenant_test.go.tmpl b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_tenant_test.go.tmpl index aa1945d986af..034523675b06 100644 --- a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_tenant_test.go.tmpl +++ b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_tenant_test.go.tmpl @@ -9,12 +9,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/saasruntime" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSaasRuntimeTenant_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-saasservicemgmt.iam.gserviceaccount.com", Role: "roles/saasservicemgmt.serviceAgent", diff --git a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_kind_test.go.tmpl b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_kind_test.go.tmpl index f9d1c2534f91..91188cf9fe06 100644 --- a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_kind_test.go.tmpl +++ b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_kind_test.go.tmpl @@ -9,12 +9,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/saasruntime" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSaasRuntimeUnitKind_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-saasservicemgmt.iam.gserviceaccount.com", Role: "roles/saasservicemgmt.serviceAgent", diff --git a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_test.go.tmpl b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_test.go.tmpl index 9b8216729068..5a5eda52fe14 100644 --- a/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_test.go.tmpl +++ b/mmv1/third_party/terraform/services/saasruntime/resource_saas_runtime_unit_test.go.tmpl @@ -9,12 +9,14 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/saasruntime" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" ) func TestAccSaasRuntimeUnit_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-saasservicemgmt.iam.gserviceaccount.com", Role: "roles/saasservicemgmt.serviceAgent", diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_test.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_test.go index f05beaba55c0..198e91a7f263 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccDataSourceSecretManagerSecret_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version.go index d99758232009..c2fa358c0708 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version.go @@ -101,12 +101,12 @@ func dataSourceSecretManagerSecretVersionRead(d *schema.ResourceData, meta inter versionNum := d.Get("version") if versionNum != "" { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret}}/versions/{{version}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/secrets/{{secret}}/versions/{{version}}") if err != nil { return err } } else { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret}}/versions/latest") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/secrets/{{secret}}/versions/latest") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access.go index 7ffe75c0ae68..404ded41e06b 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access.go @@ -85,12 +85,12 @@ func dataSourceSecretManagerSecretVersionAccessRead(d *schema.ResourceData, meta versionNum := d.Get("version") if versionNum != "" { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret}}/versions/{{version}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/secrets/{{secret}}/versions/{{version}}") if err != nil { return err } } else { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret}}/versions/latest") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/secrets/{{secret}}/versions/latest") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access_test.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access_test.go index 15c3cee73c0f..04c8915129a9 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_access_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_test.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_test.go index 47427d1e4397..608a10007d5f 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secret_version_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets.go index 47a4b5e9b09d..f130be02c0da 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets.go @@ -46,7 +46,7 @@ func dataSourceSecretManagerSecretsRead(d *schema.ResourceData, meta interface{} return err } - url, err := tpgresource.ReplaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/secrets") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets_test.go b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets_test.go index a58b2cfd1bba..66ed2cf486d7 100644 --- a/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/data_source_secret_manager_secrets_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccDataSourceSecretManagerSecrets_basic(t *testing.T) { @@ -30,8 +31,9 @@ func TestAccDataSourceSecretManagerSecrets_basic(t *testing.T) { "data.google_secret_manager_secrets.foo", "google_secret_manager_secret.foo", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), @@ -96,8 +98,9 @@ func TestAccDataSourceSecretManagerSecrets_filter(t *testing.T) { "google_secret_manager_secret.foo", "google_secret_manager_secret.bar", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), diff --git a/mmv1/third_party/terraform/services/secretmanager/ephemeral_google_secret_manager_secret_version_test.go b/mmv1/third_party/terraform/services/secretmanager/ephemeral_google_secret_manager_secret_version_test.go index 49a075a64468..95088edc9273 100644 --- a/mmv1/third_party/terraform/services/secretmanager/ephemeral_google_secret_manager_secret_version_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/ephemeral_google_secret_manager_secret_version_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccEphemeralSecretManagerSecretVersion_basic(t *testing.T) { @@ -16,7 +17,7 @@ func TestAccEphemeralSecretManagerSecretVersion_basic(t *testing.T) { secret := "tf-test-secret-" + acctest.RandString(t, 10) secretData := "secret-data" - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ @@ -38,7 +39,7 @@ func TestAccEphemeralSecretManagerSecretVersion_base64(t *testing.T) { secret := "tf-test-secret-" + acctest.RandString(t, 10) secretData := "secret-data" - resource.Test(t, resource.TestCase{ + acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), Steps: []resource.TestStep{ diff --git a/mmv1/third_party/terraform/services/secretmanager/iam_secret_manager_secret_test.go b/mmv1/third_party/terraform/services/secretmanager/iam_secret_manager_secret_test.go index 0eb78e092355..3363ada3f252 100644 --- a/mmv1/third_party/terraform/services/secretmanager/iam_secret_manager_secret_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/iam_secret_manager_secret_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccSecretManagerSecretIam_iamMemberConditionUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_test.go b/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_test.go index 749887468b42..b85c5db795cd 100644 --- a/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_test.go @@ -5,6 +5,10 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -38,8 +42,8 @@ func TestAccSecretManagerSecret_import(t *testing.T) { func TestAccSecretManagerSecret_cmek(t *testing.T) { t.Parallel() - kmscentral := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - kmseast := acctest.BootstrapKMSKeyInLocation(t, "us-east1") + kmscentral := kms.BootstrapKMSKeyInLocation(t, "us-central1") + kmseast := kms.BootstrapKMSKeyInLocation(t, "us-east1") context1 := map[string]interface{}{ "pid": envvar.GetTestProjectFromEnv(), "random_suffix": acctest.RandString(t, 10), @@ -162,9 +166,9 @@ func TestAccSecretManagerSecret_versionAliasesUpdate(t *testing.T) { func TestAccSecretManagerSecret_userManagedCmekUpdate(t *testing.T) { t.Parallel() - kmscentral := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key1") - kmseast := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-secret-manager-managed-east-key1") - kmscentralother := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key2") + kmscentral := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key1") + kmseast := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-secret-manager-managed-east-key1") + kmscentralother := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key2") context := map[string]interface{}{ "pid": envvar.GetTestProjectFromEnv(), "random_suffix": acctest.RandString(t, 10), @@ -221,8 +225,8 @@ func TestAccSecretManagerSecret_automaticCmekUpdate(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - key1 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-secret-manager-automatic-key1") - key2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-secret-manager-automatic-key2") + key1 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-secret-manager-automatic-key1") + key2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "global", "tf-secret-manager-automatic-key2") context := map[string]interface{}{ "pid": envvar.GetTestProjectFromEnv(), "random_suffix": suffix, diff --git a/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_version_test.go b/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_version_test.go index af4b160ede1b..5453e47e9893 100644 --- a/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_version_test.go +++ b/mmv1/third_party/terraform/services/secretmanager/resource_secret_manager_secret_version_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" ) func TestAccSecretManagerSecretVersion_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_test.go index a03ea5465c85..2becb4396493 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_test.go @@ -5,13 +5,16 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" ) func TestAccDataSourceSecretManagerRegionalRegionalSecret_basic(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key6").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key6").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), "timestamp_1": "2114-11-30T00:00:00Z", "timestamp_2": "2115-11-30T00:00:00Z", diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version.go index 1c445ae2b597..34efb1b1c227 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version.go @@ -134,12 +134,12 @@ func dataSourceSecretManagerRegionalRegionalSecretVersionRead(d *schema.Resource // set version if provided, else set version to latest if versionNum != "" { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerRegionalBasePath}}projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/{{version}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/{{version}}") if err != nil { return err } } else { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerRegionalBasePath}}projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/latest") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/latest") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access.go index 24fb18a812da..b63d84e6d649 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access.go @@ -109,12 +109,12 @@ func dataSourceSecretManagerRegionalRegionalSecretVersionAccessRead(d *schema.Re // set version if provided, else set version to latest if versionNum != "" { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerRegionalBasePath}}projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/{{version}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/{{version}}") if err != nil { return err } } else { - url, err = tpgresource.ReplaceVars(d, config, "{{SecretManagerRegionalBasePath}}projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/latest") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/secrets/{{secret}}/versions/latest") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access_test.go index b9ba52d542de..d3ff86660a89 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_access_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_test.go index 9c03b695ab5a..e6022a27951e 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secret_version_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets.go index fc1c9cadc351..0b6fb2804a0d 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets.go @@ -48,7 +48,7 @@ func dataSourceSecretManagerRegionalRegionalSecretsRead(d *schema.ResourceData, return err } - url, err := tpgresource.ReplaceVars(d, config, "{{SecretManagerRegionalBasePath}}projects/{{project}}/locations/{{location}}/secrets") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{location}}/secrets") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets_test.go index a3ed4127b7ac..23c7d7093a8f 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/data_source_secret_manager_regional_secrets_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" ) func TestAccDataSourceSecretManagerRegionalRegionalSecrets_basic(t *testing.T) { @@ -31,8 +32,9 @@ func TestAccDataSourceSecretManagerRegionalRegionalSecrets_basic(t *testing.T) { "data.google_secret_manager_regional_secrets.foo", "google_secret_manager_regional_secret.foo", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), @@ -89,8 +91,9 @@ func TestAccDataSourceSecretManagerRegionalRegionalSecrets_filter(t *testing.T) "google_secret_manager_regional_secret.foo", "google_secret_manager_regional_secret.bar", map[string]struct{}{ - "id": {}, - "project": {}, + "id": {}, + "project": {}, + "deletion_policy": {}, }, ), ), diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/iam_secret_manager_regional_secret_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/iam_secret_manager_regional_secret_test.go index 0a3ddebaef22..214fea86d1d8 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/iam_secret_manager_regional_secret_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/iam_secret_manager_regional_secret_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" ) func TestAccSecretManagerRegionalRegionalSecretIam_iamPolicyUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_test.go index d932595e763c..9071c4656ba8 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" "github.com/hashicorp/terraform-provider-google/google/services/tags" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -144,8 +147,8 @@ func TestAccSecretManagerRegionalRegionalSecret_cmekUpdate(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key3").CryptoKey.Name, - "kms_key_name_other": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key4").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key3").CryptoKey.Name, + "kms_key_name_other": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key4").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_version_test.go b/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_version_test.go index 23af25d99c88..8db8c901f211 100644 --- a/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_version_test.go +++ b/mmv1/third_party/terraform/services/secretmanagerregional/resource_secret_manager_regional_secret_version_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanagerregional" ) func TestAccSecretManagerRegionalRegionalSecretVersion_update(t *testing.T) { @@ -54,7 +56,7 @@ func TestAccSecretManagerRegionalRegionalSecretVersion_cmekOutputOnly(t *testing t.Parallel() context := map[string]interface{}{ - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key5").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-secret-manager-managed-central-key5").CryptoKey.Name, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_branch_rule_update_test.go b/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_branch_rule_update_test.go index ed1397c981a5..21fb94095d01 100644 --- a/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_branch_rule_update_test.go +++ b/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_branch_rule_update_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securesourcemanager" ) func TestAccSecureSourceManagerBranchRule_secureSourceManagerBranchRuleWithFieldsExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_hook_update_test.go b/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_hook_update_test.go index 4bd3d1f7537a..fc581a1f6b8a 100644 --- a/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_hook_update_test.go +++ b/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_hook_update_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securesourcemanager" ) func TestAccSecureSourceManagerHook_secureSourceManagerHookWithFieldsExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_repository_update_test.go b/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_repository_update_test.go index a035b2094130..f1c4ed6e45e4 100644 --- a/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_repository_update_test.go +++ b/mmv1/third_party/terraform/services/securesourcemanager/resource_secure_source_manager_repository_update_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securesourcemanager" ) func TestAccSecureSourceManagerRepository_secureSourceManagerRepositoryBasicExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/iam_scc_source_test.go b/mmv1/third_party/terraform/services/securitycenter/iam_scc_source_test.go index f8c7a9112158..6ae709eea11b 100644 --- a/mmv1/third_party/terraform/services/securitycenter/iam_scc_source_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/iam_scc_source_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterSourceIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_event_threat_detection_custom_module_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_event_threat_detection_custom_module_test.go index 22a2d474d5f6..3880482a1c0e 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_event_threat_detection_custom_module_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_event_threat_detection_custom_module_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -104,7 +105,7 @@ func testAccSecurityCenterEventThreatDetectionCustomModuleDestroyProducer(t *tes config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{SecurityCenterBasePath}}organizations/{{organization}}/eventThreatDetectionSettings/customModules/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(securitycenter.Product, config)+"organizations/{{organization}}/eventThreatDetectionSettings/customModules/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_big_query_export_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_big_query_export_config_test.go index 22609aff569e..e5848cffbc29 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_big_query_export_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_big_query_export_config_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterFolderBigQueryExportConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_custom_module_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_custom_module_test.go index 08675ede43b2..207fe0448c67 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_custom_module_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_custom_module_test.go @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -201,7 +203,7 @@ func testAccCheckSecurityCenterFolderCustomModuleDestroyProducer(t *testing.T) f config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{SecurityCenterBasePath}}folders/{{folder}}/securityHealthAnalyticsSettings/customModules/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(securitycenter.Product, config)+"folders/{{folder}}/securityHealthAnalyticsSettings/customModules/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_notification_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_notification_config_test.go index ca201e56f803..e37f17c5479a 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_notification_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_folder_notification_config_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterFolderNotificationConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_mute_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_mute_config_test.go index c30e7bfb60d0..e4b3348af890 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_mute_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_mute_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterMuteConfig(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_notification_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_notification_config_test.go index d49741092d22..796dff70f1bd 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_notification_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_notification_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterNotificationConfig_updateStreamingConfigFilter(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_big_query_export_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_big_query_export_config_test.go index c29e884d2c81..8cac0657de65 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_big_query_export_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_big_query_export_config_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterOrganizationBigQueryExportConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_custom_module_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_custom_module_test.go index 6d99ff43dba4..1171fcf8cb61 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_custom_module_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_organization_custom_module_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -169,7 +170,7 @@ func testAccCheckSecurityCenterOrganizationCustomModuleDestroyProducer(t *testin config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{SecurityCenterBasePath}}organizations/{{organization}}/securityHealthAnalyticsSettings/customModules/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(securitycenter.Product, config)+"organizations/{{organization}}/securityHealthAnalyticsSettings/customModules/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_big_query_export_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_big_query_export_config_test.go index b67564c098c6..208955f6d4f5 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_big_query_export_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_big_query_export_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterProjectBigQueryExportConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_custom_module_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_custom_module_test.go index a3145075af86..9eafcabe4af6 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_custom_module_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_custom_module_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -161,7 +162,7 @@ func testAccCheckSecurityCenterProjectCustomModuleDestroyProducer(t *testing.T) config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{SecurityCenterBasePath}}projects/{{project}}/securityHealthAnalyticsSettings/customModules/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(securitycenter.Product, config)+"projects/{{project}}/securityHealthAnalyticsSettings/customModules/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_notification_config_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_notification_config_test.go index 8685849126b3..0fa35906ba48 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_notification_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_project_notification_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterProjectNotificationConfig_updateStreamingConfigFilter(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenter/resource_scc_source_test.go b/mmv1/third_party/terraform/services/securitycenter/resource_scc_source_test.go index 86a02374a8c0..808b82af88c8 100644 --- a/mmv1/third_party/terraform/services/securitycenter/resource_scc_source_test.go +++ b/mmv1/third_party/terraform/services/securitycenter/resource_scc_source_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenter" ) func TestAccSecurityCenterSource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_folder_security_health_analytics_custom_module_test.go.tmpl b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_folder_security_health_analytics_custom_module_test.go.tmpl index 053b6cc00b2c..370d94dca696 100644 --- a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_folder_security_health_analytics_custom_module_test.go.tmpl +++ b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_folder_security_health_analytics_custom_module_test.go.tmpl @@ -10,6 +10,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycentermanagement" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_event_threat_detection_custom_module_test.go.tmpl b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_event_threat_detection_custom_module_test.go.tmpl index d1fdb876f2f7..053192a1a966 100644 --- a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_event_threat_detection_custom_module_test.go.tmpl +++ b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_event_threat_detection_custom_module_test.go.tmpl @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycentermanagement" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_project_security_health_analytics_custom_module_test.go.tmpl b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_project_security_health_analytics_custom_module_test.go.tmpl index 103fdf853a7b..e91946b916ad 100644 --- a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_project_security_health_analytics_custom_module_test.go.tmpl +++ b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_project_security_health_analytics_custom_module_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycentermanagement" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) diff --git a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_security_health_analytics_custom_module_test.go.tmpl b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_security_health_analytics_custom_module_test.go.tmpl index 390e8fcb79dc..ac770acb9fa1 100644 --- a/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_security_health_analytics_custom_module_test.go.tmpl +++ b/mmv1/third_party/terraform/services/securitycentermanagement/resource_scc_management_organization_security_health_analytics_custom_module_test.go.tmpl @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycentermanagement" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" diff --git a/mmv1/third_party/terraform/services/securitycenterv2/iam_scc_v2_organization_source_test.go b/mmv1/third_party/terraform/services/securitycenterv2/iam_scc_v2_organization_source_test.go index 34fbde296651..e398ef762859 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/iam_scc_v2_organization_source_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/iam_scc_v2_organization_source_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2OrganizationSourceIamBinding(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_mute_config_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_mute_config_test.go index bea5fe413f36..11386693d3d4 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_mute_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_mute_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2FolderMuteConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_notification_config_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_notification_config_test.go index d65cec3c4a47..4ff6e87ef245 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_notification_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_notification_config_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2FolderNotificationConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_scc_big_query_export_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_scc_big_query_export_test.go index e2ce56c590be..3963edaf823c 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_scc_big_query_export_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_folder_scc_big_query_export_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2FolderBigQueryExportConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_mute_config_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_mute_config_test.go index 1b8416838ef0..bba89da694cc 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_mute_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_mute_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2OrganizationMuteConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_notification_config_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_notification_config_test.go index 4c62997b7af6..7dad4b83928b 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_notification_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_notification_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2OrganizationNotificationConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_export_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_export_test.go index 3791bc285e26..4ba3c59c94eb 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_export_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_export_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2OrganizationBigQueryExportConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_exports_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_exports_test.go index d2598f059238..6bac49b819a0 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_exports_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_scc_big_query_exports_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2OrganizationBigQueryExportsConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_source_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_source_test.go index 35cdeacaebfc..3d022a900486 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_source_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_organization_source_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2OrganizationSource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_mute_config_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_mute_config_test.go index e861250a62e6..74811b7f6d6a 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_mute_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_mute_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2ProjectMuteConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_notification_config_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_notification_config_test.go index 1cb04a9b4f78..736b4366fbf0 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_notification_config_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_notification_config_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2ProjectNotificationConfig_updateStreamingConfigFilter(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_scc_big_query_export_test.go b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_scc_big_query_export_test.go index d6968886144e..52369bb5635a 100644 --- a/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_scc_big_query_export_test.go +++ b/mmv1/third_party/terraform/services/securitycenterv2/resource_scc_v2_project_scc_big_query_export_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/securitycenterv2" ) func TestAccSecurityCenterV2ProjectBigQueryExportConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_deployment_test.go b/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_deployment_test.go index 114bd76e0733..47117a78dbd5 100644 --- a/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_deployment_test.go +++ b/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_deployment_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/securityposture" ) func TestAccSecurityPosturePostureDeployment_securityposturePostureDeployment_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_test.go b/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_test.go index 3104bffa0717..54e5e8d7b850 100644 --- a/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_test.go +++ b/mmv1/third_party/terraform/services/securityposture/resource_securityposture_posture_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/securityposture" ) func TestAccSecurityposturePosture_securityposturePosture_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/securityscanner/resource_security_scanner_scan_config_test.go.tmpl b/mmv1/third_party/terraform/services/securityscanner/resource_security_scanner_scan_config_test.go.tmpl index a3513d135de6..28fc67e8ad2b 100644 --- a/mmv1/third_party/terraform/services/securityscanner/resource_security_scanner_scan_config_test.go.tmpl +++ b/mmv1/third_party/terraform/services/securityscanner/resource_security_scanner_scan_config_test.go.tmpl @@ -4,6 +4,8 @@ package securityscanner_test import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/securityscanner" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_endpoint_test.go.tmpl b/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_endpoint_test.go.tmpl index 4a572cb03b6b..a2c088ba1ba7 100644 --- a/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_endpoint_test.go.tmpl +++ b/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_endpoint_test.go.tmpl @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicedirectory" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_namespace_test.go.tmpl b/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_namespace_test.go.tmpl index e55e35dc1405..f60eabc48115 100644 --- a/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_namespace_test.go.tmpl +++ b/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_namespace_test.go.tmpl @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicedirectory" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_service_test.go.tmpl b/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_service_test.go.tmpl index 53cf01106bda..63405bc97687 100644 --- a/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_service_test.go.tmpl +++ b/mmv1/third_party/terraform/services/servicedirectory/resource_service_directory_service_test.go.tmpl @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicedirectory" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service.go b/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service.go index ce9003f77cbb..9fee26e8502c 100644 --- a/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service.go +++ b/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -148,8 +149,14 @@ func ResourceEndpointsService() *schema.Resource { }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, - CustomizeDiff: predictServiceId, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + predictServiceId, + ), UseJSONNumber: true, } } @@ -284,6 +291,11 @@ func expandEndpointServiceConfigSource(d *schema.ResourceData, meta interface{}) } func resourceEndpointsServiceUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceEndpointsService) { + return ResourceEndpointsService().Read(d, meta) + } + // This update is not quite standard for a terraform resource. Instead of // using the go client library to send an HTTP request to update something // serverside, we have to push a new configuration, wait for it to be @@ -354,6 +366,13 @@ func resourceEndpointsServiceUpdate(d *schema.ResourceData, meta interface{}) er } func resourceEndpointsServiceDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -398,6 +417,10 @@ func resourceEndpointsServiceRead(d *schema.ResourceData, meta interface{}) erro return fmt.Errorf("Error setting endpoints: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } diff --git a/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_meta.yaml b/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_meta.yaml index 11381d516efe..93207047e49d 100644 --- a/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_meta.yaml +++ b/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_meta.yaml @@ -20,3 +20,5 @@ fields: - field: 'project' - field: 'protoc_output_base64' - api_field: 'serviceName' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_test.go b/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_test.go index d957331a7ff3..fc1d7550a84a 100644 --- a/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_test.go +++ b/mmv1/third_party/terraform/services/servicemanagement/resource_endpoints_service_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" "fmt" diff --git a/mmv1/third_party/terraform/services/servicenetworking/bootstrap_test_utils.go b/mmv1/third_party/terraform/services/servicenetworking/bootstrap_test_utils.go new file mode 100644 index 000000000000..1ce70256d5f6 --- /dev/null +++ b/mmv1/third_party/terraform/services/servicenetworking/bootstrap_test_utils.go @@ -0,0 +1,128 @@ +package servicenetworking + +import ( + "fmt" + "log" + "testing" + "time" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + rmClient "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager/client" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + + "google.golang.org/api/servicenetworking/v1" +) + +type ServiceNetworkSettings struct { + PrefixLength int + ParentService string +} + +func ServiceNetworkWithPrefixLength(prefixLength int) func(*ServiceNetworkSettings) { + return func(settings *ServiceNetworkSettings) { + settings.PrefixLength = prefixLength + } +} + +func ServiceNetworkWithParentService(parentService string) func(*ServiceNetworkSettings) { + return func(settings *ServiceNetworkSettings) { + settings.ParentService = parentService + } +} + +func NewServiceNetworkSettings(options ...func(*ServiceNetworkSettings)) *ServiceNetworkSettings { + settings := &ServiceNetworkSettings{ + PrefixLength: 16, // default prefix length + ParentService: "servicenetworking.googleapis.com", // default parent service + } + + for _, o := range options { + o(settings) + } + return settings +} + +// BootstrapSharedServiceNetworkingConnection will create a shared network +// if it hasn't been created in the test project, a global address +// if it hasn't been created in the test project, and a service networking connection +// if it hasn't been created in the test project. +// +// params are the functions to set compute global address +// +// BootstrapSharedServiceNetworkingConnection returns a persistent compute network name +// for a test or set of tests. +// +// To delete a service networking connection, all of the service instances that use that connection +// must be deleted first. After the service instances are deleted, some service producers delay the deletion +// utnil a waiting period has passed. For example, after four days that you delete a SQL instance, +// the service networking connection can be deleted. +// That is the reason to use the shared service networking connection for test resources. +// https://cloud.google.com/vpc/docs/configure-private-services-access#removing-connection +// +// testId specifies the test for which a shared network and a global address are used/initialized. +func BootstrapSharedServiceNetworkingConnection(t *testing.T, testId string, params ...func(*ServiceNetworkSettings)) string { + settings := NewServiceNetworkSettings(params...) + parentService := "services/" + settings.ParentService + projectId := envvar.GetTestProjectFromEnv() + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + // Get project number by calling the API + crmClient := rmClient.NewClient(config, config.UserAgent) + project, err := crmClient.Projects.Get(projectId).Do() + if err != nil { + t.Fatalf("Error getting project: %s", err) + } + + networkName := tpgcompute.SharedTestNetworkPrefix + testId + networkId := fmt.Sprintf("projects/%v/global/networks/%v", project.ProjectNumber, networkName) + globalAddressName := tpgcompute.BootstrapSharedTestGlobalAddress(t, testId, tpgcompute.AddressWithPrefixLength(settings.PrefixLength)) + + readCall := NewClient(config, config.UserAgent).Services.Connections.List(parentService).Network(networkId) + if config.UserProjectOverride { + readCall.Header().Add("X-Goog-User-Project", projectId) + } + response, err := readCall.Do() + if err != nil { + t.Errorf("Error getting shared test service networking connection: %s", err) + } + + var connection *servicenetworking.Connection + for _, c := range response.Connections { + if c.Network == networkId { + connection = c + break + } + } + + if connection == nil { + log.Printf("[DEBUG] Service networking connection not found, bootstrapping") + + connection := &servicenetworking.Connection{ + Network: networkId, + ReservedPeeringRanges: []string{globalAddressName}, + } + + createCall := NewClient(config, config.UserAgent).Services.Connections.Create(parentService, connection) + if config.UserProjectOverride { + createCall.Header().Add("X-Goog-User-Project", projectId) + } + op, err := createCall.Do() + if err != nil { + t.Fatalf("Error bootstrapping shared test service networking connection: %s", err) + } + + log.Printf("[DEBUG] Waiting for service networking connection creation to finish") + if err := ServiceNetworkingOperationWaitTimeHW(config, op, "Create Service Networking Connection", config.UserAgent, projectId, 4*time.Minute); err != nil { + t.Fatalf("Error bootstrapping shared test service networking connection: %s", err) + } + } + + log.Printf("[DEBUG] Getting shared test service networking connection") + + return networkName +} diff --git a/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain.go b/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain.go index f800644e51ea..6b0b44228826 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain.go +++ b/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain.go @@ -1,6 +1,8 @@ package servicenetworking import ( + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" ) @@ -33,6 +35,9 @@ func DataSourceGoogleServiceNetworkingPeeredDNSDomain() *schema.Resource { Type: schema.TypeString, Computed: true, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, } } diff --git a/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain_test.go b/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain_test.go index c2dea9fdb8fa..1c1ec6da3550 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain_test.go +++ b/mmv1/third_party/terraform/services/servicenetworking/data_source_google_service_networking_peered_dns_domain_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccDatasourceGoogleServiceNetworkingPeeredDnsDomain_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain.go b/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain.go index 1044866b7bc3..780375c67e18 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain.go +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain.go @@ -21,6 +21,7 @@ func ResourceGoogleServiceNetworkingPeeredDNSDomain() *schema.Resource { return &schema.Resource{ Create: resourceGoogleServiceNetworkingPeeredDNSDomainCreate, Read: resourceGoogleServiceNetworkingPeeredDNSDomainRead, + Update: resourceGoogleServiceNetworkingPeeredDNSDomainUpdate, Delete: resourceGoogleServiceNetworkingPeeredDNSDomainDelete, Importer: &schema.ResourceImporter{ @@ -35,6 +36,7 @@ func ResourceGoogleServiceNetworkingPeeredDNSDomain() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -74,6 +76,9 @@ func ResourceGoogleServiceNetworkingPeeredDNSDomain() *schema.Resource { Type: schema.TypeString, Computed: true, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -214,10 +219,29 @@ func resourceGoogleServiceNetworkingPeeredDNSDomainRead(d *schema.ResourceData, return fmt.Errorf("Error setting parent: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceGoogleServiceNetworkingPeeredDNSDomainUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceGoogleServiceNetworkingPeeredDNSDomainRead(d, meta) +} + +//UDP update end + func resourceGoogleServiceNetworkingPeeredDNSDomainDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_meta.yaml b/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_meta.yaml index 34fba011bff2..93a599822cb4 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_meta.yaml +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_meta.yaml @@ -10,3 +10,5 @@ fields: - field: 'parent' - field: 'project' - field: 'service' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_test.go b/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_test.go index 97a52bb7b727..9da2c090f3f7 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_test.go +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_google_service_networking_peered_dns_domain_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccServiceNetworkingPeeredDNSDomain_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection.go b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection.go index 0368acfdc44a..7de22784def2 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection.go +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection.go @@ -16,8 +16,8 @@ import ( transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "github.com/hashicorp/errwrap" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "google.golang.org/api/servicenetworking/v1" ) @@ -37,6 +37,9 @@ func ResourceServiceNetworkingConnection() *schema.Resource { Importer: &schema.ResourceImporter{ State: resourceServiceNetworkingConnectionImportState, }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(10 * time.Minute), @@ -71,12 +74,9 @@ func ResourceServiceNetworkingConnection() *schema.Resource { DiffSuppressFunc: stringListDiffSuppress, Description: `Named IP address range(s) of PEERING type reserved for this service provider. Note that invoking this method with a different range when connection is already established will not reallocate already provisioned service producer subnetworks.`, }, - "deletion_policy": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{"ABANDON", ""}, false), - Description: `When set to ABANDON, terraform will abandon management of the resource instead of deleting it. Prevents terraform apply failures with CloudSQL. Note: The resource will still exist.`, - }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end "peering": { Type: schema.TypeString, Computed: true, @@ -239,10 +239,19 @@ func resourceServiceNetworkingConnectionRead(d *schema.ResourceData, meta interf return fmt.Errorf("Error setting reserved_peering_ranges: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceServiceNetworkingConnectionUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceServiceNetworkingConnection) { + return ResourceServiceNetworkingConnection().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -300,8 +309,9 @@ func resourceServiceNetworkingConnectionUpdate(d *schema.ResourceData, meta inte func resourceServiceNetworkingConnectionDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - if deletionPolicy := d.Get("deletion_policy"); deletionPolicy == "ABANDON" { - log.Printf("[WARN] The service networking connection has been abandoned") + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { return nil } diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_meta.yaml b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_meta.yaml index 802ea09a6bcc..1714fcdebdf9 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_meta.yaml +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_meta.yaml @@ -5,6 +5,7 @@ api_version: 'v1' api_resource_type_kind: 'Connection' fields: - field: 'deletion_policy' + provider_only: true - api_field: 'network' - api_field: 'peering' - api_field: 'reservedPeeringRanges' diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_test.go b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_test.go index c960dd36f922..21b7ec5e95d6 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_test.go +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_connection_test.go @@ -9,6 +9,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) diff --git a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_vpc_service_controls_test.go b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_vpc_service_controls_test.go index 0f12ea770fa5..a92ca6d05062 100644 --- a/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_vpc_service_controls_test.go +++ b/mmv1/third_party/terraform/services/servicenetworking/resource_service_networking_vpc_service_controls_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" ) func TestAccServiceNetworkingVPCServiceControls_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/serviceusage/resource_service_usage_consumer_quota_override_test.go.tmpl b/mmv1/third_party/terraform/services/serviceusage/resource_service_usage_consumer_quota_override_test.go.tmpl index 7b5f732b3fc6..7bec901a8309 100644 --- a/mmv1/third_party/terraform/services/serviceusage/resource_service_usage_consumer_quota_override_test.go.tmpl +++ b/mmv1/third_party/terraform/services/serviceusage/resource_service_usage_consumer_quota_override_test.go.tmpl @@ -6,6 +6,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/serviceusage" "github.com/hashicorp/terraform-provider-google/google/envvar" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/siteverification/data_source_google_site_verification_token.go b/mmv1/third_party/terraform/services/siteverification/data_source_google_site_verification_token.go index de4e0d27792c..0602c950fa5e 100644 --- a/mmv1/third_party/terraform/services/siteverification/data_source_google_site_verification_token.go +++ b/mmv1/third_party/terraform/services/siteverification/data_source_google_site_verification_token.go @@ -85,7 +85,7 @@ func dataSourceSiteVerificationTokenRead(d *schema.ResourceData, meta interface{ obj["verificationMethod"] = verification_methodProp } - url, err := tpgresource.ReplaceVars(d, config, "{{SiteVerificationBasePath}}token") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"token") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner.go b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner.go index a34954aa59b7..b22c0bb59225 100644 --- a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner.go +++ b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner.go @@ -16,6 +16,7 @@ func ResourceSiteVerificationOwner() *schema.Resource { return &schema.Resource{ Create: resourceSiteVerificationOwnerCreate, Read: resourceSiteVerificationOwnerRead, + Update: resourceSiteVerificationOwnerUpdate, Delete: resourceSiteVerificationOwnerDelete, Importer: &schema.ResourceImporter{ @@ -41,6 +42,9 @@ func ResourceSiteVerificationOwner() *schema.Resource { DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, Description: `The id of the Web Resource to add this owner to, in the form "webResource/".`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -57,7 +61,7 @@ func resourceSiteVerificationOwnerCreate(d *schema.ResourceData, meta interface{ log.Printf("[DEBUG] Reading existing WebResource") - url, err := tpgresource.ReplaceVars(d, config, "{{SiteVerificationBasePath}}{{web_resource_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{web_resource_id}}") if err != nil { return err } @@ -135,7 +139,7 @@ func resourceSiteVerificationOwnerRead(d *schema.ResourceData, meta interface{}) return err } - url, err := tpgresource.ReplaceVars(d, config, "{{SiteVerificationBasePath}}{{web_resource_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{web_resource_id}}") if err != nil { return err } @@ -180,10 +184,29 @@ func resourceSiteVerificationOwnerRead(d *schema.ResourceData, meta interface{}) return nil } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceSiteVerificationOwnerUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceSiteVerificationOwnerRead(d, meta) +} + +//UDP update end + func resourceSiteVerificationOwnerDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -192,7 +215,7 @@ func resourceSiteVerificationOwnerDelete(d *schema.ResourceData, meta interface{ billingProject := "" - url, err := tpgresource.ReplaceVars(d, config, "{{SiteVerificationBasePath}}{{web_resource_id}}") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{web_resource_id}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_meta.yaml b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_meta.yaml index 2030861c3b26..44085f7f1f7b 100644 --- a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_meta.yaml +++ b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_meta.yaml @@ -6,3 +6,5 @@ api_resource_type_kind: 'WebResource' fields: - field: 'email' - field: 'web_resource_id' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_test.go b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_test.go index 145eaf46f4f8..e36fa84e1881 100644 --- a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_test.go +++ b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_owner_test.go @@ -5,6 +5,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/siteverification" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccSiteVerificationOwner_siteVerificationBucket(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_web_resource_test.go b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_web_resource_test.go index 494ba4868d44..c8f2ee8267a8 100644 --- a/mmv1/third_party/terraform/services/siteverification/resource_site_verification_web_resource_test.go +++ b/mmv1/third_party/terraform/services/siteverification/resource_site_verification_web_resource_test.go @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/dns" + "github.com/hashicorp/terraform-provider-google/google/services/siteverification" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -138,7 +141,7 @@ func testAccCheckSiteVerificationWebResourceDestroyProducer(t *testing.T) func(s config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{SiteVerificationBasePath}}webResource/{{id}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(siteverification.Product, config)+"webResource/{{id}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/sourcerepo/data_source_sourcerepo_repository_test.go b/mmv1/third_party/terraform/services/sourcerepo/data_source_sourcerepo_repository_test.go index 7a33d2a19fd4..45472dc06dc5 100644 --- a/mmv1/third_party/terraform/services/sourcerepo/data_source_sourcerepo_repository_test.go +++ b/mmv1/third_party/terraform/services/sourcerepo/data_source_sourcerepo_repository_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sourcerepo" ) func TestAccDataSourceGoogleSourceRepoRepository_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sourcerepo/resource_sourcerepo_repository_test.go b/mmv1/third_party/terraform/services/sourcerepo/resource_sourcerepo_repository_test.go index fa9815e16006..0e80116c0a92 100644 --- a/mmv1/third_party/terraform/services/sourcerepo/resource_sourcerepo_repository_test.go +++ b/mmv1/third_party/terraform/services/sourcerepo/resource_sourcerepo_repository_test.go @@ -7,6 +7,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/sourcerepo" ) func TestAccSourceRepoRepository_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/spanner/data_source_spanner_database_test.go b/mmv1/third_party/terraform/services/spanner/data_source_spanner_database_test.go index 8ebeb01643d0..19360b98ca69 100644 --- a/mmv1/third_party/terraform/services/spanner/data_source_spanner_database_test.go +++ b/mmv1/third_party/terraform/services/spanner/data_source_spanner_database_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" ) func TestAccDataSourceSpannerDatabase_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/spanner/data_source_spanner_instance_test.go b/mmv1/third_party/terraform/services/spanner/data_source_spanner_instance_test.go index 04b86a377392..d30f183aa01f 100644 --- a/mmv1/third_party/terraform/services/spanner/data_source_spanner_instance_test.go +++ b/mmv1/third_party/terraform/services/spanner/data_source_spanner_instance_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" ) func TestAccDataSourceSpannerInstance_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/spanner/iam_spanner_database_test.go b/mmv1/third_party/terraform/services/spanner/iam_spanner_database_test.go index 8ce32e2edce6..c58d7e5a294c 100644 --- a/mmv1/third_party/terraform/services/spanner/iam_spanner_database_test.go +++ b/mmv1/third_party/terraform/services/spanner/iam_spanner_database_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/spanner" ) diff --git a/mmv1/third_party/terraform/services/spanner/iam_spanner_instance_test.go b/mmv1/third_party/terraform/services/spanner/iam_spanner_instance_test.go index ad9339172e77..508f6e873b1b 100644 --- a/mmv1/third_party/terraform/services/spanner/iam_spanner_instance_test.go +++ b/mmv1/third_party/terraform/services/spanner/iam_spanner_instance_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/spanner" ) diff --git a/mmv1/third_party/terraform/services/spanner/resource_spanner_database_test.go b/mmv1/third_party/terraform/services/spanner/resource_spanner_database_test.go index f1889b2fd277..81efa0f17650 100644 --- a/mmv1/third_party/terraform/services/spanner/resource_spanner_database_test.go +++ b/mmv1/third_party/terraform/services/spanner/resource_spanner_database_test.go @@ -8,6 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" ) func TestAccSpannerDatabase_basic(t *testing.T) { @@ -626,7 +629,7 @@ resource "google_spanner_database" "database" { func TestAccSpannerDatabase_cmek(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-spanner.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -635,7 +638,7 @@ func TestAccSpannerDatabase_cmek(t *testing.T) { // Make the keys outside of Terraform so that a) the project isn't littered with a key from each run and b) so that VCR // can work. - kmsKey := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "europe-west1", "tf-test-cmek-test-key-europe-west1") + kmsKey := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "europe-west1", "tf-test-cmek-test-key-europe-west1") context := map[string]interface{}{ "key_name": kmsKey.CryptoKey.Name, @@ -691,9 +694,9 @@ resource "google_spanner_database" "database" { func TestAccSpannerDatabase_mrcmek(t *testing.T) { t.Parallel() - kms1 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-mr-cmek-test-key-us-central1") - kms2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-mr-cmek-test-key-us-east1") - kms3 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-mr-cmek-test-key-us-east4") + kms1 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-mr-cmek-test-key-us-central1") + kms2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-mr-cmek-test-key-us-east1") + kms3 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-mr-cmek-test-key-us-east4") context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "key_ring1": kms1.KeyRing.Name, diff --git a/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_config_test.go b/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_config_test.go index b6253da09e31..306050abd46f 100644 --- a/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_config_test.go +++ b/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_config_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_partition_test.go b/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_partition_test.go index ca28043cb1fc..a6c9b1c7bbc5 100644 --- a/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_partition_test.go +++ b/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_partition_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" ) func TestAccSpannerInstancePartition_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_test.go b/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_test.go index d178b91219fb..0aaf5bc15931 100644 --- a/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_test.go +++ b/mmv1/third_party/terraform/services/spanner/resource_spanner_instance_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/spanner/resource_spanner_schedule_backup_test.go b/mmv1/third_party/terraform/services/spanner/resource_spanner_schedule_backup_test.go index 92f2c0b77e58..3e21d453b137 100644 --- a/mmv1/third_party/terraform/services/spanner/resource_spanner_schedule_backup_test.go +++ b/mmv1/third_party/terraform/services/spanner/resource_spanner_schedule_backup_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/spanner" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) @@ -45,11 +47,11 @@ func TestAccSpannerBackupSchedule_update(t *testing.T) { func TestAccSpannerBackupSchedule_CMEKIncrementalBackup(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - kms := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-spanner-key") + bootstrapped := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-spanner-key") context := map[string]interface{}{ "random_suffix": suffix, - "key_name": kms.CryptoKey.Name, + "key_name": bootstrapped.CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -72,11 +74,11 @@ func TestAccSpannerBackupSchedule_CMEKIncrementalBackup(t *testing.T) { func TestAccSpannerBackupSchedule_CMEKFullBackup(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - kms := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-spanner-key") + bootstrapped := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-spanner-key") context := map[string]interface{}{ "random_suffix": suffix, - "key_name": kms.CryptoKey.Name, + "key_name": bootstrapped.CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -108,9 +110,9 @@ func TestAccSpannerBackupSchedule_MRCMEKIncrementalBackup(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - kms1 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-mr-cmek-test-key-us-central1") - kms2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-mr-cmek-test-key-us-east1") - kms3 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-mr-cmek-test-key-us-east4") + kms1 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-mr-cmek-test-key-us-central1") + kms2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-mr-cmek-test-key-us-east1") + kms3 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-mr-cmek-test-key-us-east4") context := map[string]interface{}{ "random_suffix": suffix, @@ -143,9 +145,9 @@ func TestAccSpannerBackupSchedule_MRCMEKFullBackup(t *testing.T) { t.Parallel() suffix := acctest.RandString(t, 10) - kms1 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-mr-cmek-test-key-us-central1") - kms2 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-mr-cmek-test-key-us-east1") - kms3 := acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-mr-cmek-test-key-us-east4") + kms1 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-mr-cmek-test-key-us-central1") + kms2 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-mr-cmek-test-key-us-east1") + kms3 := kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east4", "tf-mr-cmek-test-key-us-east4") context := map[string]interface{}{ "random_suffix": suffix, diff --git a/mmv1/third_party/terraform/services/sql/data_source_google_sql_ca_certs_test.go b/mmv1/third_party/terraform/services/sql/data_source_google_sql_ca_certs_test.go index 1065ccdf4943..851283a8b080 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_google_sql_ca_certs_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_google_sql_ca_certs_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceGoogleSQLCaCerts_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sql/data_source_sql_backup_run_test.go b/mmv1/third_party/terraform/services/sql/data_source_sql_backup_run_test.go index 39958750dd82..eae878bba469 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_sql_backup_run_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_sql_backup_run_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) @@ -15,7 +16,7 @@ func TestAccDataSourceSqlBackupRun_basic(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - instance := acctest.BootstrapSharedSQLInstanceBackupRun(t) + instance := BootstrapSharedSQLInstanceBackupRun(t) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, diff --git a/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_latest_recovery_time_test.go b/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_latest_recovery_time_test.go index 7927f41bfa57..745d065cdd86 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_latest_recovery_time_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_latest_recovery_time_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceSqlDatabaseInstanceLatestRecoveryTime_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_test.go b/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_test.go index a6b4c7464e78..4254efdcda60 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_sql_database_instance_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceSqlDatabaseInstance_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sql/data_source_sql_database_instances_test.go b/mmv1/third_party/terraform/services/sql/data_source_sql_database_instances_test.go index deb031ea7a9c..79c180680ab7 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_sql_database_instances_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_sql_database_instances_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceSqlDatabaseInstances_basic(t *testing.T) { @@ -33,6 +34,7 @@ func TestAccDataSourceSqlDatabaseInstances_basic(t *testing.T) { map[string]struct{}{ "deletion_protection": {}, "id": {}, + "deletion_policy": {}, }, ), ), @@ -63,6 +65,7 @@ func TestAccDataSourceSqlDatabaseInstances_databaseVersionFilter(t *testing.T) { map[string]struct{}{ "deletion_protection": {}, "id": {}, + "deletion_policy": {}, }, ), ), @@ -93,6 +96,7 @@ func TestAccDataSourceSqlDatabaseInstances_regionFilter(t *testing.T) { map[string]struct{}{ "deletion_protection": {}, "id": {}, + "deletion_policy": {}, }, ), ), @@ -124,6 +128,7 @@ func TestAccDataSourceSqlDatabaseInstances_tierFilter(t *testing.T) { "deletion_protection": {}, "id": {}, "settings.0.version": {}, + "deletion_policy": {}, }, ), ), diff --git a/mmv1/third_party/terraform/services/sql/data_source_sql_database_test.go b/mmv1/third_party/terraform/services/sql/data_source_sql_database_test.go index 98826b8c0fb1..93c40e6565a7 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_sql_database_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_sql_database_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceSqlDatabase_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sql/data_source_sql_databases_test.go b/mmv1/third_party/terraform/services/sql/data_source_sql_databases_test.go index 1b476d03a5b8..38c3e8f046b1 100644 --- a/mmv1/third_party/terraform/services/sql/data_source_sql_databases_test.go +++ b/mmv1/third_party/terraform/services/sql/data_source_sql_databases_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccDataSourceSqlDatabases_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sql/fw_resource_sql_user.go b/mmv1/third_party/terraform/services/sql/fw_resource_sql_user.go deleted file mode 100644 index 1855c3aea9e5..000000000000 --- a/mmv1/third_party/terraform/services/sql/fw_resource_sql_user.go +++ /dev/null @@ -1,510 +0,0 @@ -package sql - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-framework/diag" - "github.com/hashicorp/terraform-plugin-framework/path" - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/tfsdk" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-log/tflog" - - "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" - "github.com/hashicorp/terraform-provider-google/google/fwmodels" - "github.com/hashicorp/terraform-provider-google/google/fwresource" - "github.com/hashicorp/terraform-provider-google/google/fwtransport" - "github.com/hashicorp/terraform-provider-google/google/transport" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - sqladmin "google.golang.org/api/sqladmin/v1beta4" -) - -//resource is non-functional, preserved for reference with ongoing fwprovider work -//any changes to `google_sql_user` should be performed at mmv1/third_party/terraform/services/sql/resource_sql_user.go - -var ( - _ resource.Resource = &SQLUserFWResource{} - _ resource.ResourceWithConfigure = &SQLUserFWResource{} -) - -func NewSQLUserFWResource() resource.Resource { - return &SQLUserFWResource{} -} - -type SQLUserFWResource struct { - client *sqladmin.Service - providerConfig *transport_tpg.Config -} - -type SQLUserModel struct { - Id types.String `tfsdk:"id"` - Project types.String `tfsdk:"project"` - Name types.String `tfsdk:"name"` - Host types.String `tfsdk:"host"` - Instance types.String `tfsdk:"instance"` - Password types.String `tfsdk:"password"` - // PasswordWO types.String `tfsdk:"password_wo"` - // PasswordWOVersion types.String `tfsdk:"password_wo_version"` - Type types.String `tfsdk:"type"` - // SqlServerUserDetails types.List `tfsdk:"sql_server_user_details"` - // PasswordPolicy types.List `tfsdk:"password_policy"` - // DeletionPolicy types.String `tfsdk:"deletion_policy"` - Timeouts timeouts.Value `tfsdk:"timeouts"` -} - -// Metadata returns the resource type name. -func (d *SQLUserFWResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_fw_sql_user" -} - -func (r *SQLUserFWResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - config, ok := req.ProviderData.(*transport_tpg.Config) - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *transport_tpg.Config, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - return - } - - r.client = NewClient(config, config.UserAgent) - if resp.Diagnostics.HasError() { - return - } - r.providerConfig = config -} - -func (d *SQLUserFWResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "A resource to represent a SQL User object.", - - Attributes: map[string]schema.Attribute{ - "project": schema.StringAttribute{ - Optional: true, - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), - stringplanmodifier.UseStateForUnknown(), - }, - }, - "host": schema.StringAttribute{ - Optional: true, - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), - stringplanmodifier.UseStateForUnknown(), - }, - }, - "instance": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), - }, - }, - "name": schema.StringAttribute{ - Description: `The name of the user. Changing this forces a new resource to be created.`, - Required: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), - SQLUserNameIAMPlanModifier(), - }, - }, - "password": schema.StringAttribute{ - Optional: true, - Sensitive: true, - }, - "type": schema.StringAttribute{ - Optional: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), - // TODO DiffSuppressFunc: tpgresource.EmptyOrDefaultStringSuppress("BUILT_IN"), - }, - }, - // This is included for backwards compatibility with the original, SDK-implemented resource. - "id": schema.StringAttribute{ - Description: "Project identifier", - MarkdownDescription: "Project identifier", - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), - }, - }, - }, - Blocks: map[string]schema.Block{ - "timeouts": timeouts.Block(ctx, timeouts.Opts{ - Create: true, - }), - }, - } -} - -func (r *SQLUserFWResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data SQLUserModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform plan data into the model - resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - - project := fwresource.GetProjectFramework(data.Project, types.StringValue(r.providerConfig.Project), &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - nameData, diags := data.Name.ToStringValue(ctx) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - instanceData, diags := data.Instance.ToStringValue(ctx) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - hostData, diags := data.Host.ToStringValue(ctx) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - typeData, diags := data.Type.ToStringValue(ctx) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - passwordData, diags := data.Password.ToStringValue(ctx) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - createTimeout, diags := data.Timeouts.Create(ctx, 20*time.Minute) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - user := &sqladmin.User{ - Name: nameData.ValueString(), - Instance: instanceData.ValueString(), - Password: passwordData.ValueString(), - Host: hostData.ValueString(), - Type: typeData.ValueString(), - } - - transport_tpg.MutexStore.Lock(instanceMutexKey(project.ValueString(), instanceData.ValueString())) - defer transport_tpg.MutexStore.Unlock(instanceMutexKey(project.ValueString(), instanceData.ValueString())) - - r.client.UserAgent = fwtransport.GenerateFrameworkUserAgentString(metaData, r.client.UserAgent) - - // TODO host check logic - - var op *sqladmin.Operation - var err error - insertFunc := func() error { - op, err = r.client.Users.Insert(project.ValueString(), instanceData.ValueString(), - user).Do() - return err - } - err = transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: insertFunc, - Timeout: createTimeout, - }) - - if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("Error, failed to insert "+ - "user %s into instance %s", nameData.ValueString(), instanceData.ValueString()), err.Error()) - return - } - - err = SqlAdminOperationWaitTime(r.providerConfig, op, project.ValueString(), "Insert User", r.client.UserAgent, createTimeout) - - if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("Error, failure waiting to insert "+ - "user %s into instance %s", nameData.ValueString(), instanceData.ValueString()), err.Error()) - return - } - - tflog.Trace(ctx, "created sql user resource") - - // This will include a double-slash (//) for postgres instances, - // for which user.Host is an empty string. That's okay. - data.Id = types.StringValue(fmt.Sprintf("%s/%s/%s", user.Name, user.Host, user.Instance)) - data.Project = project - - // read back sql user - r.SQLUserRefresh(ctx, &data, &resp.State, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - // Save data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *SQLUserFWResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data SQLUserModel - var metaData *fwmodels.ProviderMetaModel - - // Read Provider meta into the meta model - resp.Diagnostics.Append(req.ProviderMeta.Get(ctx, &metaData)...) - if resp.Diagnostics.HasError() { - return - } - - // Read Terraform configuration data into the model - resp.Diagnostics.Append(req.State.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - - // Use provider_meta to set User-Agent - r.client.UserAgent = fwtransport.GenerateFrameworkUserAgentString(metaData, r.client.UserAgent) - - tflog.Trace(ctx, "read sql user resource") - - // read back sql user - r.SQLUserRefresh(ctx, &data, &resp.State, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - - // Save data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *SQLUserFWResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var old, new SQLUserModel - var metaData *fwmodels.ProviderMetaModel - - resp.Diagnostics.Append(req.State.Get(ctx, &old)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(req.Plan.Get(ctx, &new)...) - if resp.Diagnostics.HasError() { - return - } - - // Use provider_meta to set User-Agent - r.client.UserAgent = fwtransport.GenerateFrameworkUserAgentString(metaData, r.client.UserAgent) - - if !old.Password.Equal(new.Password) { - project := new.Project.ValueString() - instance := new.Instance.ValueString() - name := new.Name.ValueString() - host := new.Host.ValueString() - password := new.Password.ValueString() - - updateTimeout, diags := new.Timeouts.Update(ctx, 20*time.Minute) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - user := &sqladmin.User{ - Name: name, - Instance: instance, - Password: password, - } - transport_tpg.MutexStore.Lock(instanceMutexKey(project, instance)) - defer transport_tpg.MutexStore.Unlock(instanceMutexKey(project, instance)) - var op *sqladmin.Operation - var err error - updateFunc := func() error { - op, err = r.client.Users.Update(project, instance, user).Host(host).Name(name).Do() - return err - } - err = transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: updateFunc, - Timeout: updateTimeout, - }) - - if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("failed to update"+ - "user %s in instance %s", name, instance), err.Error()) - return - } - - err = SqlAdminOperationWaitTime(r.providerConfig, op, project, "Update User", r.client.UserAgent, updateTimeout) - - if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("failure waiting for update"+ - "user %s in instance %s", name, instance), err.Error()) - return - } - - // read back sql user - r.SQLUserRefresh(ctx, &new, &resp.State, &resp.Diagnostics) - if resp.Diagnostics.HasError() { - return - } - } - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &new)...) -} - -func (r *SQLUserFWResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data SQLUserModel - - // Read Terraform prior state data into the model - resp.Diagnostics.Append(req.State.Get(ctx, &data)...) - if resp.Diagnostics.HasError() { - return - } - - project := data.Project.ValueString() - instance := data.Instance.ValueString() - name := data.Name.ValueString() - host := data.Host.ValueString() - - deleteTimeout, diags := data.Timeouts.Delete(ctx, 20*time.Minute) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - transport_tpg.MutexStore.Lock(instanceMutexKey(project, instance)) - defer transport_tpg.MutexStore.Unlock(instanceMutexKey(project, instance)) - var op *sqladmin.Operation - var err error - deleteFunc := func() error { - op, err = r.client.Users.Delete(project, instance).Host(host).Name(name).Do() - return err - } - err = transport_tpg.Retry(transport_tpg.RetryOptions{ - RetryFunc: deleteFunc, - Timeout: deleteTimeout, - }) - - if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("failed to delete"+ - "user %s in instance %s", name, instance), err.Error()) - return - } - - err = SqlAdminOperationWaitTime(r.providerConfig, op, project, "Delete User", r.client.UserAgent, deleteTimeout) - - if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("Error, failure waiting to delete "+ - "user %s", name), err.Error()) - return - } -} - -func (r *SQLUserFWResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - idParts := strings.Split(req.ID, "/") - - // TODO recreate all import cases - if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" { - resp.Diagnostics.AddError( - "Unexpected Import Identifier", - fmt.Sprintf("Expected import identifier with format: project/instance/host/name. Got: %q", req.ID), - ) - return - } - - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project"), idParts[0])...) - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance"), idParts[1])...) - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("host"), idParts[2])...) - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), idParts[3])...) -} - -func (r *SQLUserFWResource) SQLUserRefresh(ctx context.Context, data *SQLUserModel, state *tfsdk.State, diag *diag.Diagnostics) { - userReadResp, err := r.client.Users.Get(data.Project.ValueString(), data.Instance.ValueString(), data.Name.ValueString()).Host(data.Host.ValueString()).Do() - if err != nil { - // Treat HTTP 404 Not Found status as a signal to recreate resource - // and return early - if userReadResp != nil && transport.IsGoogleApiErrorWithCode(err, userReadResp.HTTPStatusCode) { - tflog.Trace(ctx, "sql user resource not found, removing from state") - state.RemoveResource(ctx) - return - } - diag.AddError(fmt.Sprintf("Error, failure waiting to read "+ - "user %s", data.Name.ValueString()), err.Error()) - return - } - - id := fmt.Sprintf("projects/%s/global/networks/%s", userReadResp.Project, userReadResp.Name) - data.Id = types.StringValue(id) - data.Project = types.StringValue(userReadResp.Project) - data.Instance = types.StringValue(userReadResp.Instance) - if userReadResp.Host != "" { - data.Host = types.StringValue(userReadResp.Host) - } - if userReadResp.Type != "" { - data.Type = types.StringValue(userReadResp.Type) - } -} - -// Plan Modifiers -func SQLUserNameIAMPlanModifier() planmodifier.String { - return &sqlUserNameIAMPlanModifier{} -} - -type sqlUserNameIAMPlanModifier struct { -} - -func (d *sqlUserNameIAMPlanModifier) Description(ctx context.Context) string { - return "Suppresses name diffs for IAM user types." -} -func (d *sqlUserNameIAMPlanModifier) MarkdownDescription(ctx context.Context) string { - return d.Description(ctx) -} - -// Plan modifier to emulate the SDK diffSuppressIamUserName -func (d *sqlUserNameIAMPlanModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) { - // Retrieve relevant fields - var oldName types.String - diags := req.State.GetAttribute(ctx, path.Root("name"), &oldName) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - var newName types.String - diags = req.Plan.GetAttribute(ctx, path.Root("name"), &newName) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - var userType types.String - diags = req.Plan.GetAttribute(ctx, path.Root("type"), &userType) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { - return - } - - // Old diff suppress logic - strippedNewName := strings.Split(newName.ValueString(), "@")[0] - - if oldName.ValueString() == strippedNewName && strings.Contains(userType.ValueString(), "IAM") { - // Suppress the diff by setting the planned value to the old value - resp.PlanValue = oldName - } -} diff --git a/mmv1/third_party/terraform/services/sql/fw_resource_sql_user_test.go b/mmv1/third_party/terraform/services/sql/fw_resource_sql_user_test.go deleted file mode 100644 index acec7e6bfc16..000000000000 --- a/mmv1/third_party/terraform/services/sql/fw_resource_sql_user_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package sql_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/envvar" -) - -func TestAccSqlUserFW_mysql(t *testing.T) { - //tests and resource are non-functional, preserved for reference with ongoing fwprovider work - t.Skip() - // Multiple fine-grained resources - //acctest.SkipIfVcr(t) - t.Parallel() - - instance := fmt.Sprintf("tf-test-%d", acctest.RandInt(t)) - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccSqlUserDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testGoogleSqlUserFW_mysql(instance, "password"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGoogleSqlUserExists(t, "google_fw_sql_user.user1"), - testAccCheckGoogleSqlUserExists(t, "google_fw_sql_user.user2"), - ), - }, - { - // Update password - Config: testGoogleSqlUserFW_mysql(instance, "new_password"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGoogleSqlUserExists(t, "google_fw_sql_user.user1"), - testAccCheckGoogleSqlUserExists(t, "google_fw_sql_user.user2"), - testAccCheckGoogleSqlUserExists(t, "google_fw_sql_user.user3"), - ), - }, - { - ResourceName: "google_fw_sql_user.user2", - ImportStateId: fmt.Sprintf("%s/%s/gmail.com/admin", envvar.GetTestProjectFromEnv(), instance), - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"password"}, - }, - { - ResourceName: "google_fw_sql_user.user3", - ImportStateId: fmt.Sprintf("%s/%s/10.0.0.0/24/admin", envvar.GetTestProjectFromEnv(), instance), - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"password"}, - }, - }, - }) -} - -func testGoogleSqlUserFW_mysql(instance, password string) string { - return fmt.Sprintf(` -resource "google_sql_database_instance" "instance" { - name = "%s" - region = "us-central1" - database_version = "MYSQL_5_7" - deletion_protection = false - settings { - tier = "db-f1-micro" - } -} - -resource "google_fw_sql_user" "user1" { - name = "admin" - instance = google_sql_database_instance.instance.name - host = "google.com" - password = "%s" -} - -resource "google_fw_sql_user" "user2" { - name = "admin" - instance = google_sql_database_instance.instance.name - host = "gmail.com" - password = "hunter2" -} - -resource "google_fw_sql_user" "user3" { - name = "admin" - instance = google_sql_database_instance.instance.name - host = "10.0.0.0/24" - password = "hunter3" -} -`, instance, password) -} diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_database_instance.go.tmpl b/mmv1/third_party/terraform/services/sql/resource_sql_database_instance.go.tmpl index 770ca8e40236..aba9f5b75e2d 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_database_instance.go.tmpl +++ b/mmv1/third_party/terraform/services/sql/resource_sql_database_instance.go.tmpl @@ -234,6 +234,7 @@ func ResourceSqlDatabaseInstance() *schema.Resource { pitrSupportDbCustomizeDiff, nodeCountCustomDiff, autoUpgradeEnabledCustomizeDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -544,7 +545,6 @@ API (for read pools, effective_availability_type may differ from availability_ty DiffSuppressFunc: caseDiffDashSuppress, Description: `The type of supported data disk is tier dependent and can be PD_SSD or PD_HDD or HYPERDISK_BALANCED.`, }, -{{- if ne $.TargetVersionName "ga" }} "data_disk_provisioned_iops": { Type: schema.TypeInt, Optional: true, @@ -557,7 +557,6 @@ API (for read pools, effective_availability_type may differ from availability_ty Computed: true, Description: `Provisioned throughput measured in MiB per second for the data disk. This field is only used for HYPERDISK_BALANCED disk types.`, }, -{{- end }} "connection_pool_config": { Type: schema.TypeSet, Optional: true, @@ -1493,6 +1492,9 @@ API (for read pools, effective_availability_type may differ from availability_ty }, }, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -1842,10 +1844,8 @@ func expandSqlDatabaseInstanceSettings(configured []interface{}, databaseVersion DataApiAccess: _settings["data_api_access"].(string), DataDiskSizeGb: int64(_settings["disk_size"].(int)), DataDiskType: _settings["disk_type"].(string), -{{- if ne $.TargetVersionName "ga" }} DataDiskProvisionedIops: int64(_settings["data_disk_provisioned_iops"].(int)), DataDiskProvisionedThroughput: int64(_settings["data_disk_provisioned_throughput"].(int)), -{{- end }} PricingPlan: _settings["pricing_plan"].(string), DeletionProtectionEnabled: _settings["deletion_protection_enabled"].(bool), EnableGoogleMlIntegration: _settings["enable_google_ml_integration"].(bool), @@ -2417,6 +2417,11 @@ func resourceSqlDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error setting dns_names: %s", err) } d.SetId(instance.Name) + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } @@ -2430,6 +2435,11 @@ const ( ) func resourceSqlDatabaseInstanceUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceSqlDatabaseInstance) { + return ResourceSqlDatabaseInstance().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -2923,6 +2933,13 @@ func serverCertificateRotationModeDiffSuppress(_, oldMode, newMode string, _ *sc } func resourceSqlDatabaseInstanceDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -3013,10 +3030,8 @@ func flattenSettings(settings *sqladmin.Settings, iType string, d *schema.Resour "data_api_access": settings.DataApiAccess, "disk_type": settings.DataDiskType, "disk_size": settings.DataDiskSizeGb, -{{- if ne $.TargetVersionName "ga" }} "data_disk_provisioned_iops": settings.DataDiskProvisionedIops, "data_disk_provisioned_throughput": settings.DataDiskProvisionedThroughput, -{{- end }} "pricing_plan": settings.PricingPlan, "user_labels": settings.UserLabels, "password_validation_policy": settings.PasswordValidationPolicy, diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_meta.yaml.tmpl b/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_meta.yaml.tmpl index 5f9447be0818..cd912e77ea4f 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_meta.yaml.tmpl +++ b/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_meta.yaml.tmpl @@ -130,12 +130,8 @@ fields: field: 'settings.disk_autoresize_limit' - api_field: 'settings.dataDiskSizeGb' field: 'settings.disk_size' -{{- if ne $.TargetVersionName "ga" }} - api_field: 'settings.dataDiskProvisionedIops' -{{- end }} -{{- if ne $.TargetVersionName "ga" }} - api_field: 'settings.dataDiskProvisionedThroughput' -{{- end }} - api_field: 'settings.dataDiskType' field: 'settings.disk_type' - api_field: 'settings.edition' @@ -202,3 +198,5 @@ fields: - api_field: 'settings.userLabels' - api_field: 'settings.settingsVersion' field: 'settings.version' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_test.go.tmpl b/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_test.go similarity index 91% rename from mmv1/third_party/terraform/services/sql/resource_sql_database_instance_test.go.tmpl rename to mmv1/third_party/terraform/services/sql/resource_sql_database_instance_test.go index 57cb3114a070..adb148ab54ad 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_test.go.tmpl +++ b/mmv1/third_party/terraform/services/sql/resource_sql_database_instance_test.go @@ -1,8 +1,8 @@ - package sql_test import ( "fmt" + "log" "regexp" "strconv" "strings" @@ -11,15 +11,22 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/activedirectory" + "github.com/hashicorp/terraform-provider-google/google/services/backupdr" + tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/privateca" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/services/sql" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-testing/helper/resource" -{{- if ne $.TargetVersionName "ga" }} "github.com/hashicorp/terraform-plugin-testing/plancheck" -{{- end }} "github.com/hashicorp/terraform-plugin-testing/terraform" sqladmin "google.golang.org/api/sqladmin/v1beta4" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // Fields that should be ignored in import tests because they aren't returned @@ -40,6 +47,169 @@ var ignoredReplicaConfigurationFields = []string{ "replica_configuration.0.failover_target", } +// SQL Instance names are not reusable for a week after deletion +const SharedTestSQLInstanceNamePrefix = "tf-bootstrap-" + +// BootstrapSharedSQLInstanceBackupRun will return a shared SQL db instance that +// has a backup created for it. +func BootstrapSharedSQLInstanceBackupRun(t *testing.T) string { + project := envvar.GetTestProjectFromEnv() + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + log.Printf("[DEBUG] Getting list of existing sql instances") + + instances, err := sql.NewClient(config, config.UserAgent).Instances.List(project).Do() + if err != nil { + t.Fatalf("Unable to bootstrap SQL Instance. Cannot retrieve instance list: %s", err) + } + + var bootstrapInstance *sqladmin.DatabaseInstance + + // Look for any existing bootstrap instances + for _, i := range instances.Items { + if strings.HasPrefix(i.Name, SharedTestSQLInstanceNamePrefix) { + bootstrapInstance = i + break + } + } + + if bootstrapInstance == nil { + bootstrapInstanceName := SharedTestSQLInstanceNamePrefix + acctest.RandString(t, 10) + log.Printf("[DEBUG] Bootstrap SQL Instance not found, bootstrapping new instance %s", bootstrapInstanceName) + + backupConfig := &sqladmin.BackupConfiguration{ + Enabled: true, + PointInTimeRecoveryEnabled: true, + } + settings := &sqladmin.Settings{ + Tier: "db-custom-2-3840", + BackupConfiguration: backupConfig, + } + bootstrapInstance = &sqladmin.DatabaseInstance{ + Name: bootstrapInstanceName, + Region: "us-central1", + Settings: settings, + DatabaseVersion: "POSTGRES_11", + } + + var op *sqladmin.Operation + err = transport_tpg.Retry(transport_tpg.RetryOptions{ + RetryFunc: func() (operr error) { + op, operr = sql.NewClient(config, config.UserAgent).Instances.Insert(project, bootstrapInstance).Do() + return operr + }, + Timeout: 20 * time.Minute, + ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{transport_tpg.IsSqlOperationInProgressError}, + }) + if err != nil { + t.Fatalf("Error, failed to create instance %s: %s", bootstrapInstance.Name, err) + } + err = sql.SqlAdminOperationWaitTime(config, op, project, "Create Instance", config.UserAgent, 40*time.Minute) + if err != nil { + t.Fatalf("Error, failed to create instance %s: %s", bootstrapInstance.Name, err) + } + } + + // Look for backups in bootstrap instance + res, err := sql.NewClient(config, config.UserAgent).BackupRuns.List(project, bootstrapInstance.Name).Do() + if err != nil { + t.Fatalf("Unable to bootstrap SQL Instance. Cannot retrieve backup list: %s", err) + } + backupsList := res.Items + if len(backupsList) == 0 { + log.Printf("[DEBUG] No backups found for %s, creating backup", bootstrapInstance.Name) + backupRun := &sqladmin.BackupRun{ + Instance: bootstrapInstance.Name, + } + + var op *sqladmin.Operation + err = transport_tpg.Retry(transport_tpg.RetryOptions{ + RetryFunc: func() (operr error) { + op, operr = sql.NewClient(config, config.UserAgent).BackupRuns.Insert(project, bootstrapInstance.Name, backupRun).Do() + return operr + }, + Timeout: 20 * time.Minute, + ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{transport_tpg.IsSqlOperationInProgressError}, + }) + if err != nil { + t.Fatalf("Error, failed to create instance backup: %s", err) + } + err = sql.SqlAdminOperationWaitTime(config, op, project, "Backup Instance", config.UserAgent, 20*time.Minute) + if err != nil { + t.Fatalf("Error, failed to create instance backup: %s", err) + } + } + + return bootstrapInstance.Name +} + +const SharedTestADDomainPrefix = "tf-bootstrap-ad" + +func BootstrapSharedTestADDomain(t *testing.T, testId string, networkName string) string { + project := envvar.GetTestProjectFromEnv() + sharedADDomain := fmt.Sprintf("%s.%s.com", SharedTestADDomainPrefix, testId) + adDomainName := fmt.Sprintf("projects/%s/locations/global/domains/%s", project, sharedADDomain) + + config := transport_tpg.BootstrapConfig(t) + if config == nil { + return "" + } + + log.Printf("[DEBUG] Getting shared test active directory domain %q", adDomainName) + getURL := fmt.Sprintf("%s%s", transport_tpg.BaseUrl(activedirectory.Product, config), adDomainName) + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: getURL, + UserAgent: config.UserAgent, + Timeout: 4 * time.Minute, + }) + if err != nil && transport_tpg.IsGoogleApiErrorWithCode(err, 404) { + log.Printf("[DEBUG] AD domain %q not found, bootstrapping", sharedADDomain) + postURL := fmt.Sprintf("%sprojects/%s/locations/global/domains?domainName=%s", transport_tpg.BaseUrl(activedirectory.Product, config), project, sharedADDomain) + domainObj := map[string]interface{}{ + "locations": []string{"us-central1"}, + "reservedIpRange": "10.0.1.0/24", + "authorizedNetworks": []string{fmt.Sprintf("projects/%s/global/networks/%s", project, networkName)}, + } + + _, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: project, + RawURL: postURL, + UserAgent: config.UserAgent, + Body: domainObj, + Timeout: 60 * time.Minute, + }) + if err != nil { + t.Fatalf("Error bootstrapping shared active directory domain %q: %s", adDomainName, err) + } + + log.Printf("[DEBUG] Waiting for active directory domain creation to finish") + } + + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: project, + RawURL: getURL, + UserAgent: config.UserAgent, + Timeout: 4 * time.Minute, + }) + + if err != nil { + t.Fatalf("Error getting shared active directory domain %q: %s", adDomainName, err) + } + + return sharedADDomain +} + func TestAccSqlDatabaseInstance_basicInferredName(t *testing.T) { // Randomness acctest.SkipIfVcr(t) @@ -235,7 +405,7 @@ func TestAccSqlDatabaseInstance_basicMSSQL_passwordWo(t *testing.T) { { Config: fmt.Sprintf( testGoogleSqlDatabaseInstance_basic_mssql_wo_password, databaseName, rootPassword), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeTestCheckFunc( resource.TestCheckNoResourceAttr("google_sql_database_instance.instance", "root_password_wo"), resource.TestCheckResourceAttr("google_sql_database_instance.instance", "root_password_wo_version", "1"), ), @@ -249,7 +419,7 @@ func TestAccSqlDatabaseInstance_basicMSSQL_passwordWo(t *testing.T) { { Config: fmt.Sprintf( testGoogleSqlDatabaseInstance_basic_mssql_wo_password_update, databaseName, updatedRootPassword), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeTestCheckFunc( resource.TestCheckNoResourceAttr("google_sql_database_instance.instance", "root_password_wo"), resource.TestCheckResourceAttr("google_sql_database_instance.instance", "root_password_wo_version", "2"), ), @@ -326,8 +496,8 @@ func TestAccSqlDatabaseInstance_deleteDefaultUserBeforeSubsequentApiCalls(t *tes databaseName := "tf-test-" + acctest.RandString(t, 10) testId := "sql-instance-clone-2" - addressName := acctest.BootstrapSharedTestGlobalAddress(t, testId) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, testId) + addressName := tpgcompute.BootstrapSharedTestGlobalAddress(t, testId) + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, testId) // 1. Create an instance. // 2. Add a root@'%' user. @@ -682,13 +852,12 @@ func TestAccSqlDatabaseInstance_diskspecs(t *testing.T) { }) } -{{- if ne $.TargetVersionName "ga" }} func TestAccSqlDatabaseInstance_hyperdisk(t *testing.T) { t.Parallel() enterprisePlusName := "tf-test-enterprise-plus" + acctest.RandString(t, 10) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), Steps: []resource.TestStep{ { @@ -717,7 +886,6 @@ func TestAccSqlDatabaseInstance_hyperdisk(t *testing.T) { }, }) } -{{- end }} func TestAccSqlDatabaseInstance_maintenance(t *testing.T) { t.Parallel() @@ -945,7 +1113,7 @@ func TestAccSqlDatabaseInstance_withPrivateNetwork_withoutAllocatedIpRange(t *te t.Parallel() databaseName := "tf-test-" + acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "sql-instance-1") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "sql-instance-1") acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1069,7 +1237,6 @@ func TestAccSqlDatabaseInstance_updateMCPEnabled(t *testing.T) { }) } - func TestAccSqlDatabaseInstance_withPSCEnabled_withoutAllowedConsumerProjects(t *testing.T) { t.Parallel() @@ -1236,7 +1403,7 @@ func TestAccSqlDatabaseInstance_withPSCEnabled_withPscAutoConnections(t *testing testId := "test-psc-auto-con-1" instanceName := "tf-test-" + acctest.RandString(t, 10) projectId := envvar.GetTestProjectFromEnv() - networkName := acctest.BootstrapSharedTestNetwork(t, testId) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, testId) network_short_link_name := fmt.Sprintf("projects/%s/global/networks/%s", projectId, networkName) acctest.VcrTest(t, resource.TestCase{ @@ -1265,7 +1432,7 @@ func TestAccSqlDatabaseInstance_withPSCEnabled_thenAddPscAutoConnections_thenRem testId := "test-psc-auto-con-2" instanceName := "tf-test-" + acctest.RandString(t, 10) projectId := envvar.GetTestProjectFromEnv() - networkName := acctest.BootstrapSharedTestNetwork(t, testId) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, testId) network_short_link_name := fmt.Sprintf("projects/%s/global/networks/%s", projectId, networkName) acctest.VcrTest(t, resource.TestCase{ @@ -1334,12 +1501,11 @@ func TestAccSqlDatabaseInstance_withPscEnabled_withNetworkAttachmentUri_thenRemo networkNameStr := "tf-test-cloud-sql-network-psc-1" subnetworkNameStr := "tf-test-cloud-sql-subnetwork-psc-1" networkAttachmentNameStr := "tf-test-cloud-sql-update-na-psc-1" - networkName := acctest.BootstrapSharedTestNetwork(t, networkNameStr) - subnetworkName := acctest.BootstrapSubnet(t, subnetworkNameStr, networkName) - networkAttachmentName := acctest.BootstrapNetworkAttachment(t, networkAttachmentNameStr, subnetworkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, networkNameStr) + subnetworkName := tpgcompute.BootstrapSubnet(t, subnetworkNameStr, networkName) + networkAttachmentName := tpgcompute.BootstrapNetworkAttachment(t, networkAttachmentNameStr, subnetworkName) networkAttachmentUri := fmt.Sprintf("projects/%s/regions/%s/networkAttachments/%s", projectId, region, networkAttachmentName) - acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), @@ -1385,19 +1551,18 @@ func TestAccSqlDatabaseInstance_withPscEnabled_withNetworkAttachmentUriOnCreate( networkNameStr := "tf-test-cloud-sql-network-psc-2" subnetworkNameStr := "tf-test-cloud-sql-subnetwork-psc-2" networkAttachmentNameStr := "tf-test-cloud-sql-update-na-psc-2" - networkName := acctest.BootstrapSharedTestNetwork(t, networkNameStr) - subnetworkName := acctest.BootstrapSubnet(t, subnetworkNameStr, networkName) - networkAttachmentName := acctest.BootstrapNetworkAttachment(t, networkAttachmentNameStr, subnetworkName) + networkName := tpgcompute.BootstrapSharedTestNetwork(t, networkNameStr) + subnetworkName := tpgcompute.BootstrapSubnet(t, subnetworkNameStr, networkName) + networkAttachmentName := tpgcompute.BootstrapNetworkAttachment(t, networkAttachmentNameStr, subnetworkName) networkAttachmentUri := fmt.Sprintf("projects/%s/regions/%s/networkAttachments/%s", projectId, region, networkAttachmentName) - acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccSqlDatabaseInstance_withPSCEnabled_withNetworkAttachmentUri(instanceName, networkAttachmentUri), + Config: testAccSqlDatabaseInstance_withPSCEnabled_withNetworkAttachmentUri(instanceName, networkAttachmentUri), ExpectError: regexp.MustCompile(`.*Network attachment used for Private Service Connect interfaces can not be assigned with instance creation.*`), }, }, @@ -1411,12 +1576,12 @@ func TestAccSqlDatabaseInstance_withPrivateNetwork_withAllocatedIpRange(t *testi databaseName := "tf-test-" + acctest.RandString(t, 10) testId := "sql-instance-allocated-1" - addressName := acctest.BootstrapSharedTestGlobalAddress(t, testId) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, testId) + addressName := tpgcompute.BootstrapSharedTestGlobalAddress(t, testId) + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, testId) updateTestId := "sql-instance-allocated-update-1" - addressName_update := acctest.BootstrapSharedTestGlobalAddress(t, updateTestId) - networkName_update := acctest.BootstrapSharedServiceNetworkingConnection(t, updateTestId) + addressName_update := tpgcompute.BootstrapSharedTestGlobalAddress(t, updateTestId) + networkName_update := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, updateTestId) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1452,8 +1617,8 @@ func TestAccSqlDatabaseInstance_withPrivateNetwork_withAllocatedIpRangeReplica(t databaseName := "tf-test-" + acctest.RandString(t, 10) testId := "sql-instance-replica-1" - addressName := acctest.BootstrapSharedTestGlobalAddress(t, testId) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, testId) + addressName := tpgcompute.BootstrapSharedTestGlobalAddress(t, testId) + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, testId) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1485,8 +1650,8 @@ func TestAccSqlDatabaseInstance_withPrivateNetwork_withAllocatedIpRangeClone(t * databaseName := "tf-test-" + acctest.RandString(t, 10) testId := "sql-instance-clone-1" - addressName := acctest.BootstrapSharedTestGlobalAddress(t, testId) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, testId) + addressName := tpgcompute.BootstrapSharedTestGlobalAddress(t, testId) + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, testId) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1519,7 +1684,7 @@ func TestAccSqlDatabaseInstance_createFromBackup(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "original_db_name": acctest.BootstrapSharedSQLInstanceBackupRun(t), + "original_db_name": BootstrapSharedSQLInstanceBackupRun(t), } acctest.VcrTest(t, resource.TestCase{ @@ -1546,19 +1711,19 @@ func TestAccSqlDatabaseInstance_createFromBackupDR(t *testing.T) { t.Parallel() // Bootstrap the BackupDR vault - backupVaultID := "bv-test" - vaultLocation := "us-central1" - project := envvar.GetTestProjectFromEnv() - backupvault := acctest.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupvault, + backupVaultID := "bv-test" + vaultLocation := "us-central1" + project := envvar.GetTestProjectFromEnv() + backupvault := backupdr.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupvault, "target_instance_region": "us-central1", - "vault_location": vaultLocation, - } + "vault_location": vaultLocation, + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1588,8 +1753,8 @@ func TestAccSqlDatabaseInstance_backupUpdate(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "db_version": "POSTGRES_11", - "original_db_name": acctest.BootstrapSharedSQLInstanceBackupRun(t), + "db_version": "POSTGRES_11", + "original_db_name": BootstrapSharedSQLInstanceBackupRun(t), } acctest.VcrTest(t, resource.TestCase{ @@ -1620,23 +1785,23 @@ func TestAccSqlDatabaseInstance_backupUpdate(t *testing.T) { } func TestAccSqlDatabaseInstance_BackupDRUpdate(t *testing.T) { - t.Skip("https://github.com/hashicorp/terraform-provider-google/issues/24234") - acctest.SkipIfVcr(t) + t.Skip("https://github.com/hashicorp/terraform-provider-google/issues/24234") + acctest.SkipIfVcr(t) t.Parallel() // Bootstrap the BackupDR vault - backupVaultID := "bv-test" - location := "us-central1" - project := envvar.GetTestProjectFromEnv() - backupvault := acctest.BootstrapBackupDRVault(t, backupVaultID, location) + backupVaultID := "bv-test" + location := "us-central1" + project := envvar.GetTestProjectFromEnv() + backupvault := backupdr.BootstrapBackupDRVault(t, backupVaultID, location) - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupvault, - "db_version": "MYSQL_8_0_41", - } + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupvault, + "db_version": "MYSQL_8_0_41", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1672,19 +1837,19 @@ func TestAccSqlDatabaseInstance_createFromCrossRegionBackupDrBackup(t *testing.T t.Parallel() // Bootstrap the BackupDR vault - backupVaultID := "bv-test" + backupVaultID := "bv-test" vaultLocation := "us-central1" - project := envvar.GetTestProjectFromEnv() - backupvault := acctest.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupvault, + project := envvar.GetTestProjectFromEnv() + backupvault := backupdr.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupvault, "target_instance_region": "us-east1", - "vault_location": vaultLocation, - } + "vault_location": vaultLocation, + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1711,19 +1876,19 @@ func TestAccSqlDatabaseInstance_createFromMultiRegionBackupDrBackup(t *testing.T t.Parallel() // Bootstrap the BackupDR vault - backupVaultID := "bv-test-mr" + backupVaultID := "bv-test-mr" vaultLocation := "us" - project := envvar.GetTestProjectFromEnv() - backupvault := acctest.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupvault, + project := envvar.GetTestProjectFromEnv() + backupvault := backupdr.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupvault, "target_instance_region": "us-central1", - "vault_location": vaultLocation, - } + "vault_location": vaultLocation, + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1750,19 +1915,19 @@ func TestAccSqlDatabaseInstance_createFromMultiRegionBackupDrBackupCrossRegion(t t.Parallel() // Bootstrap the BackupDR vault - backupVaultID := "bv-test-mr" + backupVaultID := "bv-test-mr" vaultLocation := "us" - project := envvar.GetTestProjectFromEnv() - backupvault := acctest.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupvault, + project := envvar.GetTestProjectFromEnv() + backupvault := backupdr.BootstrapBackupDRVault(t, backupVaultID, vaultLocation) + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupvault, "target_instance_region": "us-east1", - "vault_location": vaultLocation, - } + "vault_location": vaultLocation, + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1792,7 +1957,7 @@ func TestAccSqlDatabaseInstance_basicClone(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "original_db_name": acctest.BootstrapSharedSQLInstanceBackupRun(t), + "original_db_name": BootstrapSharedSQLInstanceBackupRun(t), } acctest.VcrTest(t, resource.TestCase{ @@ -1817,9 +1982,9 @@ func TestAccSqlDatabaseInstance_crossProjectClone(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "orgId": envvar.GetTestOrgFromEnv(t), - "billingAccount": envvar.GetTestBillingAccountFromEnv(t), + "random_suffix": acctest.RandString(t, 10), + "orgId": envvar.GetTestOrgFromEnv(t), + "billingAccount": envvar.GetTestBillingAccountFromEnv(t), "cloneSourceProject": envvar.GetTestProjectFromEnv(), } @@ -1837,7 +2002,7 @@ func TestAccSqlDatabaseInstance_crossProjectClone(t *testing.T) { ResourceName: "google_sql_database_instance.instance", ImportState: true, ImportStateVerify: true, - ImportStateIdFunc: testAccSqlDatabaseInstanceImportStateIdFunc("google_sql_database_instance.instance"), + ImportStateIdFunc: testAccSqlDatabaseInstanceImportStateIdFunc("google_sql_database_instance.instance"), ImportStateVerifyIgnore: []string{"deletion_protection", "clone"}, }, }, @@ -1861,7 +2026,7 @@ func TestAccSqlDatabaseInstance_cloneWithSettings(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "original_db_name": acctest.BootstrapSharedSQLInstanceBackupRun(t), + "original_db_name": BootstrapSharedSQLInstanceBackupRun(t), } acctest.VcrTest(t, resource.TestCase{ @@ -1889,7 +2054,7 @@ func TestAccSqlDatabaseInstance_cloneWithDatabaseNames(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "original_db_name": acctest.BootstrapSharedSQLInstanceBackupRun(t), + "original_db_name": BootstrapSharedSQLInstanceBackupRun(t), } acctest.VcrTest(t, resource.TestCase{ @@ -1915,18 +2080,18 @@ func TestAccSqlDatabaseInstance_pointInTimeRestore(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - backupVaultID := "bv-test" - location := "us-central1" - project := envvar.GetTestProjectFromEnv() - backupVault := acctest.BootstrapBackupDRVault(t, backupVaultID, location) + backupVaultID := "bv-test" + location := "us-central1" + project := envvar.GetTestProjectFromEnv() + backupVault := backupdr.BootstrapBackupDRVault(t, backupVaultID, location) - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupVault, - "db_version": "MYSQL_8_0_41", - } + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupVault, + "db_version": "MYSQL_8_0_41", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1954,17 +2119,17 @@ func TestAccSqlDatabaseInstance_pointInTimeRestoreInMultiRegion(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - backupVaultID := "bv-test-mr" - location := "us" - project := envvar.GetTestProjectFromEnv() - backupVault := acctest.BootstrapBackupDRVault(t, backupVaultID, location) + backupVaultID := "bv-test-mr" + location := "us" + project := envvar.GetTestProjectFromEnv() + backupVault := backupdr.BootstrapBackupDRVault(t, backupVaultID, location) - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupVault, - } + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupVault, + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -1992,18 +2157,18 @@ func TestAccSqlDatabaseInstance_pointInTimeRestoreWithSettings(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - backupVaultID := "bv-test" - location := "us-central1" - project := envvar.GetTestProjectFromEnv() - backupVault := acctest.BootstrapBackupDRVault(t, backupVaultID, location) + backupVaultID := "bv-test" + location := "us-central1" + project := envvar.GetTestProjectFromEnv() + backupVault := backupdr.BootstrapBackupDRVault(t, backupVaultID, location) - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupVault, - "db_version": "MYSQL_8_0_41", - } + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupVault, + "db_version": "MYSQL_8_0_41", + } acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -2430,8 +2595,8 @@ func TestAccSqlDatabaseInstance_encryptionKey_replicaInDifferentRegion(t *testin context := map[string]interface{}{ "project_id": envvar.GetTestProjectFromEnv(), "instance_name": "tf-test-sql-" + acctest.RandString(t, 10), - "kms_key_name1": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-sql-database-instance-key1").CryptoKey.Name, - "kms_key_name2": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-bootstrap-sql-database-instance-key2").CryptoKey.Name, + "kms_key_name1": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-sql-database-instance-key1").CryptoKey.Name, + "kms_key_name2": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-east1", "tf-bootstrap-sql-database-instance-key2").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ @@ -2466,9 +2631,9 @@ func TestAccSqlDatabaseInstance_ActiveDirectory(t *testing.T) { t.Parallel() databaseName := "tf-test-" + acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "sql-instance-ad-1") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "sql-instance-ad-1") rootPassword := acctest.RandString(t, 15) - adDomainName := acctest.BootstrapSharedTestADDomain(t, "test-domain", networkName) + adDomainName := BootstrapSharedTestADDomain(t, "test-domain", networkName) acctest.VcrTest(t, resource.TestCase{ PreCheck: func() { acctest.AccTestPreCheck(t) }, @@ -3442,7 +3607,7 @@ func TestAccSqlDatabaseInstance_MysqlEplusWithFailoverReplicaSetupWithPrivateNet primaryName := "tf-test-mysql-primary-" + acctest.RandString(t, 10) replicaName := "tf-test-mysql-replica-" + acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "endpoint") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "endpoint") projectId := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -3481,7 +3646,7 @@ func TestAccSqlDatabaseInstance_PostgresEplusWithFailoverReplicaSetupWithPrivate primaryName := "tf-test-postgres-primary-" + acctest.RandString(t, 10) replicaName := "tf-test-postgres-replica-" + acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "endpoint") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "endpoint") projectId := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -3519,7 +3684,7 @@ func TestAccSqlDatabaseInstance_MysqlEplusWithPrivateNetwork(t *testing.T) { t.Parallel() instanceName := "tf-test-" + acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "endpoint") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "endpoint") projectId := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -3546,7 +3711,7 @@ func TestAccSqlDatabaseInstance_PostgresEplusWithPrivateNetwork(t *testing.T) { t.Parallel() instanceName := "tf-test-" + acctest.RandString(t, 10) - networkName := acctest.BootstrapSharedServiceNetworkingConnection(t, "endpoint") + networkName := servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "endpoint") projectId := envvar.GetTestProjectFromEnv() acctest.VcrTest(t, resource.TestCase{ @@ -3791,10 +3956,10 @@ func TestAccSqlDatabaseInstance_PostgresReadPoolScaleUpSuccess(t *testing.T) { Steps: []resource.TestStep{ { Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - NodeCount: 1, - ReplicaMachineType: "db-perf-optimized-N-2", + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + NodeCount: 1, + ReplicaMachineType: "db-perf-optimized-N-2", }), }, { @@ -3811,10 +3976,10 @@ func TestAccSqlDatabaseInstance_PostgresReadPoolScaleUpSuccess(t *testing.T) { }, { Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - NodeCount: 1, - ReplicaMachineType: "db-perf-optimized-N-4", + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + NodeCount: 1, + ReplicaMachineType: "db-perf-optimized-N-4", }), }, { @@ -3910,170 +4075,168 @@ func TestAccSqlDatabaseInstance_MysqlReadPoolEnableDisableSuccess(t *testing.T) // Read pool for MySQL. Enable and disable read pool auto scale func TestAccSqlDatabaseInstance_MysqlReadPoolAutoScaleEnableDisableSuccess(t *testing.T) { - t.Parallel() - primaryName := "tf-test-mysql-as-readpool-primary-" + acctest.RandString(t, 10) - readPoolName := "tf-test-mysql-as-readpool-" + acctest.RandString(t, 10) - project := envvar.GetTestProjectFromEnv() - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "MYSQL_8_0", - ReplicaName: readPoolName, - }), - }, - { - ResourceName: "google_sql_database_instance.original-primary", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"deletion_protection"}, - }, - { - ResourceName: "google_sql_database_instance.original-read-pool", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"deletion_protection"}, - }, - // Enable auto scale - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "MYSQL_8_0", - ReplicaName: readPoolName, - AutoScaleEnabled: true, - NodeCount: 2, - MaxNodeCount: 2, - MinNodeCount: 2, - }), - }, - { - ResourceName: "google_sql_database_instance.original-primary", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"deletion_protection"}, - }, - { - ResourceName: "google_sql_database_instance.original-read-pool", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"deletion_protection"}, - }, - // Disable auto scale - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "MYSQL_8_0", - ReplicaName: readPoolName, - AutoScaleEnabled: false, - }), - }, - { - ResourceName: "google_sql_database_instance.original-primary", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"deletion_protection"}, - }, - { - ResourceName: "google_sql_database_instance.original-read-pool", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"deletion_protection"}, - }, - }, - }) + t.Parallel() + primaryName := "tf-test-mysql-as-readpool-primary-" + acctest.RandString(t, 10) + readPoolName := "tf-test-mysql-as-readpool-" + acctest.RandString(t, 10) + project := envvar.GetTestProjectFromEnv() + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "MYSQL_8_0", + ReplicaName: readPoolName, + }), + }, + { + ResourceName: "google_sql_database_instance.original-primary", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + { + ResourceName: "google_sql_database_instance.original-read-pool", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + // Enable auto scale + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "MYSQL_8_0", + ReplicaName: readPoolName, + AutoScaleEnabled: true, + NodeCount: 2, + MaxNodeCount: 2, + MinNodeCount: 2, + }), + }, + { + ResourceName: "google_sql_database_instance.original-primary", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + { + ResourceName: "google_sql_database_instance.original-read-pool", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + // Disable auto scale + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "MYSQL_8_0", + ReplicaName: readPoolName, + AutoScaleEnabled: false, + }), + }, + { + ResourceName: "google_sql_database_instance.original-primary", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + { + ResourceName: "google_sql_database_instance.original-read-pool", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deletion_protection"}, + }, + }, + }) } - // Read pool for Postgres. Modify Node Count when auto scale enabled func TestAccSqlDatabaseInstance_PostgresReadPoolAutoScaleChangeNodeCount(t *testing.T) { - t.Parallel() - primaryName := "tf-test-postgreas-as-readpool-primary-" + acctest.RandString(t, 10) - readPoolName := "tf-test-postgres-as-readpool-" + acctest.RandString(t, 10) - project := envvar.GetTestProjectFromEnv() - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), - Steps: []resource.TestStep{ - // Create with auto scale takes min node count as node count - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - AutoScaleEnabled: true, - NodeCount: 2, - MinNodeCount: 1, - MaxNodeCount: 5, - }), - Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 1, 1, 5), - }, - // Change node count not respected - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - AutoScaleEnabled: true, - NodeCount: 4, - MinNodeCount: 1, - MaxNodeCount: 5, - }), - Check: resource.ComposeTestCheckFunc( - testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 1, 1, 5), - testGoogleSqlDatabaseInstanceChangeNodeCount(t, readPoolName, 3), - ), // Simulate auto scale to 3 nodes. - - }, - // Change Min/Max (no change to node count) - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - AutoScaleEnabled: true, - NodeCount: 4, - MinNodeCount: 2, - MaxNodeCount: 4, - }), - Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 3, 2, 4), - }, - // Change Min (higher than node count), sets node count - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - AutoScaleEnabled: true, - NodeCount: 3, - MinNodeCount: 4, - MaxNodeCount: 5, - }), - Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 4, 4, 5), - }, - // Change Max (lower than node count), sets node count - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - AutoScaleEnabled: true, - NodeCount: 5, - MinNodeCount: 3, - MaxNodeCount: 3, - }), - Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 3, 3, 3), - }, - // Disable auto scale, sets node count - { - Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ - DatabaseType: "POSTGRES_15", - ReplicaName: readPoolName, - AutoScaleEnabled: false, - NodeCount: 2, - }), - Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 2, 0, 0), - }, - }, - }) -} + t.Parallel() + primaryName := "tf-test-postgreas-as-readpool-primary-" + acctest.RandString(t, 10) + readPoolName := "tf-test-postgres-as-readpool-" + acctest.RandString(t, 10) + project := envvar.GetTestProjectFromEnv() + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + // Create with auto scale takes min node count as node count + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + AutoScaleEnabled: true, + NodeCount: 2, + MinNodeCount: 1, + MaxNodeCount: 5, + }), + Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 1, 1, 5), + }, + // Change node count not respected + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + AutoScaleEnabled: true, + NodeCount: 4, + MinNodeCount: 1, + MaxNodeCount: 5, + }), + Check: resource.ComposeTestCheckFunc( + testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 1, 1, 5), + testGoogleSqlDatabaseInstanceChangeNodeCount(t, readPoolName, 3), + ), // Simulate auto scale to 3 nodes. + }, + // Change Min/Max (no change to node count) + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + AutoScaleEnabled: true, + NodeCount: 4, + MinNodeCount: 2, + MaxNodeCount: 4, + }), + Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 3, 2, 4), + }, + // Change Min (higher than node count), sets node count + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + AutoScaleEnabled: true, + NodeCount: 3, + MinNodeCount: 4, + MaxNodeCount: 5, + }), + Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 4, 4, 5), + }, + // Change Max (lower than node count), sets node count + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + AutoScaleEnabled: true, + NodeCount: 5, + MinNodeCount: 3, + MaxNodeCount: 3, + }), + Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 3, 3, 3), + }, + // Disable auto scale, sets node count + { + Config: testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName, ReadPoolConfig{ + DatabaseType: "POSTGRES_15", + ReplicaName: readPoolName, + AutoScaleEnabled: false, + NodeCount: 2, + }), + Check: testGoogleSqlDatabaseInstanceCheckNodeCount(t, readPoolName, 2, 0, 0), + }, + }, + }) +} func TestAccSqlDatabaseInstance_updateSslOptionsForPostgreSQL(t *testing.T) { t.Parallel() @@ -4234,7 +4397,6 @@ func TestAccSqlDatabaseInstance_setServerCertRotationMode(t *testing.T) { }) } - func TestAccSqlDatabaseInstance_useCustomSubjectAlternateName(t *testing.T) { t.Parallel() @@ -4253,7 +4415,7 @@ func TestAccSqlDatabaseInstance_useCustomSubjectAlternateName(t *testing.T) { ExternalProviders: map[string]resource.ExternalProvider{ "time": {}, }, - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), Steps: []resource.TestStep{ { @@ -4290,7 +4452,7 @@ func TestAccSqlDatabaseInstance_useCustomerManagedServerCa(t *testing.T) { ExternalProviders: map[string]resource.ExternalProvider{ "time": {}, }, - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), Steps: []resource.TestStep{ { @@ -4411,235 +4573,234 @@ func TestAccSqlDatabaseInstance_DiskSizeAutoResizeWithDiskSize(t *testing.T) { } func TestEnhancedBackupManagerDiffSuppressFunc(t *testing.T) { - cases := map[string]struct { - key string - old string - new string - backupTier string - expectSuppress bool - description string - }{ - "suppress enabled diff when backup tier is enhanced": { - key: "settings.0.backup_configuration.0.enabled", - old: "true", - new: "false", - backupTier: "ENHANCED", - expectSuppress: true, - description: "enabled should be suppressed when ENHANCED", - }, - "suppress start_time diff when backup tier is enhanced": { - key: "settings.0.backup_configuration.0.start_time", - old: "03:00", - new: "05:00", - backupTier: "ENHANCED", - expectSuppress: true, - description: "start_time should be suppressed when ENHANCED", - }, - "suppress binary_log_enabled diff when backup tier is enhanced": { - key: "settings.0.backup_configuration.0.binary_log_enabled", - old: "true", - new: "false", - backupTier: "ENHANCED", - expectSuppress: true, - description: "binary_log_enabled should be suppressed when ENHANCED", - }, - "suppress point_in_time_recovery_enabled diff when backup tier is enhanced": { - key: "settings.0.backup_configuration.0.point_in_time_recovery_enabled", - old: "false", - new: "true", - backupTier: "ENHANCED", - expectSuppress: true, - description: "point_in_time_recovery_enabled should be suppressed when ENHANCED", - }, - "suppress transaction_log_retention_days diff when backup tier is enhanced": { - key: "settings.0.backup_configuration.0.transaction_log_retention_days", - old: "7", - new: "14", - backupTier: "ENHANCED", - expectSuppress: true, - description: "transaction_log_retention_days should be suppressed when ENHANCED", - }, - "suppress retained_backups diff when backup tier is enhanced": { - key: "settings.0.backup_configuration.0.backup_retention_settings.0.retained_backups", - old: "7", - new: "14", - backupTier: "ENHANCED", - expectSuppress: true, - description: "retained_backups should be suppressed when ENHANCED", - }, - "do not suppress diff when backup tier is standard": { - key: "settings.0.backup_configuration.0.enabled", - old: "true", - new: "false", - backupTier: "STANDARD", - expectSuppress: false, - description: "enabled should NOT be suppressed when STANDARD", - }, - "do not suppress diff when backup tier is empty": { - key: "settings.0.backup_configuration.0.enabled", - old: "true", - new: "false", - backupTier: "", - expectSuppress: false, - description: "enabled should NOT be suppressed when backup_tier is empty", - }, - "do not suppress when old and new are same": { - key: "settings.0.backup_configuration.0.enabled", - old: "true", - new: "true", - backupTier: "ENHANCED", - expectSuppress: true, - description: "no diff to suppress when old and new are same", - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - // Build real *schema.ResourceData using the resource schema and TestResourceDataRaw - // Put backup_tier into the nested settings->backup_configuration block (state) - rd := schema.TestResourceDataRaw(t, sql.ResourceSqlDatabaseInstance().Schema, map[string]interface{}{ - "name": "test-instance", - "settings": []interface{}{ - map[string]interface{}{ - "backup_configuration": []interface{}{ - map[string]interface{}{ - "backup_tier": tc.backupTier, - }, - }, - }, - }, - }) - - suppressed := sql.EnhancedBackupManagerDiffSuppressFunc(tc.key, tc.old, tc.new, rd) - - if suppressed != tc.expectSuppress { - t.Errorf("expected suppressed to be %v but got %v. Desc: %s", tc.expectSuppress, suppressed, tc.description) - } - }) - } + cases := map[string]struct { + key string + old string + new string + backupTier string + expectSuppress bool + description string + }{ + "suppress enabled diff when backup tier is enhanced": { + key: "settings.0.backup_configuration.0.enabled", + old: "true", + new: "false", + backupTier: "ENHANCED", + expectSuppress: true, + description: "enabled should be suppressed when ENHANCED", + }, + "suppress start_time diff when backup tier is enhanced": { + key: "settings.0.backup_configuration.0.start_time", + old: "03:00", + new: "05:00", + backupTier: "ENHANCED", + expectSuppress: true, + description: "start_time should be suppressed when ENHANCED", + }, + "suppress binary_log_enabled diff when backup tier is enhanced": { + key: "settings.0.backup_configuration.0.binary_log_enabled", + old: "true", + new: "false", + backupTier: "ENHANCED", + expectSuppress: true, + description: "binary_log_enabled should be suppressed when ENHANCED", + }, + "suppress point_in_time_recovery_enabled diff when backup tier is enhanced": { + key: "settings.0.backup_configuration.0.point_in_time_recovery_enabled", + old: "false", + new: "true", + backupTier: "ENHANCED", + expectSuppress: true, + description: "point_in_time_recovery_enabled should be suppressed when ENHANCED", + }, + "suppress transaction_log_retention_days diff when backup tier is enhanced": { + key: "settings.0.backup_configuration.0.transaction_log_retention_days", + old: "7", + new: "14", + backupTier: "ENHANCED", + expectSuppress: true, + description: "transaction_log_retention_days should be suppressed when ENHANCED", + }, + "suppress retained_backups diff when backup tier is enhanced": { + key: "settings.0.backup_configuration.0.backup_retention_settings.0.retained_backups", + old: "7", + new: "14", + backupTier: "ENHANCED", + expectSuppress: true, + description: "retained_backups should be suppressed when ENHANCED", + }, + "do not suppress diff when backup tier is standard": { + key: "settings.0.backup_configuration.0.enabled", + old: "true", + new: "false", + backupTier: "STANDARD", + expectSuppress: false, + description: "enabled should NOT be suppressed when STANDARD", + }, + "do not suppress diff when backup tier is empty": { + key: "settings.0.backup_configuration.0.enabled", + old: "true", + new: "false", + backupTier: "", + expectSuppress: false, + description: "enabled should NOT be suppressed when backup_tier is empty", + }, + "do not suppress when old and new are same": { + key: "settings.0.backup_configuration.0.enabled", + old: "true", + new: "true", + backupTier: "ENHANCED", + expectSuppress: true, + description: "no diff to suppress when old and new are same", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + // Build real *schema.ResourceData using the resource schema and TestResourceDataRaw + // Put backup_tier into the nested settings->backup_configuration block (state) + rd := schema.TestResourceDataRaw(t, sql.ResourceSqlDatabaseInstance().Schema, map[string]interface{}{ + "name": "test-instance", + "settings": []interface{}{ + map[string]interface{}{ + "backup_configuration": []interface{}{ + map[string]interface{}{ + "backup_tier": tc.backupTier, + }, + }, + }, + }, + }) + + suppressed := sql.EnhancedBackupManagerDiffSuppressFunc(tc.key, tc.old, tc.new, rd) + + if suppressed != tc.expectSuppress { + t.Errorf("expected suppressed to be %v but got %v. Desc: %s", tc.expectSuppress, suppressed, tc.description) + } + }) + } } func TestAccSqlDatabaseInstance_updateInstanceTierForEnhancedBackupTierInstance(t *testing.T) { - t.Parallel() - - backupVaultID := "bv-test" - location := "us-central1" - project := envvar.GetTestProjectFromEnv() - backupVault := acctest.BootstrapBackupDRVault(t, backupVaultID, location) - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": project, - "backup_vault_id": backupVaultID, - "backup_vault": backupVault, - "db_version": "MYSQL_8_0_41", - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), - Steps: []resource.TestStep{ - { - // Create backup plan and associate with instance - Config: testGoogleSqlDatabaseInstance_attachGCBDR(context), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("google_backup_dr_backup_plan_association.backup_association", "id"), - ), - }, - { - // Update instance backup tier to ENHANCED, which should ignore backup_configuration settings + t.Parallel() + + backupVaultID := "bv-test" + location := "us-central1" + project := envvar.GetTestProjectFromEnv() + backupVault := backupdr.BootstrapBackupDRVault(t, backupVaultID, location) + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": project, + "backup_vault_id": backupVaultID, + "backup_vault": backupVault, + "db_version": "MYSQL_8_0_41", + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + { + // Create backup plan and associate with instance + Config: testGoogleSqlDatabaseInstance_attachGCBDR(context), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrSet("google_backup_dr_backup_plan_association.backup_association", "id"), + ), + }, + { + // Update instance backup tier to ENHANCED, which should ignore backup_configuration settings Config: testGoogleSqlDatabaseInstance_updateTierForGcbdrManagedInstance(context), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("google_sql_database_instance.instance", "settings.0.tier", "db-g1-small"), ), - }, - }, - }) + }, + }, + }) } func TestAccSqlDatabaseInstance_majorVersionUpgradeForEnhancedBackupTierInstance(t *testing.T) { - t.Parallel() - - backupVault := acctest.BootstrapBackupDRVault(t, "bv-test", "us-central1") - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": envvar.GetTestProjectFromEnv(), - "backup_vault": backupVault, - "db_version": "MYSQL_8_0_41", - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), - Steps: []resource.TestStep{ - { - // Create backup plan and associate with instance - Config: testGoogleSqlDatabaseInstance_attachGCBDR(context), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("google_backup_dr_backup_plan_association.backup_association", "id"), - ), - }, - { - // Update instance database version to a new major version, which should ignore backup_configuration settings + t.Parallel() + + backupVault := backupdr.BootstrapBackupDRVault(t, "bv-test", "us-central1") + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": envvar.GetTestProjectFromEnv(), + "backup_vault": backupVault, + "db_version": "MYSQL_8_0_41", + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + { + // Create backup plan and associate with instance + Config: testGoogleSqlDatabaseInstance_attachGCBDR(context), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrSet("google_backup_dr_backup_plan_association.backup_association", "id"), + ), + }, + { + // Update instance database version to a new major version, which should ignore backup_configuration settings Config: testGoogleSqlDatabaseInstance_majorVersionUpgradeGcbdrManagedInstance(context), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("google_sql_database_instance.instance", "database_version", "MYSQL_8_0_42"), ), - }, - }, - }) + }, + }, + }) } func TestAccSqlDatabaseInstance_editionUpdateForEnhancedBackupTierInstance(t *testing.T) { - t.Parallel() - - backupVault := acctest.BootstrapBackupDRVault(t, "bv-test", "us-central1") - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "project": envvar.GetTestProjectFromEnv(), - "backup_vault": backupVault, - "db_version": "MYSQL_8_0_41", - "edition": "ENTERPRISE", - "tier": "db-f1-micro", - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), - Steps: []resource.TestStep{ - { - // Create backup plan and associate with instance - Config: testGoogleSqlDatabaseInstance_attachGCBDR(context), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("google_backup_dr_backup_plan_association.backup_association", "id"), - ), - }, - { - // Edition upgrade, which should ignore backup_configuration settings + t.Parallel() + + backupVault := backupdr.BootstrapBackupDRVault(t, "bv-test", "us-central1") + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + "project": envvar.GetTestProjectFromEnv(), + "backup_vault": backupVault, + "db_version": "MYSQL_8_0_41", + "edition": "ENTERPRISE", + "tier": "db-f1-micro", + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccSqlDatabaseInstanceDestroyProducer(t), + Steps: []resource.TestStep{ + { + // Create backup plan and associate with instance + Config: testGoogleSqlDatabaseInstance_attachGCBDR(context), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrSet("google_backup_dr_backup_plan_association.backup_association", "id"), + ), + }, + { + // Edition upgrade, which should ignore backup_configuration settings Config: testGoogleSqlDatabaseInstance_editionUpdateForGcbdrManagedInstance(context, "ENTERPRISE_PLUS", "db-perf-optimized-N-4"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("google_sql_database_instance.instance", "settings.0.edition", "ENTERPRISE_PLUS"), ), - }, + }, { - // Edition downgrade, which should ignore backup_configuration settings + // Edition downgrade, which should ignore backup_configuration settings Config: testGoogleSqlDatabaseInstance_editionUpdateForGcbdrManagedInstance(context, "ENTERPRISE", "db-f1-micro"), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("google_sql_database_instance.instance", "settings.0.edition", "ENTERPRISE"), ), - }, - - }, - }) + }, + }, + }) } func testGoogleSqlDatabaseInstance_attachGCBDR(context map[string]interface{}) string { - return acctest.Nprintf(` + return acctest.Nprintf(` data "google_project" "project" {} resource "google_sql_database_instance" "instance" { @@ -4687,7 +4848,7 @@ resource "google_backup_dr_backup_plan_association" "backup_association" { } func testGoogleSqlDatabaseInstance_updateTierForGcbdrManagedInstance(context map[string]interface{}) string { - return acctest.Nprintf(` + return acctest.Nprintf(` data "google_project" "project" {} resource "google_sql_database_instance" "instance" { @@ -4746,7 +4907,7 @@ resource "google_backup_dr_backup_plan_association" "backup_association" { } func testGoogleSqlDatabaseInstance_majorVersionUpgradeGcbdrManagedInstance(context map[string]interface{}) string { - return acctest.Nprintf(` + return acctest.Nprintf(` data "google_project" "project" {} resource "google_sql_database_instance" "instance" { @@ -4805,14 +4966,14 @@ resource "google_backup_dr_backup_plan_association" "backup_association" { } func testGoogleSqlDatabaseInstance_editionUpdateForGcbdrManagedInstance(context map[string]interface{}, edition string, tier string) string { - // Create a copy of the context map to avoid modifying the map from the caller - localContext := make(map[string]interface{}) + // Create a copy of the context map to avoid modifying the map from the caller + localContext := make(map[string]interface{}) for k, v := range context { - localContext[k] = v - } - localContext["edition"] = edition - localContext["tier"] = tier - return acctest.Nprintf(` + localContext[k] = v + } + localContext["edition"] = edition + localContext["tier"] = tier + return acctest.Nprintf(` data "google_project" "project" {} resource "google_sql_database_instance" "instance" { @@ -5072,7 +5233,7 @@ resource "google_sql_database_instance" "instance" { } func testGoogleSqlDatabaseInstance_setServerCertRotationMode(databaseName, rotationMode string) string { - return fmt.Sprintf(` + return fmt.Sprintf(` resource "google_sql_database_instance" "instance" { name = "%s" region = "us-central1" @@ -6713,7 +6874,7 @@ resource "google_sql_database_instance" "original-replica" { type ReadPoolConfig struct { DatabaseType string - ReplicaName string + ReplicaName string // InstanceType specifies the instance type of the replica, // defaulting to READ_POOL_INSTANCE. // @@ -6721,19 +6882,19 @@ type ReadPoolConfig struct { // READ_REPLICA_INSTANCE to create an ordinary read replica in order // to test enable/disable pool scenarios. InstanceType string - NodeCount int64 + NodeCount int64 // ReplicaMachineType gives the machine type of the read pool nodes // or read replica. It defaults to db-perf-optimized-N-2. ReplicaMachineType string // AutoScaleEnabled indicates if auto scaling should be enabled on // the read pool. AutoScaleEnabled bool - MinNodeCount int64 - MaxNodeCount int64 + MinNodeCount int64 + MaxNodeCount int64 } func testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName string, rpconfig ReadPoolConfig) string { - nodeCountStr := "" + nodeCountStr := "" if rpconfig.NodeCount > 0 { nodeCountStr = fmt.Sprintf(` node_count = %d `, rpconfig.NodeCount) @@ -6785,7 +6946,7 @@ func testGoogleSqlDatabaseInstanceConfig_eplusWithReadPool(project, primaryName read_pool_auto_scale_config { enabled = false } -` ) +`) } return fmt.Sprintf(` @@ -7055,7 +7216,6 @@ func verifyCreateOperationOnEplusWithPrivateNetwork(resourceName string) func(*t } } - func verifyPscAutoConnectionsOperation(resourceName string, isPscConfigExpected bool, expectedPscEnabled bool, isPscAutoConnectionConfigExpected bool, expectedConsumerNetwork string, expectedConsumerProject string) func(*terraform.State) error { return func(s *terraform.State) error { resource, ok := s.RootModule().Resources[resourceName] @@ -7103,7 +7263,7 @@ func verifyPscAutoConnectionsOperation(resourceName string, isPscConfigExpected } } -func verifyPscNetorkAttachmentOperation(resourceName string, isPscConfigExpected bool, expectedPscEnabled bool, expectedNetworkAttachmentUri string ) func(*terraform.State) error { +func verifyPscNetorkAttachmentOperation(resourceName string, isPscConfigExpected bool, expectedPscEnabled bool, expectedNetworkAttachmentUri string) func(*terraform.State) error { return func(s *terraform.State) error { resource, ok := s.RootModule().Resources[resourceName] if !ok { @@ -7763,13 +7923,10 @@ resource "google_sql_database_instance" "instance" { } ` -{{- if ne $.TargetVersionName "ga" }} func testGoogleSqlDatabaseInstance_hyperdisk_default(databaseName string) string { return fmt.Sprintf(` resource "google_sql_database_instance" "instance" { - provider = google-beta - name = "%s" region = "us-east1" database_version = "POSTGRES_17" @@ -7786,7 +7943,6 @@ func testGoogleSqlDatabaseInstance_hyperdisk(databaseName string, iops, throughp return fmt.Sprintf(` resource "google_sql_database_instance" "instance" { - provider = google-beta name = "%s" region = "us-east1" @@ -7801,7 +7957,6 @@ resource "google_sql_database_instance" "instance" { } }`, databaseName, iops, throughput) } -{{- end }} var testGoogleSqlDatabaseInstance_maintenance = ` resource "google_sql_database_instance" "instance" { @@ -7953,7 +8108,7 @@ resource "google_sql_database_instance" "instance" { ` func testGoogleSqlDatabaseInstance_insights_enhanced_postgres17(instanceName string, enhanced bool) string { - return fmt.Sprintf(`resource "google_sql_database_instance" "instance" { + return fmt.Sprintf(`resource "google_sql_database_instance" "instance" { name = "%s" region = "us-central1" database_version = "POSTGRES_17" @@ -7974,6 +8129,7 @@ func testGoogleSqlDatabaseInstance_insights_enhanced_postgres17(instanceName str } `, instanceName, enhanced) } + var testGoogleSqlDatabaseInstance_encryptionKey = ` data "google_project" "project" { project_id = "%{project_id}" @@ -9510,4 +9666,4 @@ func testGoogleSqlDatabaseInstanceCheckNodeCount(t *testing.T, instance string, return nil } -} \ No newline at end of file +} diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_provision_script_test.go b/mmv1/third_party/terraform/services/sql/resource_sql_provision_script_test.go index 4c6f72a20f5f..d1c72bb0bbbc 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_provision_script_test.go +++ b/mmv1/third_party/terraform/services/sql/resource_sql_provision_script_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/sql" ) func TestAccSqlProvisionScriptMySql(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert.go b/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert.go index 51ddd1377d5f..6b8271c11cb9 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert.go +++ b/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert.go @@ -18,6 +18,7 @@ func ResourceSqlSslCert() *schema.Resource { return &schema.Resource{ Create: resourceSqlSslCertCreate, Read: resourceSqlSslCertRead, + Update: resourceSqlSslCertUpdate, Delete: resourceSqlSslCertDelete, SchemaVersion: 1, @@ -29,6 +30,7 @@ func ResourceSqlSslCert() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -98,6 +100,9 @@ func ResourceSqlSslCert() *schema.Resource { Computed: true, Description: `The SHA1 Fingerprint of the certificate.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -207,10 +212,30 @@ func resourceSqlSslCertRead(d *schema.ResourceData, meta interface{}) error { } d.SetId(fmt.Sprintf("projects/%s/instances/%s/sslCerts/%s", project, instance, fingerprint)) + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } +// UDP update start +func resourceSqlSslCertUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceSqlSslCertRead(d, meta) +} + +//UDP update end + func resourceSqlSslCertDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert_meta.yaml b/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert_meta.yaml index 1b7a6a0e2b54..1fa6abed58a7 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert_meta.yaml +++ b/mmv1/third_party/terraform/services/sql/resource_sql_ssl_cert_meta.yaml @@ -14,3 +14,5 @@ fields: - field: 'project' - field: 'server_ca_cert' - api_field: 'sha1Fingerprint' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_user.go b/mmv1/third_party/terraform/services/sql/resource_sql_user.go index a274951b71a9..af6495642993 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_user.go +++ b/mmv1/third_party/terraform/services/sql/resource_sql_user.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" sqladmin "google.golang.org/api/sqladmin/v1beta4" ) @@ -61,6 +60,7 @@ func ResourceSqlUser() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), SchemaVersion: 1, @@ -200,14 +200,9 @@ func ResourceSqlUser() *schema.Resource { Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`, }, - "deletion_policy": { - Type: schema.TypeString, - Optional: true, - Description: `The deletion policy for the user. Setting ABANDON allows the resource - to be abandoned rather than deleted. This is useful for Postgres, where users cannot be deleted from the API if they - have been granted SQL roles. Possible values are: "ABANDON".`, - ValidateFunc: validation.StringInSlice([]string{"ABANDON", ""}, false), - }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end "database_roles": { Type: schema.TypeList, Optional: true, @@ -448,6 +443,11 @@ func resourceSqlUserRead(d *schema.ResourceData, meta interface{}) error { } d.SetId(fmt.Sprintf("%s/%s/%s", user.Name, user.Host, user.Instance)) + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } @@ -491,6 +491,11 @@ func flattenPasswordStatus(status *sqladmin.PasswordStatus) interface{} { } func resourceSqlUserUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceSqlUser) { + return ResourceSqlUser().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -574,9 +579,9 @@ func resourceSqlUserUpdate(d *schema.ResourceData, meta interface{}) error { func resourceSqlUserDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - if deletionPolicy := d.Get("deletion_policy"); deletionPolicy == "ABANDON" { - // Allows for user to be abandoned without deletion to avoid deletion failing - // for Postgres users in some circumstances due to existing SQL roles + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { return nil } diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_user_meta.yaml b/mmv1/third_party/terraform/services/sql/resource_sql_user_meta.yaml index c385260d1fd7..b5dda22358e4 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_user_meta.yaml +++ b/mmv1/third_party/terraform/services/sql/resource_sql_user_meta.yaml @@ -5,6 +5,7 @@ api_version: 'v1beta4' api_resource_type_kind: 'User' fields: - field: 'deletion_policy' + provider_only: true - api_field: 'host' - api_field: 'instance' - api_field: 'name' diff --git a/mmv1/third_party/terraform/services/sql/resource_sql_user_test.go b/mmv1/third_party/terraform/services/sql/resource_sql_user_test.go index 1a866a17946c..23f15bbda041 100644 --- a/mmv1/third_party/terraform/services/sql/resource_sql_user_test.go +++ b/mmv1/third_party/terraform/services/sql/resource_sql_user_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/sql" ) diff --git a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object.go b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object.go index 24403c3e8ccc..3edc07bc3c1c 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object.go +++ b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object.go @@ -42,7 +42,7 @@ func dataSourceGoogleStorageBucketObjectRead(d *schema.ResourceData, meta interf name = url.QueryEscape(name) } // Using REST apis because the storage go client doesn't support folders - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{StorageBasePath}}b/%s/o/%s", bucket, name)) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"b/%s/o/%s", bucket, name)) if err != nil { return fmt.Errorf("Error formatting url for storage bucket object: %s", err) } diff --git a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object_test.go b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object_test.go index 64da62288c3f..6678d4ba5be8 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_object_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceGoogleStorageBucketObject_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects.go b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects.go index e6159da60813..2552881b679a 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects.go +++ b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects.go @@ -69,7 +69,7 @@ func datasourceGoogleStorageBucketObjectsRead(d *schema.ResourceData, meta inter for { bucket := d.Get("bucket").(string) - url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf("{{StorageBasePath}}b/%s/o", bucket)) + url, err := tpgresource.ReplaceVars(d, config, fmt.Sprintf(transport_tpg.BaseUrl(Product, config)+"b/%s/o", bucket)) if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects_test.go b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects_test.go index 7d83a4026ddb..8196758b104a 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_objects_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceGoogleStorageBucketObjects_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_test.go b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_test.go index 333c04f3bb86..51e31d99442f 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_google_storage_bucket_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceGoogleStorageBucket_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/data_source_google_storage_buckets_test.go b/mmv1/third_party/terraform/services/storage/data_source_google_storage_buckets_test.go index 93900df08276..da7bb49cf792 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_google_storage_buckets_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_google_storage_buckets_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceGoogleStorageBuckets_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_content_test.go b/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_content_test.go index 07dd90d84dad..9777ea85d1b8 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_content_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_content_test.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceStorageBucketObjectContent_Basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_contents_test.go b/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_contents_test.go index b5474c39e7a5..f13b73e1786b 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_contents_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_storage_bucket_object_contents_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccDataSourceStorageBucketObjectContents_Basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/data_source_storage_object_signed_url_test.go b/mmv1/third_party/terraform/services/storage/data_source_storage_object_signed_url_test.go index 1745584e3c76..335120f90284 100644 --- a/mmv1/third_party/terraform/services/storage/data_source_storage_object_signed_url_test.go +++ b/mmv1/third_party/terraform/services/storage/data_source_storage_object_signed_url_test.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) const objectPath = "object/objname" diff --git a/mmv1/third_party/terraform/services/storage/iam_storage_bucket.go b/mmv1/third_party/terraform/services/storage/iam_storage_bucket.go index 6399417aada6..de14fccf3e1b 100644 --- a/mmv1/third_party/terraform/services/storage/iam_storage_bucket.go +++ b/mmv1/third_party/terraform/services/storage/iam_storage_bucket.go @@ -162,7 +162,7 @@ func (u *StorageBucketIamUpdater) SetResourceIamPolicy(policy *cloudresourcemana } func (u *StorageBucketIamUpdater) qualifyBucketUrl(methodIdentifier string) (string, error) { - urlTemplate := fmt.Sprintf("{{StorageBasePath}}%s/%s", fmt.Sprintf("b/%s", u.bucket), methodIdentifier) + urlTemplate := fmt.Sprintf(transport_tpg.BaseUrl(Product, u.Config)+"%s/%s", fmt.Sprintf("b/%s", u.bucket), methodIdentifier) url, err := tpgresource.ReplaceVars(u.d, u.Config, urlTemplate) if err != nil { return "", err diff --git a/mmv1/third_party/terraform/services/storage/iam_storage_bucket_test.go b/mmv1/third_party/terraform/services/storage/iam_storage_bucket_test.go index a6959c21fd73..6d48ce49f0b4 100644 --- a/mmv1/third_party/terraform/services/storage/iam_storage_bucket_test.go +++ b/mmv1/third_party/terraform/services/storage/iam_storage_bucket_test.go @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder.go b/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder.go index 2ccf46942f31..8b7a3ae0d29c 100644 --- a/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder.go +++ b/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder.go @@ -164,7 +164,7 @@ func (u *StorageManagedFolderIamUpdater) SetResourceIamPolicy(policy *cloudresou } func (u *StorageManagedFolderIamUpdater) qualifyManagedFolderUrl(methodIdentifier string) (string, error) { - urlTemplate := fmt.Sprintf("{{StorageBasePath}}b/%s/managedFolders/%s/%s", u.bucket, url.PathEscape(u.managedFolder), methodIdentifier) + urlTemplate := fmt.Sprintf(transport_tpg.BaseUrl(Product, u.Config)+"b/%s/managedFolders/%s/%s", u.bucket, url.PathEscape(u.managedFolder), methodIdentifier) url, err := tpgresource.ReplaceVars(u.d, u.Config, urlTemplate) if err != nil { return "", err diff --git a/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder_test.go b/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder_test.go index 98f1628a9881..4f2e996ef82f 100644 --- a/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder_test.go +++ b/mmv1/third_party/terraform/services/storage/iam_storage_managed_folder_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/tpgresource" ) diff --git a/mmv1/third_party/terraform/services/storage/list_google_storage_bucket.go.tmpl b/mmv1/third_party/terraform/services/storage/list_google_storage_bucket.go.tmpl new file mode 100644 index 000000000000..138e158bad10 --- /dev/null +++ b/mmv1/third_party/terraform/services/storage/list_google_storage_bucket.go.tmpl @@ -0,0 +1,152 @@ +// Copyright (c) IBM Corp. 2014, 2026 +// SPDX-License-Identifier: MPL-2.0 + +package storage + +import ( + "context" + "errors" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/list" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "google.golang.org/api/storage/v1" + + "github.com/hashicorp/terraform-provider-google/google/registry" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func init() { + registry.FrameworkListResource{ + Name: "google_storage_bucket", + ProductName: "storage", + Func: NewGoogleStorageBucketListResource, + }.Register() +} + + +type GoogleStorageBucketListResource struct { + tpgresource.ListResourceMetadata +} + +type GoogleStorageBucketListModel struct { + Project types.String `tfsdk:"project"` +} + +func NewGoogleStorageBucketListResource() list.ListResource { + listR := &GoogleStorageBucketListResource{} + listR.TypeName = "google_storage_bucket" + listR.SDKv2Resource = ResourceStorageBucket() + listR.ListConfigFields = []tpgresource.ListConfigField{ + {Name: "project", Kind: tpgresource.ListConfigKindString, Optional: true}, + } + return listR +} + +func (listR *GoogleStorageBucketListResource) List(ctx context.Context, listReq list.ListRequest, stream *list.ListResultsStream) { + errStorageBucketListStreamClosed := errors.New("stream closed") + + var data GoogleStorageBucketListModel + diags := listReq.Config.Get(ctx, &data) + if diags.HasError() { + stream.Results = list.ListResultsStreamDiagnostics(diags) + return + } + if listR.Client == nil { + diags = append(diags, diag.NewErrorDiagnostic( + "Provider not configured", + "The Google provider client is not available; ensure the provider is configured (e.g. credentials and default project).", + )) + stream.Results = list.ListResultsStreamDiagnostics(diags) + return + } + project := listR.GetProject(data.Project) + + stream.Results = func(push func(list.ListResult) bool) { + err := ListStorageBuckets(listR.Client, project, func(rd *schema.ResourceData) error { + result := listReq.NewListResult(ctx) + + if err := listR.SetResult(ctx, listReq.IncludeResource, &result, rd, "name"); err != nil { + return err + } + + if !push(result) { + return errStorageBucketListStreamClosed + } + return nil + }) + if err != nil { + if errors.Is(err, errStorageBucketListStreamClosed) { + return + } + diags.AddError("API Error", err.Error()) + result := listReq.NewListResult(ctx) + result.Diagnostics = diags + push(result) + } + } +} + +func flattenStorageBucketListItem(res map[string]interface{}, d *schema.ResourceData, config *transport_tpg.Config) error { + var bucket storage.Bucket + if err := tpgresource.Convert(res, &bucket); err != nil { + return fmt.Errorf("error converting storage bucket list response: %w", err) + } + if bucket.Name == "" { + return fmt.Errorf("missing name in storage bucket list response") + } + if err := d.Set("name", bucket.Name); err != nil { + return err + } + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + return setStorageBucket(d, config, &bucket, bucket.Name, userAgent) +} + +func ListStorageBuckets(config *transport_tpg.Config, project string, callback func(rd *schema.ResourceData) error) error { + if config == nil { + return fmt.Errorf("provider client is not configured") + } + d := ResourceStorageBucket().Data(&terraform.InstanceState{}) + + if project != "" { + if err := d.Set("project", project); err != nil { + return fmt.Errorf("error setting project on temporary resource data: %w", err) + } + } + url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}StorageBasePath{{"}}"}}b?project={{"{{"}}project{{"}}"}}") + if err != nil { + return err + } + + billingProject := "" + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + return transport_tpg.ListPages(transport_tpg.ListPagesOptions{ + Config: config, + TempData: d, + Resource: ResourceStorageBucket(), + ListURL: url, + BillingProject: billingProject, + UserAgent: userAgent, + Flattener: flattenStorageBucketListItem, + Callback: callback, + }) +} + + + diff --git a/mmv1/third_party/terraform/services/storage/list_google_storage_bucket_test.go b/mmv1/third_party/terraform/services/storage/list_google_storage_bucket_test.go new file mode 100644 index 000000000000..2f92e5530daf --- /dev/null +++ b/mmv1/third_party/terraform/services/storage/list_google_storage_bucket_test.go @@ -0,0 +1,104 @@ +// Copyright (c) IBM Corp. 2014, 2026 +// SPDX-License-Identifier: MPL-2.0 + +package storage_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/querycheck" + "github.com/hashicorp/terraform-plugin-testing/querycheck/queryfilter" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/hashicorp/terraform-plugin-testing/tfversion" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" +) + +func TestAccStorageBucketListResource_queryIdentity(t *testing.T) { + t.Parallel() + + project := envvar.GetTestProjectFromEnv() + bucketName := "tf-test-" + acctest.RandString(t, 10) + + acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.SkipBelow(tfversion.Version1_14_0), + }, + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + Steps: []resource.TestStep{ + { + Config: testAccStorageBucketBasic(bucketName, project), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("google_storage_bucket.test", "project", project), + resource.TestCheckResourceAttr("google_storage_bucket.test", "name", bucketName), + ), + }, + { + Query: true, + Config: testAccStorageBucketListQuery(project, true), + QueryResultChecks: []querycheck.QueryResultCheck{ + querycheck.ExpectIdentity("google_storage_bucket.all_in_project", map[string]knownvalue.Check{ + "name": knownvalue.StringExact(bucketName), + "project": knownvalue.StringExact(project), + }), + querycheck.ExpectLengthAtLeast("google_storage_bucket.all_in_project", 1), + querycheck.ExpectResourceKnownValues( + "google_storage_bucket.all_in_project", + queryfilter.ByDisplayName(knownvalue.StringExact(bucketName)), + []querycheck.KnownValueCheck{ + { + Path: tfjsonpath.New("name"), + KnownValue: knownvalue.StringExact(bucketName), + }, + { + Path: tfjsonpath.New("project"), + KnownValue: knownvalue.StringExact(project), + }, + { + Path: tfjsonpath.New("location"), + KnownValue: knownvalue.StringExact("US"), + }, + }, + ), + }, + }, + }, + }) +} + +func testAccStorageBucketBasic(name, project string) string { + return fmt.Sprintf(` +resource "google_storage_bucket" "test" { + name = %q + location = "US" + project = %q +} +`, name, project) +} + +func testAccStorageBucketListQuery(project string, includeResource bool) string { + includeResourceBlock := "" + if includeResource { + includeResourceBlock = " include_resource = true" + } + + return fmt.Sprintf(` +provider "google" {} + +list "google_storage_bucket" "all_in_project" { + provider = google +%s + limit = 1000 + + config { + project = %q + } +} +`, includeResourceBlock, project) +} diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_anywhere_cache_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_anywhere_cache_test.go index 7182e1e13a64..ede31a228673 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_anywhere_cache_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_anywhere_cache_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccStorageAnywhereCache_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket.go.tmpl b/mmv1/third_party/terraform/services/storage/resource_storage_bucket.go.tmpl index 00520e61c489..d31c58667b19 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket.go.tmpl +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket.go.tmpl @@ -64,8 +64,25 @@ func ResourceStorageBucket() *schema.Resource { CustomizeDiff: customdiff.All( customdiff.ForceNewIfChange("retention_policy.0.is_locked", isPolicyLocked), tpgresource.SetLabelsDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), + Identity: &schema.ResourceIdentity{ + Version: 1, + SchemaFunc: func() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "project": { + Type: schema.TypeString, + OptionalForImport: true, + }, + "name": { + Type: schema.TypeString, + RequiredForImport: true, + }, + } + }, + }, + Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(10 * time.Minute), Update: schema.DefaultTimeout(4 * time.Minute), @@ -694,7 +711,10 @@ func ResourceStorageBucket() *schema.Resource { } return false }, - }, + }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -721,7 +741,7 @@ func labelKeyValidator(val interface{}, key string) (warns []string, errs []erro func getAnywhereCacheListResult(d *schema.ResourceData, config *transport_tpg.Config) ([]interface{}, error) { // Define the cache list URL - cacheListUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{StorageBasePath}}b/{{name}}/anywhereCaches/"}}") + cacheListUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"b/{{name}}/anywhereCaches/"}}") if err != nil { return nil, err } @@ -786,7 +806,7 @@ func deleteAnywhereCacheIfAny(d *schema.ResourceData, config *transport_tpg.Conf if !ok { return fmt.Errorf("missing or invalid anywhereCacheId: %v", obj) } - anywhereCacheUrl, err := tpgresource.ReplaceVars(d, config, "{{"{{StorageBasePath}}b/{{name}}/anywhereCaches/"}}") + anywhereCacheUrl, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{"b/{{name}}/anywhereCaches/"}}") if err != nil { return err } @@ -1007,6 +1027,11 @@ func resourceStorageBucketCreate(d *schema.ResourceData, meta interface{}) error } func resourceStorageBucketUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceStorageBucket) { + return ResourceStorageBucket().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1208,6 +1233,13 @@ func resourceStorageBucketRead(d *schema.ResourceData, meta interface{}) error { } func resourceStorageBucketDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1349,6 +1381,35 @@ func resourceStorageBucketDelete(d *schema.ResourceData, meta interface{}) error } func resourceStorageBucketStateImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + if d.Id() == "" { + identity, err := d.Identity() + if err != nil { + return nil, fmt.Errorf("Error reading import identity: %s", err) + } + if identity == nil { + return nil, fmt.Errorf("import requires bucket name") + } + + nameValue, ok := identity.GetOk("name") + if !ok || nameValue.(string) == "" { + return nil, fmt.Errorf("import requires bucket name") + } + + name := nameValue.(string) + if err := d.Set("name", name); err != nil { + return nil, fmt.Errorf("Error setting name: %s", err) + } + + if projectValue, ok := identity.GetOk("project"); ok && projectValue.(string) != "" { + if err := d.Set("project", projectValue.(string)); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + d.SetId(fmt.Sprintf("%s/%s", projectValue.(string), name)) + } else { + d.SetId(name) + } + } + // We need to support project/bucket_name and bucket_name formats. This will allow // importing a bucket that is in a different project than the provider default. // ParseImportID can't be used because having no project will cause an error but it @@ -2443,12 +2504,12 @@ func setStorageBucket(d *schema.ResourceData, config *transport_tpg.Config, res if err := tpgresource.SetLabels(res.Labels, d, "labels"); err != nil { return fmt.Errorf("Error setting labels: %s", err) } - if err := tpgresource.SetLabels(res.Labels, d, "terraform_labels"); err != nil { - return fmt.Errorf("Error setting terraform_labels: %s", err) - } if err := d.Set("effective_labels", res.Labels); err != nil { return fmt.Errorf("Error setting labels: %s", err) } + if err := tpgresource.SetLabels(res.Labels, d, "terraform_labels"); err != nil { + return fmt.Errorf("Error setting terraform_labels: %s", err) + } if err := d.Set("website", flattenBucketWebsite(res.Website)); err != nil { return fmt.Errorf("Error setting website: %s", err) } @@ -2506,9 +2567,18 @@ func setStorageBucket(d *schema.ResourceData, config *transport_tpg.Config, res if err := d.Set("ip_filter", flattenBucketIpFilter(res.IpFilter)); err != nil { return fmt.Errorf("Error setting ip_filter: %s", err) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + d.SetId(res.Id) - return nil + + return tpgresource.SetResourceIdentityAttributes(d, map[string]interface{}{ + "name": res.Name, + "project": d.Get("project").(string), +}) } func hierachicalNamespaceDiffSuppress(k, old, new string, r *schema.ResourceData) bool { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_access_control_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_access_control_test.go index 31c52b69c807..0bf7ba83b6db 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_access_control_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_access_control_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccStorageBucketAccessControl_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl.go b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl.go index 74bf6a8e7dce..ea5dad331e4d 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/api/storage/v1" @@ -18,11 +19,14 @@ import ( func ResourceStorageBucketAcl() *schema.Resource { return &schema.Resource{ - Create: resourceStorageBucketAclCreate, - Read: resourceStorageBucketAclRead, - Update: resourceStorageBucketAclUpdate, - Delete: resourceStorageBucketAclDelete, - CustomizeDiff: resourceStorageRoleEntityCustomizeDiff, + Create: resourceStorageBucketAclCreate, + Read: resourceStorageBucketAclRead, + Update: resourceStorageBucketAclUpdate, + Delete: resourceStorageBucketAclDelete, + CustomizeDiff: customdiff.All( + resourceStorageRoleEntityCustomizeDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), Schema: map[string]*schema.Schema{ "bucket": { @@ -54,6 +58,9 @@ func ResourceStorageBucketAcl() *schema.Resource { ConflictsWith: []string{"predefined_acl"}, Description: `List of role/entity pairs in the form ROLE:entity. See GCS Bucket ACL documentation for more details. Must be set if predefined_acl is not.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -275,10 +282,19 @@ func resourceStorageBucketAclRead(d *schema.ResourceData, meta interface{}) erro } } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceStorageBucketAclUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceStorageBucketAcl) { + return ResourceStorageBucketAcl().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -375,6 +391,13 @@ func resourceStorageBucketAclUpdate(d *schema.ResourceData, meta interface{}) er } func resourceStorageBucketAclDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl_meta.yaml b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl_meta.yaml index 3e08e3339b17..99dafdb21743 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl_meta.yaml +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_acl_meta.yaml @@ -8,3 +8,5 @@ fields: - field: 'default_acl' - field: 'predefined_acl' - field: 'role_entity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_iam_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_iam_test.go index f9c4aebf636e..341b172665b6 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_iam_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_iam_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccStorageBucketIamPolicy(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_meta.yaml b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_meta.yaml index 0a98e679de75..2f07fab941d6 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_meta.yaml +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_meta.yaml @@ -98,3 +98,5 @@ fields: - api_field: 'versioning.enabled' - api_field: 'website.mainPageSuffix' - api_field: 'website.notFoundPage' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object.go b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object.go index a22afa858f8e..e11dde705af3 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "crypto/sha256" "encoding/base64" @@ -36,6 +35,7 @@ func ResourceStorageBucketObject() *schema.Resource { CustomizeDiff: customdiff.All( resourceStorageBucketObjectCustomizeDiff, validateContexts, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Timeouts: &schema.ResourceTimeout{ @@ -352,12 +352,9 @@ func ResourceStorageBucketObject() *schema.Resource { Description: `A url reference to download this object.`, }, - "deletion_policy": { - Type: schema.TypeString, - Optional: true, - Description: `The deletion policy for the object. Setting ABANDON allows the resource to be abandoned rather than deleted when removed from your Terraform configuration.`, - ValidateFunc: validation.StringInSlice([]string{"ABANDON"}, false), - }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -465,6 +462,11 @@ func resourceStorageBucketObjectCreate(d *schema.ResourceData, meta interface{}) } func resourceStorageBucketObjectUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceStorageBucketObject) { + return ResourceStorageBucketObject().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -622,12 +624,23 @@ func resourceStorageBucketObjectRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error reading Contexts: %s", err) } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + d.SetId(objectGetID(res)) return nil } func resourceStorageBucketObjectDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object_test.go index 2e2cdf3e82ec..074b49df28ee 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_object_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" storage_tpg "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -320,7 +321,7 @@ func TestAccStorageObject_metadata(t *testing.T) { func TestAccStorageObjectKms(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKeyInLocation(t, "us") + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us") bucketName := acctest.TestBucketName(t) data := []byte("data data data") dataCrc32c := calculateCrc32cHash(data) @@ -335,7 +336,7 @@ func TestAccStorageObjectKms(t *testing.T) { CheckDestroy: testAccStorageObjectDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testGoogleStorageBucketsObjectKms(bucketName, testFile.Name(), kms.CryptoKey.Name), + Config: testGoogleStorageBucketsObjectKms(bucketName, testFile.Name(), bootstrapped.CryptoKey.Name), Check: testAccCheckGoogleStorageObjectCrc32cHash(t, bucketName, objectName, dataCrc32c), }, }, diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_test.go index f66bee491406..bc6f1ae85ea1 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_bucket_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_bucket_test.go @@ -13,9 +13,13 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-plugin-testing/tfversion" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" storage_tpg "github.com/hashicorp/terraform-provider-google/google/services/storage" "google.golang.org/api/googleapi" @@ -66,6 +70,39 @@ func TestAccStorageBucket_basic(t *testing.T) { }) } +func TestAccStorageBucket_importBlockWithResourceIdentity(t *testing.T) { + t.Parallel() + + bucketName := acctest.TestBucketName(t) + project := envvar.GetTestProjectFromEnv() + + acctest.VcrTest(t, resource.TestCase{ + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.SkipBelow(tfversion.Version1_12_0), + }, + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccStorageBucketDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccStorageBucket_basic(bucketName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "google_storage_bucket.bucket", "project", project), + resource.TestCheckResourceAttr( + "google_storage_bucket.bucket", "name", bucketName), + ), + }, + { + ResourceName: "google_storage_bucket.bucket", + RefreshState: true, + ExpectNonEmptyPlan: true, + ImportStateKind: resource.ImportBlockWithResourceIdentity, + }, + }, + }) +} + func TestAccStorageBucket_basicWithAutoclass(t *testing.T) { t.Parallel() @@ -3162,7 +3199,7 @@ func TestAccStorageBucket_encryptionCmek(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "kms_key": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "kms_key": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "random_int": acctest.RandInt(t), } diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_default_object_access_control_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_default_object_access_control_test.go index e3487e2686fd..4e10ca4d4610 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_default_object_access_control_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_default_object_access_control_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccStorageDefaultObjectAccessControl_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl.go b/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl.go index 31c8cc817338..896d703b2f09 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl.go @@ -3,6 +3,7 @@ package storage import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-google/google/registry" "github.com/hashicorp/terraform-provider-google/google/tpgresource" @@ -17,6 +18,10 @@ func ResourceStorageDefaultObjectAcl() *schema.Resource { Update: resourceStorageDefaultObjectAclCreateUpdate, Delete: resourceStorageDefaultObjectAclDelete, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "bucket": { Type: schema.TypeString, @@ -33,12 +38,21 @@ func ResourceStorageDefaultObjectAcl() *schema.Resource { ValidateFunc: validateRoleEntityPair, }, }, + + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } } func resourceStorageDefaultObjectAclCreateUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceStorageDefaultObjectAcl) { + return ResourceStorageDefaultObjectAcl().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -109,11 +123,22 @@ func resourceStorageDefaultObjectAclRead(d *schema.ResourceData, meta interface{ return err } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + d.SetId(bucket) return nil } func resourceStorageDefaultObjectAclDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl_meta.yaml b/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl_meta.yaml index a76369719824..97ea8b93f09d 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl_meta.yaml +++ b/mmv1/third_party/terraform/services/storage/resource_storage_default_object_acl_meta.yaml @@ -6,3 +6,5 @@ api_resource_type_kind: 'ObjectAccessControl' fields: - field: 'bucket' - field: 'role_entity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_hmac_key_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_hmac_key_test.go index 07652a858262..60387cab8b14 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_hmac_key_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_hmac_key_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccStorageHmacKey_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_managed_folder_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_managed_folder_test.go index 78e492309e5a..61c673d650a5 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_managed_folder_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_managed_folder_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" ) func TestAccStorageManagedFolder_storageManagedFolderUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_notification_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_notification_test.go index 74848ad4410b..8242e0eaef98 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_notification_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_notification_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" tpgstorage "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_object_access_control_test.go b/mmv1/third_party/terraform/services/storage/resource_storage_object_access_control_test.go index 953c81b41e83..9018c9926fb6 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_object_access_control_test.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_object_access_control_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_object_acl.go b/mmv1/third_party/terraform/services/storage/resource_storage_object_acl.go index 4dcba4c4fe1b..ac233431fb9c 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_object_acl.go +++ b/mmv1/third_party/terraform/services/storage/resource_storage_object_acl.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "google.golang.org/api/storage/v1" @@ -16,11 +17,14 @@ import ( func ResourceStorageObjectAcl() *schema.Resource { return &schema.Resource{ - Create: resourceStorageObjectAclCreate, - Read: resourceStorageObjectAclRead, - Update: resourceStorageObjectAclUpdate, - Delete: resourceStorageObjectAclDelete, - CustomizeDiff: resourceStorageObjectAclDiff, + Create: resourceStorageObjectAclCreate, + Read: resourceStorageObjectAclRead, + Update: resourceStorageObjectAclUpdate, + Delete: resourceStorageObjectAclDelete, + CustomizeDiff: customdiff.All( + resourceStorageObjectAclDiff, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), Schema: map[string]*schema.Schema{ "bucket": { @@ -52,6 +56,10 @@ func ResourceStorageObjectAcl() *schema.Resource { }, ConflictsWith: []string{"predefined_acl"}, }, + + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -198,11 +206,20 @@ func resourceStorageObjectAclRead(d *schema.ResourceData, meta interface{}) erro return err } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + d.SetId(getObjectAclId(object)) return nil } func resourceStorageObjectAclUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceStorageObjectAcl) { + return ResourceStorageObjectAcl().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -261,6 +278,13 @@ func resourceStorageObjectAclUpdate(d *schema.ResourceData, meta interface{}) er } func resourceStorageObjectAclDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/storage/resource_storage_object_acl_meta.yaml b/mmv1/third_party/terraform/services/storage/resource_storage_object_acl_meta.yaml index 1571519d6ef1..286b57efcc4a 100644 --- a/mmv1/third_party/terraform/services/storage/resource_storage_object_acl_meta.yaml +++ b/mmv1/third_party/terraform/services/storage/resource_storage_object_acl_meta.yaml @@ -8,3 +8,5 @@ fields: - field: 'object' - field: 'predefined_acl' - field: 'role_entity' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/storagebatchoperations/resource_storage_batch_operations_job_test.go b/mmv1/third_party/terraform/services/storagebatchoperations/resource_storage_batch_operations_job_test.go index 9ef158b8216c..0be2cc862303 100644 --- a/mmv1/third_party/terraform/services/storagebatchoperations/resource_storage_batch_operations_job_test.go +++ b/mmv1/third_party/terraform/services/storagebatchoperations/resource_storage_batch_operations_job_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagebatchoperations" ) func TestAccStorageBatchOperationsJobs_createJobWithPrefix(t *testing.T) { @@ -127,7 +130,7 @@ func TestAccStorageBatchOperationsJobs_batchOperationJobKmsKey(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "kms_key": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "kms_key": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, "job_id": fmt.Sprintf("tf-test-job-%d", acctest.RandInt(t)), "object_name": fmt.Sprintf("tf-test-object-%d", acctest.RandInt(t)), "bucket_name": acctest.TestBucketName(t), diff --git a/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_folder_intelligence_config_test.go b/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_folder_intelligence_config_test.go index eab96be75f2e..6603a7a209db 100644 --- a/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_folder_intelligence_config_test.go +++ b/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_folder_intelligence_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagecontrol" ) func TestAccDataSourceGoogleStorageControlFolderIntelligenceConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_organizaton_intelligence_config_test.go b/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_organizaton_intelligence_config_test.go index 2205bf6d646b..bad938c7bbfa 100644 --- a/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_organizaton_intelligence_config_test.go +++ b/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_organizaton_intelligence_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagecontrol" ) func TestAccDataSourceGoogleStorageControlOrganizationIntelligenceConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_project_intelligence_config_test.go b/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_project_intelligence_config_test.go index 2cc23c42aaec..f869074d8287 100644 --- a/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_project_intelligence_config_test.go +++ b/mmv1/third_party/terraform/services/storagecontrol/data_source_storage_control_project_intelligence_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagecontrol" ) func TestAccDataSourceGoogleStorageControlProjectIntelligenceConfig_basic(t *testing.T) { @@ -13,7 +15,7 @@ func TestAccDataSourceGoogleStorageControlProjectIntelligenceConfig_basic(t *tes context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "project": acctest.BootstrapProject(t, "tf-boot-stor-int-", envvar.GetTestBillingAccountFromEnv(t), []string{"storage.googleapis.com"}).ProjectId, + "project": resourcemanager.BootstrapProject(t, "tf-boot-stor-int-", envvar.GetTestBillingAccountFromEnv(t), []string{"storage.googleapis.com"}).ProjectId, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_folder_intelligence_config_test.go b/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_folder_intelligence_config_test.go index 1ca470f732de..258616615043 100644 --- a/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_folder_intelligence_config_test.go +++ b/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_folder_intelligence_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagecontrol" ) func TestAccStorageControlFolderIntelligenceConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_organization_intelligence_config_test.go b/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_organization_intelligence_config_test.go index 85691914f47b..2110b3251f58 100644 --- a/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_organization_intelligence_config_test.go +++ b/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_organization_intelligence_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagecontrol" ) func TestAccStorageControlOrganizationIntelligenceConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_project_intelligence_config_test.go b/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_project_intelligence_config_test.go index c0ebc73c9fd4..ea9039763df8 100644 --- a/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_project_intelligence_config_test.go +++ b/mmv1/third_party/terraform/services/storagecontrol/resource_storage_control_project_intelligence_config_test.go @@ -6,13 +6,15 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storagecontrol" ) func TestAccStorageControlProjectIntelligenceConfig_update(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "project": acctest.BootstrapProject(t, "tf-boot-stor-int-", envvar.GetTestBillingAccountFromEnv(t), []string{"storage.googleapis.com"}).ProjectId, + "project": resourcemanager.BootstrapProject(t, "tf-boot-stor-int-", envvar.GetTestBillingAccountFromEnv(t), []string{"storage.googleapis.com"}).ProjectId, "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_dataset_config_test.go b/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_dataset_config_test.go index 8928eef23d83..58383801244f 100644 --- a/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_dataset_config_test.go +++ b/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_dataset_config_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storageinsights" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_report_config_test.go b/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_report_config_test.go index ff643d1d9bc8..890fdb7485f8 100644 --- a/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_report_config_test.go +++ b/mmv1/third_party/terraform/services/storageinsights/resource_storage_insights_report_config_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/storageinsights" ) func TestAccStorageInsightsReportConfig_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_agent_pool_test.go b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_agent_pool_test.go index d3fe9f0ea67f..17a9585819c1 100644 --- a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_agent_pool_test.go +++ b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_agent_pool_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/storagetransfer" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -174,7 +176,7 @@ func testAccCheckStorageTransferAgentPoolDestroyProducer(t *testing.T) func(s *t config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{StorageTransferBasePath}}projects/{{project}}/agentPools/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(storagetransfer.Product, config)+"projects/{{project}}/agentPools/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job.go b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job.go index 8861c5188f51..b5e0ad7e3a42 100644 --- a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job.go +++ b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job.go @@ -122,6 +122,7 @@ func ResourceStorageTransferJob() *schema.Resource { CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, + tpgresource.DefaultProviderDeletionPolicy("DELETE"), ), Schema: map[string]*schema.Schema{ @@ -442,6 +443,9 @@ func ResourceStorageTransferJob() *schema.Resource { Computed: true, Description: `When the Transfer Job was deleted.`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -1131,10 +1135,19 @@ func resourceStorageTransferJobRead(d *schema.ResourceData, meta interface{}) er return err } + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil { + return err + } + return nil } func resourceStorageTransferJobUpdate(d *schema.ResourceData, meta interface{}) error { + + if tpgresource.DeletionPolicyPreUpdate(d, ResourceStorageTransferJob) { + return ResourceStorageTransferJob().Read(d, meta) + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { @@ -1248,6 +1261,13 @@ func resourceStorageTransferJobUpdate(d *schema.ResourceData, meta interface{}) } func resourceStorageTransferJobDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil { + return err + } else if ok { + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_meta.yaml b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_meta.yaml index 5950abca6af8..9bf9ba4ae234 100644 --- a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_meta.yaml +++ b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_meta.yaml @@ -109,3 +109,5 @@ fields: - api_field: 'transferSpec.transferOptions.metadataOptions.uid' - api_field: 'transferSpec.transferOptions.overwriteObjectsAlreadyExistingInSink' - api_field: 'transferSpec.transferOptions.overwriteWhen' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_test.go b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_test.go index da6f7fc0a7bd..b54c9259a32b 100644 --- a/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_test.go +++ b/mmv1/third_party/terraform/services/storagetransfer/resource_storage_transfer_job_test.go @@ -8,6 +8,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/pubsub" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" "github.com/hashicorp/terraform-provider-google/google/services/storagetransfer" ) @@ -114,7 +117,7 @@ func TestAccStorageTransferJob_updateLoggingConfig(t *testing.T) { func TestAccStorageTransferReplicationJob_basic(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gs-project-accounts.iam.gserviceaccount.com", Role: "roles/pubsub.publisher", @@ -248,7 +251,7 @@ func TestAccStorageTransferJob_omitScheduleEndDate(t *testing.T) { func TestAccStorageTransferJob_posixSource(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:project-{project_number}@storage-transfer-service.iam.gserviceaccount.com", Role: "roles/pubsub.admin", @@ -286,7 +289,7 @@ func TestAccStorageTransferJob_posixSource(t *testing.T) { func TestAccStorageTransferJob_posixSink(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:project-{project_number}@storage-transfer-service.iam.gserviceaccount.com", Role: "roles/pubsub.admin", @@ -544,7 +547,7 @@ func TestAccStorageTransferJob_notificationConfig(t *testing.T) { func TestAccStorageTransferJob_hdfsSource(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:project-{project_number}@storage-transfer-service.iam.gserviceaccount.com", Role: "roles/pubsub.admin", diff --git a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_key_test.go b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_key_test.go index d3ebcd7a90d7..45677f167449 100644 --- a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_key_test.go +++ b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_key_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccDataSourceGoogleTagsTagKey_default(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_keys_test.go b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_keys_test.go index 598260c9cf8d..ba3affa99105 100644 --- a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_keys_test.go +++ b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_keys_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccDataSourceGoogleTagsTagKeys_default(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_value_test.go b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_value_test.go index 4218f28bb2a4..a74c68e36895 100644 --- a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_value_test.go +++ b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_value_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccDataSourceGoogleTagsTagValue_default(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_values_test.go b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_values_test.go index 4f67edb071cc..0d76d3db2bde 100644 --- a/mmv1/third_party/terraform/services/tags/data_source_tags_tag_values_test.go +++ b/mmv1/third_party/terraform/services/tags/data_source_tags_tag_values_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" ) func TestAccDataSourceGoogleTagsTagValues_default(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding.go.tmpl b/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding.go.tmpl index 0bbc4432c47b..ca5b69b76a9b 100644 --- a/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding.go.tmpl +++ b/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding.go.tmpl @@ -13,6 +13,7 @@ import ( transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "google.golang.org/api/googleapi" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -20,6 +21,7 @@ func ResourceTagsLocationTagBinding() *schema.Resource { return &schema.Resource{ Create: resourceTagsLocationTagBindingCreate, Read: resourceTagsLocationTagBindingRead, + Update: resourceTagsLocationTagBindingUpdate, Delete: resourceTagsLocationTagBindingDelete, Importer: &schema.ResourceImporter{ @@ -31,6 +33,10 @@ func ResourceTagsLocationTagBinding() *schema.Resource { Delete: schema.DefaultTimeout(20 * time.Minute), }, + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderDeletionPolicy("DELETE"), + ), + Schema: map[string]*schema.Schema{ "parent": { Type: schema.TypeString, @@ -57,6 +63,9 @@ Examples: US, EU, asia-northeast1. The default value is US.`, Computed: true, Description: `The generated id for the TagBinding. This is a string of the form 'tagBindings/{full-resource-name}/{tag-value-name}' or 'tagBindings/{full-resource-name}/{tag-key-name}'`, }, + //UDP schema start + "deletion_policy": tpgresource.DeletionPolicySchemaEntry("DELETE"), + //UDP schema end }, UseJSONNumber: true, } @@ -272,11 +281,30 @@ func resourceTagsLocationTagBindingRead(d *schema.ResourceData, meta interface{} // Do not change the existing d.Get("tag_value") format to maintain backward compatibility. log.Printf("[DEBUG] Read: Existing tag_value in state: %s.", d.Get("tag_value").(string)) } + + if err := tpgresource.DeletionPolicyReadDefault(d, config, "DELETE"); err != nil{ + return err + } + return nil } +//UDP update start +func resourceTagsLocationTagBindingUpdate(d *schema.ResourceData, meta interface{}) error { + // Only the root field "deletion_policy", "labels", "terraform_labels", and virtual fields are mutable + return resourceTagsLocationTagBindingRead(d, meta) +} +//UDP update end + func resourceTagsLocationTagBindingDelete(d *schema.ResourceData, meta interface{}) error { + + if ok, err := tpgresource.DeletionPolicyPreDelete(d); err != nil{ + return err + }else if ok{ + return nil + } + config := meta.(*transport_tpg.Config) userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { diff --git a/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding_meta.yaml b/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding_meta.yaml index d8466f80dda2..466d99f5a6b3 100644 --- a/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding_meta.yaml +++ b/mmv1/third_party/terraform/services/tags/resource_tags_location_tag_binding_meta.yaml @@ -10,3 +10,5 @@ fields: - api_field: 'name' - api_field: 'parent' - api_field: 'tagValue' + - field: 'deletion_policy' + provider_only: true diff --git a/mmv1/third_party/terraform/services/tags/resource_tags_test.go b/mmv1/third_party/terraform/services/tags/resource_tags_test.go index 62cf56e2b14a..6f453bc8e8fd 100644 --- a/mmv1/third_party/terraform/services/tags/resource_tags_test.go +++ b/mmv1/third_party/terraform/services/tags/resource_tags_test.go @@ -7,6 +7,11 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/tags" + "github.com/hashicorp/terraform-provider-google/google/services/tagslocation" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -301,7 +306,7 @@ func testAccCheckTagsTagKeyDestroyProducer(t *testing.T) func(s *terraform.State config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{TagsBasePath}}tagKeys/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(tags.Product, config)+"tagKeys/{{name}}") if err != nil { return err } @@ -443,7 +448,7 @@ func testAccCheckTagsTagValueDestroyProducer(t *testing.T) func(s *terraform.Sta config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{TagsBasePath}}tagValues/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(tags.Product, config)+"tagValues/{{name}}") if err != nil { return err } @@ -642,7 +647,7 @@ func testAccCheckTagsTagBindingDestroyProducer(t *testing.T) func(s *terraform.S config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{TagsBasePath}}tagBindings/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(tags.Product, config)+"tagBindings/{{name}}") if err != nil { return err } @@ -1619,7 +1624,7 @@ func testAccCheckTagsLocationTagBindingDestroyProducer(t *testing.T) func(s *ter config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{TagsLocationBasePath}}{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(tagslocation.Product, config)+"{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/tpuv2/resource_tpu_v2_vm_test.go.tmpl b/mmv1/third_party/terraform/services/tpuv2/resource_tpu_v2_vm_test.go.tmpl index 4249f3f954ce..b48433b6dc34 100644 --- a/mmv1/third_party/terraform/services/tpuv2/resource_tpu_v2_vm_test.go.tmpl +++ b/mmv1/third_party/terraform/services/tpuv2/resource_tpu_v2_vm_test.go.tmpl @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/tpuv2" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" ) func TestAccTpuV2Vm_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vectorsearch/resource_vector_search_collection_test.go b/mmv1/third_party/terraform/services/vectorsearch/resource_vector_search_collection_test.go index 67164a65bf9d..197d839d5ed9 100644 --- a/mmv1/third_party/terraform/services/vectorsearch/resource_vector_search_collection_test.go +++ b/mmv1/third_party/terraform/services/vectorsearch/resource_vector_search_collection_test.go @@ -4,6 +4,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/vectorsearch" "testing" ) diff --git a/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_index_test.go b/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_index_test.go index 6f376ca69d22..86ee013bb908 100644 --- a/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_index_test.go +++ b/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_index_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccDataSourceVertexAIIndex_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query.go b/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query.go index 738329ef8af0..9019b69fc44e 100644 --- a/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query.go +++ b/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query.go @@ -68,7 +68,7 @@ func dataSourceVertexAIReasoningEngineQueryRead(d *schema.ResourceData, meta int // A non-nil billing_project indicates no error, and should be used. billingProject, _ := tpgresource.GetBillingProject(d, config) - url, err := tpgresource.ReplaceVars(d, config, "{{VertexAIBasePath}}projects/{{project}}/locations/{{region}}/reasoningEngines/{{reasoning_engine_id}}:query") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"projects/{{project}}/locations/{{region}}/reasoningEngines/{{reasoning_engine_id}}:query") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query_test.go b/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query_test.go index cb82f9ab84fa..a70873e17fe4 100644 --- a/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query_test.go +++ b/mmv1/third_party/terraform/services/vertexai/data_source_vertex_ai_reasoning_engine_query_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccDataSourceVertexAIReasoningEngineQuery_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/iam_vertex_endpoint_test.go.tmpl b/mmv1/third_party/terraform/services/vertexai/iam_vertex_endpoint_test.go.tmpl index 209e3173207c..3fe7eb40896f 100644 --- a/mmv1/third_party/terraform/services/vertexai/iam_vertex_endpoint_test.go.tmpl +++ b/mmv1/third_party/terraform/services/vertexai/iam_vertex_endpoint_test.go.tmpl @@ -9,6 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" + _ "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/envvar" ) diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_test.go index aa7665dbacd1..261205873784 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_test.go @@ -6,6 +6,10 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIEndpoint_vertexAiEndpointNetwork(t *testing.T) { @@ -13,8 +17,8 @@ func TestAccVertexAIEndpoint_vertexAiEndpointNetwork(t *testing.T) { context := map[string]interface{}{ "endpoint_name": fmt.Sprint(acctest.RandInt(t) % 9999999999), - "kms_key_name": acctest.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "vertex-ai-endpoint-update-1"), + "kms_key_name": kms.BootstrapKMSKeyInLocation(t, "us-central1").CryptoKey.Name, + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vertex-ai-endpoint-update-1"), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_with_model_garden_deployment_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_with_model_garden_deployment_test.go index f97ec5504eaf..23083ea12947 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_with_model_garden_deployment_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_endpoint_with_model_garden_deployment_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/vertexai" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" "strings" @@ -292,7 +294,7 @@ func testAccCheckVertexAIEndpointWithModelGardenDeploymentDestroyProducer(t *tes config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{VertexAIBasePath}}projects/{{project}}/locations/{{location}}/endpoints/{{endpoint}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(vertexai.Product, config)+"projects/{{project}}/locations/{{location}}/endpoints/{{endpoint}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_feature_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_feature_test.go index 156680aecd1e..aa255cb88209 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_feature_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_feature_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIFeatureGroupFeature_updated(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_test.go index 5778910b6934..fce6eb6b476b 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_group_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIFeatureGroup_updated(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_featureview_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_featureview_test.go index 255957c2ee7a..bad0046b19e3 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_featureview_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_featureview_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/bigquery" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIFeatureOnlineStoreFeatureview_vertexAiFeatureonlinestoreFeatureview_updated(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_test.go index 58d0d4d19150..26e40b8b0af7 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_feature_online_store_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" ) func TestAccVertexAIFeatureOnlineStore_updated(t *testing.T) { @@ -87,11 +88,11 @@ resource google_vertex_ai_feature_online_store "feature_online_store" { func TestAccVertexAIFeatureOnlineStore_bigtable_full(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), - "kms_key_name": kms.CryptoKey.Name, + "kms_key_name": bootstrapped.CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_deployed_index_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_deployed_index_test.go index c32b255b6705..1109f77c2140 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_deployed_index_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_deployed_index_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIIndexEndpointDeployedIndex_vertexAiIndexEndpointDeployedIndexDedicatedResourcesExample_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_test.go index 2cc51a0bdeab..8e6d4901d12d 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_endpoint_test.go @@ -6,6 +6,9 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIIndexEndpoint_updated(t *testing.T) { @@ -13,7 +16,7 @@ func TestAccVertexAIIndexEndpoint_updated(t *testing.T) { t.Parallel() context := map[string]interface{}{ - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "vpc-network-1"), "random_suffix": acctest.RandString(t, 10), } diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_test.go index 08c4d02f2b60..ee2f0e979228 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_index_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + "github.com/hashicorp/terraform-provider-google/google/services/vertexai" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -173,7 +175,7 @@ func testAccCheckVertexAIIndexDestroyProducer_basic(t *testing.T) func(s *terraf config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{VertexAIBasePath}}projects/{{project}}/locations/{{region}}/indexes/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(vertexai.Product, config)+"projects/{{project}}/locations/{{region}}/indexes/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_metadata_store_test.go.tmpl b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_metadata_store_test.go.tmpl index 2f2170fe940f..94c897eddebb 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_metadata_store_test.go.tmpl +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_metadata_store_test.go.tmpl @@ -4,11 +4,13 @@ package vertexai_test import ( "fmt" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" "testing" "strings" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-provider-google/google/services/kms" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -16,7 +18,7 @@ import ( func TestAccVertexAIMetadataStore_vertexAiMetadataStoreExample(t *testing.T) { t.Parallel() - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") name := fmt.Sprintf("tf-test-%s", acctest.RandString(t, 10)) acctest.VcrTest(t, resource.TestCase{ @@ -25,7 +27,7 @@ func TestAccVertexAIMetadataStore_vertexAiMetadataStoreExample(t *testing.T) { CheckDestroy: testAccCheckVertexAIMetadataStoreDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccVertexAIMetadataStore_vertexAiMetadataStoreExample(name, kms.CryptoKey.Name), + Config: testAccVertexAIMetadataStore_vertexAiMetadataStoreExample(name, bootstrapped.CryptoKey.Name), }, { ResourceName: "google_vertex_ai_metadata_store.store", diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_rag_engine_config_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_rag_engine_config_test.go index 20f5f798ddc9..4990b66ce2b2 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_rag_engine_config_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_rag_engine_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIRagEngineConfig_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_reasoning_engine_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_reasoning_engine_test.go index 38959ebf15ef..929cae07405f 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_reasoning_engine_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_reasoning_engine_test.go @@ -7,12 +7,17 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/secretmanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/storage" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAIReasoningEngine_vertexAiReasoningEngineUpdate(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-aiplatform.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -22,7 +27,7 @@ func TestAccVertexAIReasoningEngine_vertexAiReasoningEngineUpdate(t *testing.T) context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), "bucket_name": acctest.TestBucketName(t), - "kms_key_name": acctest.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-re-key1").CryptoKey.Name, + "kms_key_name": kms.BootstrapKMSKeyWithPurposeInLocationAndName(t, "ENCRYPT_DECRYPT", "us-central1", "tf-bootstrap-re-key1").CryptoKey.Name, } acctest.VcrTest(t, resource.TestCase{ diff --git a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_tensorboard_test.go b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_tensorboard_test.go index 8cfb7984e688..127f0c17516b 100644 --- a/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_tensorboard_test.go +++ b/mmv1/third_party/terraform/services/vertexai/resource_vertex_ai_tensorboard_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/vertexai" ) func TestAccVertexAITensorboard_Update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_annoucements.go b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_annoucements.go index f703fbfac2f6..3bde84877cf2 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_annoucements.go +++ b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_annoucements.go @@ -47,9 +47,9 @@ func dataSourceVmwareengineAnnouncementsRead(d *schema.ResourceData, meta interf var resourceURL string if fetchSingleAnnouncement { - resourceURL, err = tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}{{parent}}/announcements/{{name}}") + resourceURL, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/announcements/{{name}}") } else { - resourceURL, err = tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}{{parent}}/announcements") + resourceURL, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/announcements") } if err != nil { diff --git a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_network_test.go b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_network_test.go index 880f77c6d25f..8a07fe2c65e9 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_network_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_network_test.go @@ -6,6 +6,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" ) func TestAccDataSourceVmwareEngineNetwork_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_nsx_credentials.go b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_nsx_credentials.go index 984ff1e94650..7b327b83590c 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_nsx_credentials.go +++ b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_nsx_credentials.go @@ -42,7 +42,7 @@ func dataSourceVmwareengineNsxCredentialsRead(d *schema.ResourceData, meta inter return err } - url, err := tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}{{parent}}:showNsxCredentials") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}:showNsxCredentials") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_upgrades.go b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_upgrades.go index 773f29c285d2..d8c2a34594be 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_upgrades.go +++ b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_upgrades.go @@ -48,9 +48,9 @@ func dataSourceVmwareengineUpgradesRead(d *schema.ResourceData, meta interface{} var url string if fetchSingleUpgrade { - url, err = tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}{{parent}}/upgrades/{{name}}") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/upgrades/{{name}}") } else { - url, err = tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}{{parent}}/upgrades") + url, err = tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}/upgrades") } if err != nil { diff --git a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_vcenter_credentials.go b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_vcenter_credentials.go index 55ac33a38d2f..a87cb80149b6 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_vcenter_credentials.go +++ b/mmv1/third_party/terraform/services/vmwareengine/data_source_google_vmwareengine_vcenter_credentials.go @@ -43,7 +43,7 @@ func dataSourceVmwareengineVcenterCredentialsRead(d *schema.ResourceData, meta i return err } - url, err := tpgresource.ReplaceVars(d, config, "{{VmwareengineBasePath}}{{parent}}:showVcenterCredentials") + url, err := tpgresource.ReplaceVars(d, config, transport_tpg.BaseUrl(Product, config)+"{{parent}}:showVcenterCredentials") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_cluster_test.go b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_cluster_test.go index 880cfe3a21a6..3352d171ff51 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_cluster_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_cluster_test.go @@ -9,9 +9,12 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/filestore" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" @@ -21,7 +24,7 @@ func TestAccVmwareengineCluster_vmwareEngineClusterUpdate(t *testing.T) { acctest.SkipIfVcr(t) t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-vmwareengine.iam.gserviceaccount.com", Role: "roles/file.viewer", @@ -35,7 +38,7 @@ func TestAccVmwareengineCluster_vmwareEngineClusterUpdate(t *testing.T) { "org_id": envvar.GetTestOrgFromEnv(t), "billing_account": envvar.GetTestBillingAccountFromEnv(t), "vmwareengine_project": os.Getenv("GOOGLE_VMWAREENGINE_PROJECT"), - "fs_network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "tf-test-cluster"), + "fs_network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "tf-test-cluster"), "svc_ip_cidr": "10.0.0.0/24", "zone": region_id + "-b", "pc_name": "tf-test-cluster-pc" + random_suffix, @@ -393,7 +396,7 @@ func testAccCheckVmwareengineClusterDestroyProducer(t *testing.T) func(s *terraf config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{VmwareengineBasePath}}{{parent}}/clusters/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(vmwareengine.Product, config)+"{{parent}}/clusters/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_datastore_test.go b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_datastore_test.go index 1cf8a4954e02..cc1cd681868d 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_datastore_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_datastore_test.go @@ -11,6 +11,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/filestore" + _ "github.com/hashicorp/terraform-provider-google/google/services/netapp" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + "github.com/hashicorp/terraform-provider-google/google/services/servicenetworking" + "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -75,7 +80,7 @@ resource "google_vmwareengine_datastore" "example_thirdparty" { func TestAccVmwareengineDatastore_vmwareEngineDatastoreFilestore_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-vmwareengine.iam.gserviceaccount.com", Role: "roles/file.viewer", @@ -85,7 +90,7 @@ func TestAccVmwareengineDatastore_vmwareEngineDatastoreFilestore_update(t *testi context := map[string]interface{}{ "region": envvar.GetTestRegionFromEnv(), "zone": envvar.GetTestZoneFromEnv(), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "datastore-test"), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "datastore-test"), "random_suffix": acctest.RandString(t, 10), } @@ -163,7 +168,7 @@ resource "google_vmwareengine_datastore" "example_filestore" { func TestAccVmwareengineDatastore_vmwareEngineDatastoreNetapp_update(t *testing.T) { t.Parallel() - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-vmwareengine.iam.gserviceaccount.com", Role: "roles/netapp.viewer", @@ -173,7 +178,7 @@ func TestAccVmwareengineDatastore_vmwareEngineDatastoreNetapp_update(t *testing. context := map[string]interface{}{ "region": envvar.GetTestRegionFromEnv(), "zone": envvar.GetTestZoneFromEnv(), - "network_name": acctest.BootstrapSharedServiceNetworkingConnection(t, "datastore-test", acctest.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), + "network_name": servicenetworking.BootstrapSharedServiceNetworkingConnection(t, "datastore-test", servicenetworking.ServiceNetworkWithParentService("netapp.servicenetworking.goog")), "random_suffix": acctest.RandString(t, 10), } @@ -266,7 +271,7 @@ func testAccCheckVmwareengineDatastoreDestroyProducer(t *testing.T) func(s *terr config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{VmwareengineBasePath}}projects/{{project}}/locations/{{location}}/datastores/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(vmwareengine.Product, config)+"projects/{{project}}/locations/{{location}}/datastores/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_external_address_test.go b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_external_address_test.go index 92554ea620d6..0b683e382e48 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_external_address_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_external_address_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -257,7 +258,7 @@ func testAccCheckVmwareengineExternalAddressDestroyProducer(t *testing.T) func(s } config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{VmwareengineBasePath}}{{parent}}/externalAddresses/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(vmwareengine.Product, config)+"{{parent}}/externalAddresses/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_policy_test.go b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_policy_test.go index e190cab624ad..46dff8af7126 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_policy_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_policy_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" ) func TestAccVmwareengineNetworkPolicy_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_test.go b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_test.go index 9f966662e8d1..c22391fc3543 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_network_test.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" ) func TestAccVmwareengineNetwork_vmwareEngineNetworkUpdate(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_private_cloud_test.go b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_private_cloud_test.go index c98354d3f067..b969d7e90a5e 100644 --- a/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_private_cloud_test.go +++ b/mmv1/third_party/terraform/services/vmwareengine/resource_vmwareengine_private_cloud_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/services/vmwareengine" "github.com/hashicorp/terraform-provider-google/google/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -434,7 +435,7 @@ func testAccCheckVmwareenginePrivateCloudDestroyProducer(t *testing.T) func(s *t continue } config := acctest.GoogleProviderConfig(t) - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{VmwareengineBasePath}}projects/{{project}}/locations/{{location}}/privateClouds/{{name}}") + url, err := tpgresource.ReplaceVarsForTest(config, rs, transport_tpg.BaseUrl(vmwareengine.Product, config)+"projects/{{project}}/locations/{{location}}/privateClouds/{{name}}") if err != nil { return err } diff --git a/mmv1/third_party/terraform/services/vpcaccess/data_source_vpc_access_connector_test.go b/mmv1/third_party/terraform/services/vpcaccess/data_source_vpc_access_connector_test.go index 80826aaa4766..a00e91669ea0 100644 --- a/mmv1/third_party/terraform/services/vpcaccess/data_source_vpc_access_connector_test.go +++ b/mmv1/third_party/terraform/services/vpcaccess/data_source_vpc_access_connector_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/vpcaccess" ) func TestAccVPCAccessConnectorDatasource_basic(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/vpcaccess/resource_vpc_access_connector_test.go b/mmv1/third_party/terraform/services/vpcaccess/resource_vpc_access_connector_test.go index 9abbd722514d..1010fc46ad99 100644 --- a/mmv1/third_party/terraform/services/vpcaccess/resource_vpc_access_connector_test.go +++ b/mmv1/third_party/terraform/services/vpcaccess/resource_vpc_access_connector_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/vpcaccess" ) func TestAccVPCAccessConnector_vpcAccessConnectorThroughput(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_shielded_config_test.go b/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_shielded_config_test.go index e72f63d05d14..276e4fa371a3 100644 --- a/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_shielded_config_test.go +++ b/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_shielded_config_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/workbench" ) func TestAccWorkbenchInstance_shielded_config_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_test.go b/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_test.go index 9f66d08c26e7..c8a0a7b612d7 100644 --- a/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_test.go +++ b/mmv1/third_party/terraform/services/workbench/resource_workbench_instance_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/workbench" "github.com/hashicorp/terraform-plugin-testing/plancheck" ) diff --git a/mmv1/third_party/terraform/services/workflows/resource_workflows_workflow_test.go b/mmv1/third_party/terraform/services/workflows/resource_workflows_workflow_test.go index 4ac91af4ceec..f7ffebd63e8a 100644 --- a/mmv1/third_party/terraform/services/workflows/resource_workflows_workflow_test.go +++ b/mmv1/third_party/terraform/services/workflows/resource_workflows_workflow_test.go @@ -8,6 +8,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/services/kms" + "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" "github.com/hashicorp/terraform-provider-google/google/services/workflows" transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" ) @@ -293,8 +295,8 @@ func TestAccWorkflowsWorkflow_CMEK(t *testing.T) { t.Parallel() workflowName := fmt.Sprintf("tf-test-acc-workflow-%d", acctest.RandInt(t)) - kms := acctest.BootstrapKMSKeyInLocation(t, "us-central1") - acctest.BootstrapIamMembers(t, []acctest.IamMember{ + bootstrapped := kms.BootstrapKMSKeyInLocation(t, "us-central1") + resourcemanager.BootstrapIamMembers(t, []resourcemanager.IamMember{ { Member: "serviceAccount:service-{project_number}@gcp-sa-workflows.iam.gserviceaccount.com", Role: "roles/cloudkms.cryptoKeyEncrypterDecrypter", @@ -307,7 +309,7 @@ func TestAccWorkflowsWorkflow_CMEK(t *testing.T) { CheckDestroy: testAccCheckWorkflowsWorkflowDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccWorkflowsWorkflow_CMEK(workflowName, kms.CryptoKey.Name), + Config: testAccWorkflowsWorkflow_CMEK(workflowName, bootstrapped.CryptoKey.Name), }, }, }) diff --git a/mmv1/third_party/terraform/services/workloadidentity/resource_workload_identity_service_agent_test.go b/mmv1/third_party/terraform/services/workloadidentity/resource_workload_identity_service_agent_test.go index 03f9ad45ec3e..8822f2e4601e 100644 --- a/mmv1/third_party/terraform/services/workloadidentity/resource_workload_identity_service_agent_test.go +++ b/mmv1/third_party/terraform/services/workloadidentity/resource_workload_identity_service_agent_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/workloadidentity" ) func TestAccWorkloadIdentityServiceAgent_AllFieldsPresent(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_cluster_test.go b/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_cluster_test.go index a9d3be0177e2..7ed9766a3306 100644 --- a/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_cluster_test.go +++ b/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_cluster_test.go @@ -5,6 +5,8 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/workstations" ) func TestAccWorkstationsWorkstationCluster_update(t *testing.T) { diff --git a/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_config_test.go b/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_config_test.go index d5ba01fee70a..c9884b1e78e8 100644 --- a/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_config_test.go +++ b/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_config_test.go @@ -3,6 +3,10 @@ package workstations_test import ( "github.com/hashicorp/terraform-provider-google/google/acctest" "github.com/hashicorp/terraform-provider-google/google/envvar" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/resourcemanager" + _ "github.com/hashicorp/terraform-provider-google/google/services/tags" + _ "github.com/hashicorp/terraform-provider-google/google/services/workstations" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_test.go b/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_test.go index 127b6db6fbae..2313c956309a 100644 --- a/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_test.go +++ b/mmv1/third_party/terraform/services/workstations/resource_workstations_workstation_test.go @@ -2,6 +2,8 @@ package workstations_test import ( "github.com/hashicorp/terraform-provider-google/google/acctest" + _ "github.com/hashicorp/terraform-provider-google/google/services/compute" + _ "github.com/hashicorp/terraform-provider-google/google/services/workstations" "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/mmv1/third_party/terraform/sweeper/gcp_sweeper.go b/mmv1/third_party/terraform/sweeper/gcp_sweeper.go index 695cc2450655..7c196838b6c8 100644 --- a/mmv1/third_party/terraform/sweeper/gcp_sweeper.go +++ b/mmv1/third_party/terraform/sweeper/gcp_sweeper.go @@ -45,8 +45,6 @@ func SharedConfigForRegion(region string) (*transport_tpg.Config, error) { Project: project, } - transport_tpg.ConfigureBasePaths(conf) - return conf, nil } diff --git a/mmv1/third_party/terraform/tpgdclresource/canonicalize.go b/mmv1/third_party/terraform/tpgdclresource/canonicalize.go index d72cd3f00852..8f47b7ef075b 100755 --- a/mmv1/third_party/terraform/tpgdclresource/canonicalize.go +++ b/mmv1/third_party/terraform/tpgdclresource/canonicalize.go @@ -9,11 +9,25 @@ import ( "strings" "time" - "bitbucket.org/creachadair/stringset" glog "github.com/golang/glog" ) -var selfLinkIgnorableComponents = stringset.New("projects", "regions", "locations", "zones", "organizations", "compute", "v1", "v1beta1", "beta") +var selfLinkIgnorableComponents = map[string]struct{}{ + "projects": {}, + "regions": {}, + "locations": {}, + "zones": {}, + "organizations": {}, + "compute": {}, + "v1": {}, + "v1beta1": {}, + "beta": {}, +} + +func hasKey(m map[string]struct{}, k string) bool { + _, ok := m[k] + return ok +} // SelfLinkToSelfLink returns true if left and right are equivalent for selflinks. // That means that they are piecewise equal, comparing components, allowing for @@ -54,9 +68,9 @@ func SelfLinkToSelfLink(l, r *string) bool { case lcomp[li] == rcomp[ri]: li++ ri++ - case selfLinkIgnorableComponents.Contains(lcomp[li]): + case hasKey(selfLinkIgnorableComponents, lcomp[li]): li++ - case selfLinkIgnorableComponents.Contains(rcomp[ri]): + case hasKey(selfLinkIgnorableComponents, rcomp[ri]): ri++ // The second-to-last element in a long-form self-link contains the // name of the resource. The name of the resource might be anything, @@ -192,9 +206,9 @@ func PartialSelfLinkToSelfLink(l, r *string) bool { case lcomp[li] == rcomp[ri]: li-- ri-- - case selfLinkIgnorableComponents.Contains(lcomp[li]): + case hasKey(selfLinkIgnorableComponents, lcomp[li]): li-- - case selfLinkIgnorableComponents.Contains(rcomp[ri]): + case hasKey(selfLinkIgnorableComponents, rcomp[ri]): ri-- // As in SelfLinkToSelfLink, we permit any value in the second-to-last field // for the value which is longer. diff --git a/mmv1/third_party/terraform/tpgdclresource/update.go b/mmv1/third_party/terraform/tpgdclresource/update.go index 06e4d0f0673c..5e8bec864cd4 100755 --- a/mmv1/third_party/terraform/tpgdclresource/update.go +++ b/mmv1/third_party/terraform/tpgdclresource/update.go @@ -7,8 +7,6 @@ import ( "strings" "unicode" "unicode/utf8" - - "bitbucket.org/creachadair/stringset" ) // UpdateMask creates a Update Mask string according to https://google.aip.dev/161 @@ -18,13 +16,25 @@ func UpdateMask(ds []*FieldDiff) string { ss = append(ss, convertUpdateMaskVal(v.FieldName)) } - dupesRemoved := stringset.New(ss...).Elements() + dupesRemoved := removeDuplicates(ss) // Sorting the entries is optional, but makes it easier to read + test. sort.Strings(dupesRemoved) return strings.Join(dupesRemoved, ",") } +func removeDuplicates(ss []string) []string { + m := make(map[string]struct{}) + var out []string + for _, s := range ss { + if _, ok := m[s]; !ok { + m[s] = struct{}{} + out = append(out, s) + } + } + return out +} + func titleCaseToCamelCase(s string) string { r, n := utf8.DecodeRuneInString(s) p := string(unicode.ToLower(r)) @@ -71,7 +81,7 @@ func TopLevelUpdateMask(ds []*FieldDiff) string { ss = append(ss, convertUpdateMaskVal(part)) } - dupesRemoved := stringset.New(ss...).Elements() + dupesRemoved := removeDuplicates(ss) // Sorting the entries is optional, but makes it easier to read + test. sort.Strings(dupesRemoved) @@ -84,7 +94,7 @@ func SnakeCaseUpdateMask(ds []*FieldDiff) string { for _, v := range ds { ss = append(ss, TitleToSnakeCase(convertUpdateMaskVal(v.FieldName))) } - dupesRemoved := stringset.New(ss...).Elements() + dupesRemoved := removeDuplicates(ss) // Sorting the entries is optional, but makes it easier to read + test. sort.Strings(dupesRemoved) diff --git a/mmv1/third_party/terraform/tpgiamresource/iam.go.tmpl b/mmv1/third_party/terraform/tpgiamresource/iam.go.tmpl index e26760b39d47..b1d6f8e6ea0a 100644 --- a/mmv1/third_party/terraform/tpgiamresource/iam.go.tmpl +++ b/mmv1/third_party/terraform/tpgiamresource/iam.go.tmpl @@ -55,6 +55,10 @@ type ( // Parser for Terraform resource identifier (d.Id) for resource whose IAM policy is being changed ResourceIdParserFunc func(d *schema.ResourceData, config *transport_tpg.Config) error + + // ParentResourceIdFromIdentityParserFunc derives the canonical identifier of the IAM resource's + // parent (e.g. the project, folder, bucket, or instance the policy is attached to). + ParentResourceIdFromIdentityParserFunc func(d *schema.ResourceData, identity *schema.IdentityData, config *transport_tpg.Config) (resourceID string, err error) ) // Locking wrapper around read-only operation with retries. @@ -428,6 +432,8 @@ type IamSettings struct { StateUpgraders []schema.StateUpgrader SchemaVersion int CreateTimeOut int64 + // ParentResourceIdentityParser, when non-nil, enables ResourceIdentity for this IAM resource + ParentResourceIdentityParser ParentResourceIdFromIdentityParserFunc } func NewIamSettings(options ...func(*IamSettings)) *IamSettings { @@ -444,6 +450,13 @@ func IamWithDeprecationMessage(message string) func(s *IamSettings) { } } +// IamWithParentResourceIdentity enables import with resource identity block when parser is non-nil. +func IamWithParentResourceIdentity(parser ParentResourceIdFromIdentityParserFunc) func(*IamSettings) { + return func(s *IamSettings) { + s.ParentResourceIdentityParser = parser + } +} + func IamWithGAResourceDeprecation() func (s *IamSettings) { {{- if eq $.TargetVersionName "ga" }} return IamWithDeprecationMessage("This resource has been deprecated in the google (GA) provider, and will only be available in the google-beta provider in a future release.") @@ -544,3 +557,26 @@ func MissingBindings(a, b []*cloudresourcemanager.Binding) []*cloudresourcemanag } return results } + +// Converts an IAM parent resource schema to identity schema +func ConvertToIdentitySchema(parentSchema map[string]*schema.Schema) map[string]*schema.Schema { + identitySchema := make(map[string]*schema.Schema) + for k, v := range parentSchema { + identitySchema[k] = &schema.Schema{ + Type: v.Type, + } + if v.Required { + identitySchema[k].RequiredForImport = true + } else { + identitySchema[k].OptionalForImport = true + } + } + return identitySchema +} + +// Copies IAM parent attributes from resource state into identity +func populateIamParentIdentity(identity *schema.IdentityData, d *schema.ResourceData, parentSchema map[string]*schema.Schema) { + for attr := range parentSchema { + identity.Set(attr, d.Get(attr)) + } +} diff --git a/mmv1/third_party/terraform/tpgiamresource/iam_resource_identity.go b/mmv1/third_party/terraform/tpgiamresource/iam_resource_identity.go new file mode 100644 index 000000000000..c8dab376fbbf --- /dev/null +++ b/mmv1/third_party/terraform/tpgiamresource/iam_resource_identity.go @@ -0,0 +1,118 @@ +package tpgiamresource + +import ( + "fmt" + "regexp" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +// IamIdentityParam describes a single parameter of the IAM resource URI. +type IamIdentityParam struct { + Key string // raw key for values map and regex captures (e.g. "serviceId") + IdentityKey string // snake_case key for identity.GetOk (e.g. "service_id") +} + +// IamResourceIdentityConfig holds all the per-resource data needed to parse an +// IAM import identity into the parent resource's id +type IamResourceIdentityConfig struct { + Params []IamIdentityParam + UriFormat string // fmt.Sprintf format producing the canonical resource id +} + +var DefaultConfigValueFuncs = map[string]func(tpgresource.TerraformResourceData, *transport_tpg.Config) (string, error){ + "project": tpgresource.GetProject, + "zone": tpgresource.GetZone, + "region": tpgresource.GetRegion, + "location": tpgresource.GetLocation, +} + +// ParseIamResourceIdentity resolves an IAM import identity into the parent +// resource id string (the same shape as the IAM updater's GetResourceId()). +func ParseIamResourceIdentity( + d *schema.ResourceData, + identity *schema.IdentityData, + config *transport_tpg.Config, + rc IamResourceIdentityConfig, +) (string, error) { + // Collect the raw value supplied for each param from the import identity. + rawVals := make([]string, len(rc.Params)) + for i, p := range rc.Params { + if rv, ok := identity.GetOk(p.IdentityKey); ok { + if s, ok := rv.(string); ok { + rawVals[i] = s + } + } + } + + if uriRe := buildUriFormatRegexp(rc.UriFormat); uriRe != nil { + for i := len(rawVals) - 1; i >= 0; i-- { + if rawVals[i] == "" { + continue + } + m := uriRe.FindStringSubmatch(rawVals[i]) + if m != nil && len(m)-1 == len(rc.Params) { + for j := range rc.Params { + rawVals[j] = m[j+1] + } + break + } + } + } + + resolved := make(map[string]string, len(rc.Params)) + for i, p := range rc.Params { + val := rawVals[i] + if GetDefaultConfigValue := DefaultConfigValueFuncs[p.Key]; GetDefaultConfigValue != nil && val == "" { + defaultVal, err := GetDefaultConfigValue(d, config) + if err != nil { + return "", err + } + if defaultVal == "" { + return "", fmt.Errorf("could not determine %q for IAM import identity; set it on the resource or configure the provider", p.IdentityKey) + } + resolved[p.Key] = defaultVal + continue + } + if val == "" { + return "", fmt.Errorf("import identity is missing attribute %q", p.IdentityKey) + } + resolved[p.Key] = val + } + + args := make([]any, len(rc.Params)) + for i, p := range rc.Params { + args[i] = resolved[p.Key] + } + + return fmt.Sprintf(rc.UriFormat, args...), nil +} + +func buildUriFormatRegexp(uriFormat string) *regexp.Regexp { + parts := strings.Split(uriFormat, "%s") + var sb strings.Builder + sb.WriteString("^") + for i, part := range parts { + sb.WriteString(regexp.QuoteMeta(part)) + if i < len(parts)-1 { + if i == len(parts)-2 { + sb.WriteString("(.+)") + } else { + // Non-final params may themselves contain '/' + // (e.g. "organizations/{id}"). Use a non-greedy match so the + // literal separator that follows anchors the split. + sb.WriteString("(.+?)") + } + } + } + sb.WriteString("$") + re, err := regexp.Compile(sb.String()) + if err != nil { + return nil + } + return re +} diff --git a/mmv1/third_party/terraform/tpgiamresource/resource_iam_binding.go b/mmv1/third_party/terraform/tpgiamresource/resource_iam_binding.go index f3e9f8380379..31e17652e8c1 100644 --- a/mmv1/third_party/terraform/tpgiamresource/resource_iam_binding.go +++ b/mmv1/third_party/terraform/tpgiamresource/resource_iam_binding.go @@ -64,15 +64,26 @@ var iamBindingSchema = map[string]*schema.Schema{ }, } +var IamBindingBaseIdentitySchema = map[string]*schema.Schema{ + "role": { + Type: schema.TypeString, + RequiredForImport: true, + }, + "condition_title": { + Type: schema.TypeString, + OptionalForImport: true, + }, +} + func ResourceIamBinding(parentSpecificSchema map[string]*schema.Schema, newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc, options ...func(*IamSettings)) *schema.Resource { settings := NewIamSettings(options...) createTimeOut := time.Duration(settings.CreateTimeOut) * time.Minute resource := &schema.Resource{ - Create: resourceIamBindingCreateUpdate(newUpdaterFunc, settings.EnableBatching), - Read: resourceIamBindingRead(newUpdaterFunc), - Update: resourceIamBindingCreateUpdate(newUpdaterFunc, settings.EnableBatching), - Delete: resourceIamBindingDelete(newUpdaterFunc, settings.EnableBatching), + Create: resourceIamBindingCreateUpdate(newUpdaterFunc, settings.EnableBatching, parentSpecificSchema, settings.ParentResourceIdentityParser), + Read: resourceIamBindingRead(newUpdaterFunc, parentSpecificSchema, settings.ParentResourceIdentityParser), + Update: resourceIamBindingCreateUpdate(newUpdaterFunc, settings.EnableBatching, parentSpecificSchema, settings.ParentResourceIdentityParser), + Delete: resourceIamBindingDelete(newUpdaterFunc, settings.EnableBatching, parentSpecificSchema, settings.ParentResourceIdentityParser), // if non-empty, this will be used to send a deprecation message when the // resource is used. @@ -81,10 +92,20 @@ func ResourceIamBinding(parentSpecificSchema map[string]*schema.Schema, newUpdat SchemaVersion: settings.SchemaVersion, StateUpgraders: settings.StateUpgraders, Importer: &schema.ResourceImporter{ - State: iamBindingImport(newUpdaterFunc, resourceIdParser), + State: iamBindingImport(newUpdaterFunc, resourceIdParser, settings.ParentResourceIdentityParser), }, UseJSONNumber: true, } + + if settings.ParentResourceIdentityParser != nil { + resource.Identity = &schema.ResourceIdentity{ + Version: 1, + SchemaFunc: func() map[string]*schema.Schema { + return tpgresource.MergeSchemas(IamBindingBaseIdentitySchema, ConvertToIdentitySchema(parentSpecificSchema)) + }, + } + } + if createTimeOut > 0 { resource.Timeouts = &schema.ResourceTimeout{ Create: schema.DefaultTimeout(createTimeOut), @@ -93,7 +114,58 @@ func ResourceIamBinding(parentSpecificSchema map[string]*schema.Schema, newUpdat return resource } -func resourceIamBindingCreateUpdate(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool) func(*schema.ResourceData, interface{}) error { +// setIamBindingIdFromParentResourceIdentity converts a resource-identity import +// into the `id` (`{resource} {role} [condition_title]`) consumed by +// iamBindingImport. No-op if there is no identity parser or d already has an id. +func setIamBindingIdFromParentResourceIdentity(d *schema.ResourceData, config *transport_tpg.Config, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) error { + if parentResourceIdentityParser == nil || d.Id() != "" { + return nil + } + identity, err := d.Identity() + if err != nil { + return err + } + resourceID, err := parentResourceIdentityParser(d, identity, config) + if err != nil { + return err + } + roleVal, ok := identity.GetOk("role") + if !ok { + return fmt.Errorf("import identity is missing attribute %q", "role") + } + role, ok := roleVal.(string) + if !ok || role == "" { + return fmt.Errorf("import identity attribute %q must be a non-empty string", "role") + } + conditionTitle := "" + if ctVal, ok := identity.GetOk("condition_title"); ok { + ct, ok := ctVal.(string) + if !ok { + return fmt.Errorf("import identity attribute %q must be a string", "condition_title") + } + conditionTitle = ct + } + idParts := []string{resourceID, role} + if conditionTitle != "" { + idParts = append(idParts, conditionTitle) + } + d.SetId(strings.Join(idParts, " ")) + return nil +} + +// setIamBindingResourceIdentity sets parent attributes from state plus role/condition_title. +// ParentResourceIdentityParser is only identity→id (for import); it cannot derive parent +// fields from updater.GetResourceId(). Those fields must come from the same state the updater +// used, so they stay consistent with GetResourceId() and round-trip through ParentResourceIdentityParser. +func setIamBindingResourceIdentity(identity *schema.IdentityData, d *schema.ResourceData, parentSpecificSchema map[string]*schema.Schema, role, conditionTitle string) { + populateIamParentIdentity(identity, d, parentSpecificSchema) + identity.Set("role", role) + if conditionTitle != "" { + identity.Set("condition_title", conditionTitle) + } +} + +func resourceIamBindingCreateUpdate(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) func(*schema.ResourceData, interface{}) error { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) updater, err := newUpdaterFunc(d, config) @@ -123,11 +195,24 @@ func resourceIamBindingCreateUpdate(newUpdaterFunc NewResourceIamUpdaterFunc, en if k := conditionKeyFromCondition(binding.Condition); !k.Empty() { d.SetId(d.Id() + "/" + k.String()) } - return resourceIamBindingRead(newUpdaterFunc)(d, meta) + + if parentResourceIdentityParser != nil { + identity, err := d.Identity() + if err != nil { + return err + } + conditionTitle := "" + if binding.Condition != nil { + conditionTitle = binding.Condition.Title + } + setIamBindingResourceIdentity(identity, d, parentSpecificSchema, binding.Role, conditionTitle) + } + + return resourceIamBindingRead(newUpdaterFunc, parentSpecificSchema, parentResourceIdentityParser)(d, meta) } } -func resourceIamBindingRead(newUpdaterFunc NewResourceIamUpdaterFunc) schema.ReadFunc { +func resourceIamBindingRead(newUpdaterFunc NewResourceIamUpdaterFunc, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.ReadFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -177,16 +262,31 @@ func resourceIamBindingRead(newUpdaterFunc NewResourceIamUpdaterFunc) schema.Rea if err := d.Set("etag", p.Etag); err != nil { return fmt.Errorf("Error setting etag: %s", err) } + + if parentResourceIdentityParser != nil && binding != nil { + identity, err := d.Identity() + if err != nil { + return err + } + conditionTitle := "" + if binding.Condition != nil { + conditionTitle = binding.Condition.Title + } + setIamBindingResourceIdentity(identity, d, parentSpecificSchema, binding.Role, conditionTitle) + } return nil } } -func iamBindingImport(newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc) schema.StateFunc { +func iamBindingImport(newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.StateFunc { return func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { if resourceIdParser == nil { return nil, errors.New("Import not supported for this IAM resource.") } config := m.(*transport_tpg.Config) + if err := setIamBindingIdFromParentResourceIdentity(d, config, parentResourceIdentityParser); err != nil { + return nil, err + } s := strings.Fields(d.Id()) var id, role string if len(s) < 2 { @@ -261,7 +361,7 @@ func iamBindingImport(newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser } } -func resourceIamBindingDelete(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool) schema.DeleteFunc { +func resourceIamBindingDelete(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.DeleteFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -286,7 +386,7 @@ func resourceIamBindingDelete(newUpdaterFunc NewResourceIamUpdaterFunc, enableBa return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Resource %q for IAM binding with role %q", updater.DescribeResource(), binding.Role)) } - return resourceIamBindingRead(newUpdaterFunc)(d, meta) + return resourceIamBindingRead(newUpdaterFunc, parentSpecificSchema, parentResourceIdentityParser)(d, meta) } } diff --git a/mmv1/third_party/terraform/tpgiamresource/resource_iam_member.go b/mmv1/third_party/terraform/tpgiamresource/resource_iam_member.go index ae2fd9d80b7e..b6f6b89fa491 100644 --- a/mmv1/third_party/terraform/tpgiamresource/resource_iam_member.go +++ b/mmv1/third_party/terraform/tpgiamresource/resource_iam_member.go @@ -88,12 +88,32 @@ var IamMemberBaseSchema = map[string]*schema.Schema{ }, } -func iamMemberImport(newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc) schema.StateFunc { +var IamMemberBaseIdentitySchema = map[string]*schema.Schema{ + "member": { + Type: schema.TypeString, + RequiredForImport: true, + }, + "role": { + Type: schema.TypeString, + RequiredForImport: true, + }, + "condition_title": { + Type: schema.TypeString, + OptionalForImport: true, + }, +} + +func iamMemberImport(newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.StateFunc { return func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { if resourceIdParser == nil { return nil, errors.New("Import not supported for this IAM resource.") } + config := m.(*transport_tpg.Config) + if err := setIamMemberIdFromParentResourceIdentity(d, config, parentResourceIdentityParser); err != nil { + return nil, err + } + s := strings.Fields(d.Id()) var id, role, member string if len(s) < 3 { @@ -170,15 +190,77 @@ func iamMemberImport(newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser } } +// setIamMemberIdFromParentResourceIdentity converts a resource-identity import into +// the `id` (`{resource} {role} {member} [condition_title]`) consumed +// by iamMemberImport. No-op if there is no identity parser or d already has +// an id. +func setIamMemberIdFromParentResourceIdentity(d *schema.ResourceData, config *transport_tpg.Config, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) error { + if parentResourceIdentityParser == nil || d.Id() != "" { + return nil + } + identity, err := d.Identity() + if err != nil { + return err + } + resourceID, err := parentResourceIdentityParser(d, identity, config) + if err != nil { + return err + } + roleVal, ok := identity.GetOk("role") + if !ok { + return fmt.Errorf("import identity is missing attribute %q", "role") + } + role, ok := roleVal.(string) + if !ok || role == "" { + return fmt.Errorf("import identity attribute %q must be a non-empty string", "role") + } + memberVal, ok := identity.GetOk("member") + if !ok { + return fmt.Errorf("import identity is missing attribute %q", "member") + } + member, ok := memberVal.(string) + if !ok || member == "" { + return fmt.Errorf("import identity attribute %q must be a non-empty string", "member") + } + member = tpgresource.NormalizeIamPrincipalCasing(member) + conditionTitle := "" + if ctVal, ok := identity.GetOk("condition_title"); ok { + ct, ok := ctVal.(string) + if !ok { + return fmt.Errorf("import identity attribute %q must be a string", "condition_title") + } + conditionTitle = ct + } + idParts := []string{resourceID, role, member} + if conditionTitle != "" { + idParts = append(idParts, conditionTitle) + } + d.SetId(strings.Join(idParts, " ")) + return nil +} + +// setIamMemberResourceIdentity sets parent attributes from state plus role/member/condition_title. +// ParentResourceIdentityParser is only identity→id (for import); it cannot derive parent +// fields from updater.GetResourceId(). Those fields must come from the same state the updater +// used, so they stay consistent with GetResourceId() and round-trip through ParentResourceIdentityParser. +func setIamMemberResourceIdentity(identity *schema.IdentityData, d *schema.ResourceData, parentSpecificSchema map[string]*schema.Schema, role, member, conditionTitle string) { + populateIamParentIdentity(identity, d, parentSpecificSchema) + identity.Set("role", role) + identity.Set("member", tpgresource.NormalizeIamPrincipalCasing(member)) + if conditionTitle != "" { + identity.Set("condition_title", conditionTitle) + } +} + func ResourceIamMember(parentSpecificSchema map[string]*schema.Schema, newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc, options ...func(*IamSettings)) *schema.Resource { settings := NewIamSettings(options...) createTimeOut := time.Duration(settings.CreateTimeOut) * time.Minute resourceSchema := &schema.Resource{ - Create: resourceIamMemberCreate(newUpdaterFunc, settings.EnableBatching), - Read: resourceIamMemberRead(newUpdaterFunc), - Delete: resourceIamMemberDelete(newUpdaterFunc, settings.EnableBatching), + Create: resourceIamMemberCreate(newUpdaterFunc, settings.EnableBatching, parentSpecificSchema, settings.ParentResourceIdentityParser), + Read: resourceIamMemberRead(newUpdaterFunc, parentSpecificSchema, settings.ParentResourceIdentityParser), + Delete: resourceIamMemberDelete(newUpdaterFunc, settings.EnableBatching, parentSpecificSchema, settings.ParentResourceIdentityParser), // if non-empty, this will be used to send a deprecation message when the // resource is used. @@ -188,11 +270,20 @@ func ResourceIamMember(parentSpecificSchema map[string]*schema.Schema, newUpdate SchemaVersion: settings.SchemaVersion, StateUpgraders: settings.StateUpgraders, Importer: &schema.ResourceImporter{ - State: iamMemberImport(newUpdaterFunc, resourceIdParser), + State: iamMemberImport(newUpdaterFunc, resourceIdParser, settings.ParentResourceIdentityParser), }, UseJSONNumber: true, } + if settings.ParentResourceIdentityParser != nil { + resourceSchema.Identity = &schema.ResourceIdentity{ + Version: 1, + SchemaFunc: func() map[string]*schema.Schema { + return tpgresource.MergeSchemas(IamMemberBaseIdentitySchema, ConvertToIdentitySchema(parentSpecificSchema)) + }, + } + } + if createTimeOut > 0 { resourceSchema.Timeouts = &schema.ResourceTimeout{ Create: schema.DefaultTimeout(createTimeOut), @@ -212,7 +303,7 @@ func getResourceIamMember(d *schema.ResourceData) *cloudresourcemanager.Binding return b } -func resourceIamMemberCreate(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool) schema.CreateFunc { +func resourceIamMemberCreate(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.CreateFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -241,11 +332,24 @@ func resourceIamMemberCreate(newUpdaterFunc NewResourceIamUpdaterFunc, enableBat if k := conditionKeyFromCondition(memberBind.Condition); !k.Empty() { d.SetId(d.Id() + "/" + k.String()) } - return resourceIamMemberRead(newUpdaterFunc)(d, meta) + + if parentResourceIdentityParser != nil { + identity, err := d.Identity() + if err != nil { + return err + } + conditionTitle := "" + if memberBind.Condition != nil { + conditionTitle = memberBind.Condition.Title + } + setIamMemberResourceIdentity(identity, d, parentSpecificSchema, memberBind.Role, memberBind.Members[0], conditionTitle) + } + + return resourceIamMemberRead(newUpdaterFunc, parentSpecificSchema, parentResourceIdentityParser)(d, meta) } } -func resourceIamMemberRead(newUpdaterFunc NewResourceIamUpdaterFunc) schema.ReadFunc { +func resourceIamMemberRead(newUpdaterFunc NewResourceIamUpdaterFunc, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.ReadFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -303,11 +407,23 @@ func resourceIamMemberRead(newUpdaterFunc NewResourceIamUpdaterFunc) schema.Read if err := d.Set("condition", FlattenIamCondition(binding.Condition)); err != nil { return fmt.Errorf("Error setting condition: %s", err) } + + if parentResourceIdentityParser != nil { + identity, err := d.Identity() + if err != nil { + return err + } + conditionTitle := "" + if binding.Condition != nil { + conditionTitle = binding.Condition.Title + } + setIamMemberResourceIdentity(identity, d, parentSpecificSchema, binding.Role, eMember.Members[0], conditionTitle) + } return nil } } -func resourceIamMemberDelete(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool) schema.DeleteFunc { +func resourceIamMemberDelete(newUpdaterFunc NewResourceIamUpdaterFunc, enableBatching bool, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.DeleteFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -331,6 +447,6 @@ func resourceIamMemberDelete(newUpdaterFunc NewResourceIamUpdaterFunc, enableBat if err != nil { return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("Resource %s for IAM Member (role %q, %q)", updater.GetResourceId(), memberBind.Members[0], memberBind.Role)) } - return resourceIamMemberRead(newUpdaterFunc)(d, meta) + return resourceIamMemberRead(newUpdaterFunc, parentSpecificSchema, parentResourceIdentityParser)(d, meta) } } diff --git a/mmv1/third_party/terraform/tpgiamresource/resource_iam_policy.go b/mmv1/third_party/terraform/tpgiamresource/resource_iam_policy.go index 94b728528e79..5369b74dfc62 100644 --- a/mmv1/third_party/terraform/tpgiamresource/resource_iam_policy.go +++ b/mmv1/third_party/terraform/tpgiamresource/resource_iam_policy.go @@ -26,12 +26,15 @@ var IamPolicyBaseSchema = map[string]*schema.Schema{ }, } -func iamPolicyImport(resourceIdParser ResourceIdParserFunc) schema.StateFunc { +func iamPolicyImport(resourceIdParser ResourceIdParserFunc, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.StateFunc { return func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { if resourceIdParser == nil { return nil, errors.New("Import not supported for this IAM resource.") } config := m.(*transport_tpg.Config) + if err := setIamPolicyIdFromParentResourceIdentity(d, config, parentResourceIdentityParser); err != nil { + return nil, err + } err := resourceIdParser(d, config) if err != nil { return nil, err @@ -40,14 +43,38 @@ func iamPolicyImport(resourceIdParser ResourceIdParserFunc) schema.StateFunc { } } +// setIamPolicyIdFromParentResourceIdentity converts a resource-identity import +// into the resource id consumed by iamPolicyImport. No-op if there is no +// identity parser or d already has an id. +func setIamPolicyIdFromParentResourceIdentity(d *schema.ResourceData, config *transport_tpg.Config, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) error { + if parentResourceIdentityParser == nil || d.Id() != "" { + return nil + } + identity, err := d.Identity() + if err != nil { + return err + } + resourceID, err := parentResourceIdentityParser(d, identity, config) + if err != nil { + return err + } + d.SetId(resourceID) + return nil +} + +// setIamPolicyResourceIdentity sets parent attributes from state into identity. +func setIamPolicyResourceIdentity(identity *schema.IdentityData, d *schema.ResourceData, parentSpecificSchema map[string]*schema.Schema) { + populateIamParentIdentity(identity, d, parentSpecificSchema) +} + func ResourceIamPolicy(parentSpecificSchema map[string]*schema.Schema, newUpdaterFunc NewResourceIamUpdaterFunc, resourceIdParser ResourceIdParserFunc, options ...func(*IamSettings)) *schema.Resource { settings := NewIamSettings(options...) createTimeOut := time.Duration(settings.CreateTimeOut) * time.Minute resourceSchema := &schema.Resource{ - Create: ResourceIamPolicyCreate(newUpdaterFunc), - Read: ResourceIamPolicyRead(newUpdaterFunc), - Update: ResourceIamPolicyUpdate(newUpdaterFunc), + Create: ResourceIamPolicyCreate(newUpdaterFunc, parentSpecificSchema, settings.ParentResourceIdentityParser), + Read: ResourceIamPolicyRead(newUpdaterFunc, parentSpecificSchema, settings.ParentResourceIdentityParser), + Update: ResourceIamPolicyUpdate(newUpdaterFunc, parentSpecificSchema, settings.ParentResourceIdentityParser), Delete: ResourceIamPolicyDelete(newUpdaterFunc), // if non-empty, this will be used to send a deprecation message when the @@ -58,10 +85,20 @@ func ResourceIamPolicy(parentSpecificSchema map[string]*schema.Schema, newUpdate SchemaVersion: settings.SchemaVersion, StateUpgraders: settings.StateUpgraders, Importer: &schema.ResourceImporter{ - State: iamPolicyImport(resourceIdParser), + State: iamPolicyImport(resourceIdParser, settings.ParentResourceIdentityParser), }, UseJSONNumber: true, } + + if settings.ParentResourceIdentityParser != nil { + resourceSchema.Identity = &schema.ResourceIdentity{ + Version: 1, + SchemaFunc: func() map[string]*schema.Schema { + return ConvertToIdentitySchema(parentSpecificSchema) + }, + } + } + if createTimeOut > 0 { resourceSchema.Timeouts = &schema.ResourceTimeout{ Create: schema.DefaultTimeout(createTimeOut), @@ -70,7 +107,7 @@ func ResourceIamPolicy(parentSpecificSchema map[string]*schema.Schema, newUpdate return resourceSchema } -func ResourceIamPolicyCreate(newUpdaterFunc NewResourceIamUpdaterFunc) schema.CreateFunc { +func ResourceIamPolicyCreate(newUpdaterFunc NewResourceIamUpdaterFunc, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.CreateFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -84,11 +121,20 @@ func ResourceIamPolicyCreate(newUpdaterFunc NewResourceIamUpdaterFunc) schema.Cr } d.SetId(updater.GetResourceId()) - return ResourceIamPolicyRead(newUpdaterFunc)(d, meta) + + if parentResourceIdentityParser != nil { + identity, err := d.Identity() + if err != nil { + return err + } + setIamPolicyResourceIdentity(identity, d, parentSpecificSchema) + } + + return ResourceIamPolicyRead(newUpdaterFunc, parentSpecificSchema, parentResourceIdentityParser)(d, meta) } } -func ResourceIamPolicyRead(newUpdaterFunc NewResourceIamUpdaterFunc) schema.ReadFunc { +func ResourceIamPolicyRead(newUpdaterFunc NewResourceIamUpdaterFunc, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.ReadFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -109,11 +155,19 @@ func ResourceIamPolicyRead(newUpdaterFunc NewResourceIamUpdaterFunc) schema.Read return fmt.Errorf("Error setting policy_data: %s", err) } + if parentResourceIdentityParser != nil { + identity, err := d.Identity() + if err != nil { + return err + } + setIamPolicyResourceIdentity(identity, d, parentSpecificSchema) + } + return nil } } -func ResourceIamPolicyUpdate(newUpdaterFunc NewResourceIamUpdaterFunc) schema.UpdateFunc { +func ResourceIamPolicyUpdate(newUpdaterFunc NewResourceIamUpdaterFunc, parentSpecificSchema map[string]*schema.Schema, parentResourceIdentityParser ParentResourceIdFromIdentityParserFunc) schema.UpdateFunc { return func(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) @@ -128,7 +182,7 @@ func ResourceIamPolicyUpdate(newUpdaterFunc NewResourceIamUpdaterFunc) schema.Up } } - return ResourceIamPolicyRead(newUpdaterFunc)(d, meta) + return ResourceIamPolicyRead(newUpdaterFunc, parentSpecificSchema, parentResourceIdentityParser)(d, meta) } } diff --git a/mmv1/third_party/terraform/tpgresource/resource_test_utils.go b/mmv1/third_party/terraform/tpgresource/resource_test_utils.go index 64b3f610683b..a15deba3c94d 100644 --- a/mmv1/third_party/terraform/tpgresource/resource_test_utils.go +++ b/mmv1/third_party/terraform/tpgresource/resource_test_utils.go @@ -88,6 +88,8 @@ type ResourceDiffMock struct { Cleared map[string]interface{} Schema map[string]*schema.Schema IsForceNew bool + RawConfig cty.Value + KeysPrefix []string } func (d *ResourceDiffMock) GetChange(key string) (interface{}, interface{}) { @@ -235,3 +237,10 @@ func GetResourceAttributes(n string, s *terraform.State) (map[string]string, err return rs.Primary.Attributes, nil } + +func (d *ResourceDiffMock) GetChangedKeysPrefix(prefix string) []string { + return d.KeysPrefix +} +func (d *ResourceDiffMock) GetRawConfig() cty.Value { + return d.RawConfig +} diff --git a/mmv1/third_party/terraform/tpgresource/utils.go b/mmv1/third_party/terraform/tpgresource/utils.go index 6585aad6d3be..6cd32f740d93 100644 --- a/mmv1/third_party/terraform/tpgresource/utils.go +++ b/mmv1/third_party/terraform/tpgresource/utils.go @@ -59,6 +59,8 @@ type TerraformResourceDiff interface { Clear(string) error ForceNew(string) error SetNew(string, interface{}) error + GetChangedKeysPrefix(string) []string + GetRawConfig() cty.Value } // Contains functions that don't really belong anywhere else. @@ -154,6 +156,88 @@ func GetZoneFromDiff(d *schema.ResourceDiff, config *transport_tpg.Config) (stri return "", fmt.Errorf("%s: required field is not set", "zone") } +// getDeletionPolicyFromDiff reads the "deletion_policy" field from the given diff and falls +// back to the provider's value if not given. If the provider's value is not +// given, an error is returned. +func GetDeletionPolicyFromDiff(d *schema.ResourceDiff, config *transport_tpg.Config, resourceDefault string) (string, error) { + //if IsNull() value, then the value has not been manually configured + if d.GetRawConfig().GetAttr("deletion_policy").IsNull() { + if config.DeletionPolicy != "" { + log.Printf("[DEBUG] `deletion_policy` detected as not set within resource configuration. Falling back to configured provider default, %s", config.DeletionPolicy) + return config.DeletionPolicy, nil + } + //return the provided resource default as the final backup + log.Printf("[DEBUG] `deletion_policy` detected as not set within resource or provider configuration. Falling back to resource default, %s", resourceDefault) + return resourceDefault, nil + } + //if not null, then use/maintain usage of manually configured value + // + //this has to happen after a check for the null is made, + //as "GetOk" will always return a value once the resource is set, preventing changes + res, ok := d.GetOk("deletion_policy") + if ok { + return res.(string), nil + } + return "", fmt.Errorf("An error has occured during %s configuration. Please report this issue to the provider developers.", "`deletion_policy`") +} + +func DeletionPolicySchemaEntry(resourceDefault string) *schema.Schema { + return &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: fmt.Sprintf(`Whether Terraform will be prevented from destroying the instance. Defaults to "%s". +When a 'terraform destroy' or 'terraform apply' would delete the instance, +the command will fail if this field is set to "PREVENT" in Terraform state. +When set to "ABANDON", the command will remove the resource from Terraform +management without updating or deleting the resource in the API. +When set to "DELETE", deleting the resource is allowed. +`, resourceDefault), + } +} + +func DeletionPolicyReadDefault(d *schema.ResourceData, config *transport_tpg.Config, resourceDefault string) error { + if _, ok := d.GetOkExists("deletion_policy"); !ok { + //prioritize config's value if present + if config.DeletionPolicy != "" { + if err := d.Set("deletion_policy", config.DeletionPolicy); err != nil { + return fmt.Errorf("Error setting deletion_policy: %s", err) + } + } else { + if err := d.Set("deletion_policy", resourceDefault); err != nil { + return fmt.Errorf("Error setting deletion_policy: %s", err) + } + } + } + return nil +} + +func DeletionPolicyPreUpdate(d *schema.ResourceData, resourceSchema func() *schema.Resource) bool { + clientSideFields := map[string]bool{"deletion_policy": true} + clientSideOnly := true + for field := range resourceSchema().Schema { + if d.HasChange(field) && !clientSideFields[field] { + return false + } + } + if clientSideOnly { + log.Print("[DEBUG] Only client-side changes detected. Cancelling update operation.") + return true + } + return false +} + +func DeletionPolicyPreDelete(d *schema.ResourceData) (bool, error) { + if d.Get("deletion_policy").(string) == "PREVENT" { + return true, fmt.Errorf("cannot destroy %q without setting deletion_policy=\"DELETE\" and running `terraform apply`", d.Id()) + } + if d.Get("deletion_policy").(string) == "ABANDON" { + log.Printf("[DEBUG] deletion_policy set to \"ABANDON\", removing %q from Terraform state without deletion", d.Id()) + return true, nil + } + return false, nil +} + func GetRouterLockName(region string, router string) string { return fmt.Sprintf("router/%s/%s", region, router) } @@ -901,6 +985,20 @@ func DefaultProviderZone(_ context.Context, diff *schema.ResourceDiff, meta inte return nil } +func DefaultProviderDeletionPolicy(resourceDefault string) schema.CustomizeDiffFunc { + return func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error { + config := meta.(*transport_tpg.Config) + if dpolicy := diff.Get("deletion_policy"); dpolicy != nil { + dpolicy, err := GetDeletionPolicyFromDiff(diff, config, resourceDefault) + err = diff.SetNew("deletion_policy", dpolicy) + if err != nil { + return err + } + } + return nil + } +} + // id.UniqueId() returns a timestamp + incremental hash // This function truncates the timestamp to provide a prefix + 9 using // YYmmdd + last 3 digits of the incremental hash diff --git a/mmv1/third_party/terraform/transport/base_url.go b/mmv1/third_party/terraform/transport/base_url.go index 96fe8eea4f92..e3128afa141b 100644 --- a/mmv1/third_party/terraform/transport/base_url.go +++ b/mmv1/third_party/terraform/transport/base_url.go @@ -1,11 +1,52 @@ package transport import ( + "context" + "fmt" + "net/url" "strings" "github.com/hashicorp/terraform-provider-google/google/registry" + + "google.golang.org/api/option/internaloption" + "google.golang.org/api/transport" ) +// The transport libaray does not natively expose logic to determine whether +// the user is within mtls mode or not. They do return the mtls endpoint if +// it is enabled during client creation so we will use this logic to determine +// the mode the user is in and throw away the client they give us back. +func IsMtls() bool { + regularEndpoint := "https://mockservice.googleapis.com/v1/" + mtlsEndpoint := GetMtlsEndpoint(regularEndpoint) + _, endpoint, err := transport.NewHTTPClient(context.Background(), + internaloption.WithDefaultEndpoint(regularEndpoint), + internaloption.WithDefaultMTLSEndpoint(mtlsEndpoint), + ) + if err != nil { + return false + } + isMtls := endpoint == mtlsEndpoint + return isMtls +} + +func GetMtlsEndpoint(baseEndpoint string) string { + u, err := url.Parse(baseEndpoint) + if err != nil { + if strings.Contains(baseEndpoint, ".googleapis") { + return strings.Replace(baseEndpoint, ".googleapis", ".mtls.googleapis", 1) + } + return baseEndpoint + } + domainParts := strings.Split(u.Host, ".") + if len(domainParts) > 1 { + u.Host = fmt.Sprintf("%s.mtls.%s", domainParts[0], strings.Join(domainParts[1:], ".")) + } else { + u.Host = fmt.Sprintf("%s.mtls", domainParts[0]) + } + return u.String() +} + // Returns the base URL for a product taking into account the following rules: // 1. If there is a custom endpoint set, return that immediately. // 2. Otherwise, determine whether to use the REP url or standard url. diff --git a/mmv1/third_party/terraform/transport/config.go.tmpl b/mmv1/third_party/terraform/transport/config.go.tmpl index 176b1ab46e87..b1431963384f 100644 --- a/mmv1/third_party/terraform/transport/config.go.tmpl +++ b/mmv1/third_party/terraform/transport/config.go.tmpl @@ -177,6 +177,12 @@ func ExpandExternalCredentialsConfig(v interface{}) (*ExternalCredentials, error return config, nil } +type RPCClient struct { + ProxyAddress string + Address string + Package string +} + // Config is the configuration structure used to instantiate the Google // provider. type Config struct { @@ -199,6 +205,8 @@ type Config struct { DefaultLabels map[string]string AddTerraformAttributionLabel bool TerraformAttributionLabelAdditionStrategy string + DeletionPolicy string + // PollInterval is passed to retry.StateChangeConf in common_operation.go // It controls the interval at which we poll for successful operations PollInterval time.Duration @@ -211,26 +219,14 @@ type Config struct { TokenSource oauth2.TokenSource CustomEndpoints map[string]string - {{ range $product := $.Products }} - {{ $product.Name }}BasePath string - {{- end }} RequestBatcherServiceUsage *RequestBatcher RequestBatcherIam *RequestBatcher PreferGlobalEndpoints bool PreferRegionalEndpoints bool -} - -{{- range $product := $.Products }} -const {{ $product.Name }}BasePathKey = "{{ $product.Name }}" -{{- end }} -// Generated product base paths -var DefaultBasePaths = map[string]string{ -{{- range $product := $.Products }} - {{ $product.Name }}BasePathKey : "{{ $product.Version.BaseUrl }}", -{{- end }} + RPCClients map[string]*RPCClient } var DefaultClientScopes = []string{ @@ -382,6 +378,7 @@ func (c *Config) LoadAndValidate(ctx context.Context) error { c.PollInterval = 10 * time.Second } + c.setRPCClients() // gRPC Logging setup logger := logrus.StandardLogger() @@ -527,6 +524,21 @@ func (c *Config) getTokenSource(ctx context.Context, clientScopes []string, init return creds.TokenSource, nil } +func (c *Config) setRPCClients() { + c.RPCClients = make(map[string]*RPCClient) + {{- range $product := $.Products }} + {{- if ne $product.Version.RPCAddress "" }} + c.RPCClients["{{ $product.Name }}"] = &RPCClient{ + ProxyAddress: envvar.MultiEnvDefault([]string{ + "TF_HTTP_RPC_PROXY_ADDRESS", + }, "http://192.168.1.7:80").(string), + Address: "{{ $product.Version.RPCAddress }}", + Package: "{{ $product.Version.RPCPackage }}", + } + {{- end }} + {{- end }} +} + // StaticTokenSource is used to be able to identify static token sources without reflection. type StaticTokenSource struct { oauth2.TokenSource @@ -748,16 +760,6 @@ func RemoveBasePathVersion(url string) string { return re.ReplaceAllString(url, "$1/") } -// For a consumer of config.go that isn't a full fledged provider and doesn't -// have its own endpoint mechanism such as sweepers, init {{"{{"}}service{{"}}"}}BasePath -// values to a default. After using this, you should call config.LoadAndValidate. -func ConfigureBasePaths(c *Config) { - // Generated Products - {{- range $product := $.Products }} - c.{{ $product.Name }}BasePath = DefaultBasePaths[{{ $product.Name }}BasePathKey] - {{- end }} -} - func GetCurrentUserEmail(config *Config, userAgent string) (string, error) { ud := config.UniverseDomain if ud != "" && ud != "googleapis.com" { diff --git a/mmv1/third_party/terraform/transport/config_test.go b/mmv1/third_party/terraform/transport/config_test.go index 0a6f1a60491a..948c6bf7deb1 100644 --- a/mmv1/third_party/terraform/transport/config_test.go +++ b/mmv1/third_party/terraform/transport/config_test.go @@ -203,8 +203,6 @@ func TestConfigLoadAndValidate_accountFilePath(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - err := config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("error: %v", err) @@ -222,8 +220,6 @@ func TestConfigLoadAndValidate_accountFileJSON(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - err = config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("error: %v", err) @@ -237,8 +233,6 @@ func TestConfigLoadAndValidate_accountFileJSONInvalid(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - if config.LoadAndValidate(context.Background()) == nil { t.Fatalf("expected error, but got nil") } @@ -259,8 +253,6 @@ func TestAccConfigLoadValidate_credentials(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - err := config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("error: %v", err) @@ -289,8 +281,6 @@ func TestAccConfigLoadValidate_impersonated(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - err := config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("error: %v", err) @@ -329,8 +319,6 @@ func TestAccConfigLoadValidate_accessTokenImpersonated(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - err = config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("error: %v", err) @@ -367,8 +355,6 @@ func TestAccConfigLoadValidate_accessToken(t *testing.T) { Region: "us-central1", } - transport_tpg.ConfigureBasePaths(config) - err = config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("error: %v", err) @@ -388,8 +374,6 @@ func TestConfigLoadAndValidate_customScopes(t *testing.T) { Scopes: []string{"https://www.googleapis.com/auth/compute"}, } - transport_tpg.ConfigureBasePaths(config) - err := config.LoadAndValidate(context.Background()) if err != nil { t.Fatalf("unexpected error: %v", err) diff --git a/mmv1/third_party/terraform/transport/mtls_util.go b/mmv1/third_party/terraform/transport/mtls_util.go deleted file mode 100644 index 942c911767cc..000000000000 --- a/mmv1/third_party/terraform/transport/mtls_util.go +++ /dev/null @@ -1,46 +0,0 @@ -package transport - -import ( - "context" - "fmt" - "net/url" - "strings" - - "google.golang.org/api/option/internaloption" - "google.golang.org/api/transport" -) - -// The transport libaray does not natively expose logic to determine whether -// the user is within mtls mode or not. They do return the mtls endpoint if -// it is enabled during client creation so we will use this logic to determine -// the mode the user is in and throw away the client they give us back. -func IsMtls() bool { - regularEndpoint := "https://mockservice.googleapis.com/v1/" - mtlsEndpoint := GetMtlsEndpoint(regularEndpoint) - _, endpoint, err := transport.NewHTTPClient(context.Background(), - internaloption.WithDefaultEndpoint(regularEndpoint), - internaloption.WithDefaultMTLSEndpoint(mtlsEndpoint), - ) - if err != nil { - return false - } - isMtls := endpoint == mtlsEndpoint - return isMtls -} - -func GetMtlsEndpoint(baseEndpoint string) string { - u, err := url.Parse(baseEndpoint) - if err != nil { - if strings.Contains(baseEndpoint, ".googleapis") { - return strings.Replace(baseEndpoint, ".googleapis", ".mtls.googleapis", 1) - } - return baseEndpoint - } - domainParts := strings.Split(u.Host, ".") - if len(domainParts) > 1 { - u.Host = fmt.Sprintf("%s.mtls.%s", domainParts[0], strings.Join(domainParts[1:], ".")) - } else { - u.Host = fmt.Sprintf("%s.mtls", domainParts[0]) - } - return u.String() -} diff --git a/mmv1/third_party/terraform/transport/mtls_util_test.go b/mmv1/third_party/terraform/transport/mtls_util_test.go deleted file mode 100644 index 25117491ca75..000000000000 --- a/mmv1/third_party/terraform/transport/mtls_util_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package transport - -import ( - "strings" - "testing" -) - -func TestUnitMtls_urlSwitching(t *testing.T) { - t.Parallel() - for key, bp := range DefaultBasePaths { - url := GetMtlsEndpoint(bp) - if !strings.Contains(url, ".mtls.") { - t.Errorf("%s: mtls conversion unsuccessful preconv - %s postconv - %s", key, bp, url) - } - } -} diff --git a/mmv1/third_party/terraform/transport/transport.go b/mmv1/third_party/terraform/transport/transport.go index d6dae5f69c6c..11defd51a335 100644 --- a/mmv1/third_party/terraform/transport/transport.go +++ b/mmv1/third_party/terraform/transport/transport.go @@ -27,6 +27,9 @@ type SendRequestOptions struct { Headers http.Header ErrorRetryPredicates []RetryErrorPredicateFunc ErrorAbortPredicates []RetryErrorPredicateFunc + // RPC related opts + Product string + RPCService string } func SendRequest(opt SendRequestOptions) (map[string]interface{}, error) { @@ -118,6 +121,110 @@ func SendRequest(opt SendRequestOptions) (map[string]interface{}, error) { return result, nil } +func SendRequestRPC(opt SendRequestOptions) (map[string]interface{}, error) { + if opt.Config == nil || opt.Config.Client == nil { + return nil, fmt.Errorf("http client is nil for request to rpc proxy") + } + if opt.Product == "" || opt.Config.RPCClients[opt.Product] == nil { + return nil, fmt.Errorf("rpc client is nil for request to rpc proxy; product is %q", opt.Product) + } + + reqHeaders := opt.Headers + if reqHeaders == nil { + reqHeaders = make(http.Header) + } + reqHeaders.Set("User-Agent", opt.UserAgent) + reqHeaders.Set("Content-Type", "application/json") + + if opt.Timeout == 0 { + opt.Timeout = DefaultRequestTimeout + } + + var res *http.Response + err := Retry(RetryOptions{ + RetryFunc: func() error { + var reqJsonStr string + if opt.Body != nil { + b, err := json.Marshal(opt.Body) + if err != nil { + return err + } + reqJsonStr = string(b) + } + + reqBody := map[string]interface{}{ + "targetAddress": opt.Config.RPCClients[opt.Product].Address, + "packageName": opt.Config.RPCClients[opt.Product].Package, + "serviceName": opt.RPCService, + "methodName": opt.Method, + "requestJson": reqJsonStr, + } + + var buf bytes.Buffer + if reqBody != nil { + err := json.NewEncoder(&buf).Encode(reqBody) + if err != nil { + return err + } + } + + req, err := http.NewRequest("POST", opt.Config.RPCClients[opt.Product].ProxyAddress+"/handleRPC", &buf) + if err != nil { + return err + } + + req.Header = reqHeaders + res, err = opt.Config.Client.Do(req) + if err != nil { + return err + } + + if err := googleapi.CheckResponse(res); err != nil { + googleapi.CloseBody(res) + return err + } + + return nil + }, + Timeout: opt.Timeout, + ErrorRetryPredicates: opt.ErrorRetryPredicates, + ErrorAbortPredicates: opt.ErrorAbortPredicates, + }) + if err != nil { + return nil, err + } + + if res == nil { + return nil, fmt.Errorf("Unable to parse server response. This is most likely a terraform problem, please file a bug at https://github.com/hashicorp/terraform-provider-google/issues.") + } + + // The defer call must be made outside of the retryFunc otherwise it's closed too soon. + defer googleapi.CloseBody(res) + + // 204 responses will have no body, so we're going to error with "EOF" if we + // try to parse it. Instead, we can just return nil. + if res.StatusCode == 204 { + return nil, nil + } + var proxyResult map[string]interface{} + if err := json.NewDecoder(res.Body).Decode(&proxyResult); err != nil { + return nil, err + } + + if errMsg, ok := proxyResult["errorMessage"].(string); ok && errMsg != "" { + return nil, fmt.Errorf("RPC proxy returned error: %s", errMsg) + } + + var result map[string]interface{} + if respJsonStr, ok := proxyResult["responseJson"].(string); ok && respJsonStr != "" { + if err := json.Unmarshal([]byte(respJsonStr), &result); err != nil { + return nil, fmt.Errorf("Failed to unmarshal responseJson from proxy: %v", err) + } + } + + return result, nil +} + func AddQueryParams(rawurl string, params map[string]string) (string, error) { u, err := url.Parse(rawurl) if err != nil { @@ -202,6 +309,7 @@ func IsApiNotEnabledError(err error) bool { type ListPagesOptions struct { Config *Config TempData *schema.ResourceData + Resource *schema.Resource ListURL string BillingProject string UserAgent string @@ -250,18 +358,20 @@ func ListPages(opt ListPagesOptions) error { items, ok = res["items"].([]interface{}) } if ok { + // Capture the seed state once per page. State() returns a snapshot, so reads + // here are unaffected by anything the flattener writes on prior iterations. + seedState := opt.TempData.State() for _, item := range items { itemMap, ok := item.(map[string]interface{}) if !ok { return fmt.Errorf("expected item to be map[string]interface{}, got %T", item) } - err = opt.Flattener(itemMap, opt.TempData, opt.Config) - if err != nil { + itemResourceData := opt.Resource.Data(seedState) + if err := opt.Flattener(itemMap, itemResourceData, opt.Config); err != nil { return fmt.Errorf("Error flattening instance: %s", err) } - err = opt.Callback(opt.TempData) - if err != nil { + if err := opt.Callback(itemResourceData); err != nil { return err } } diff --git a/mmv1/third_party/terraform/transport/transport_test_utils.go b/mmv1/third_party/terraform/transport/transport_test_utils.go index 462dfcdafc44..97cf123c6fce 100644 --- a/mmv1/third_party/terraform/transport/transport_test_utils.go +++ b/mmv1/third_party/terraform/transport/transport_test_utils.go @@ -37,8 +37,6 @@ func BootstrapConfig(t *testing.T) *Config { Zone: envvar.GetTestZoneFromEnv(), } - ConfigureBasePaths(config) - if err := config.LoadAndValidate(context.Background()); err != nil { t.Fatalf("Bootstrapping failed. Unable to load test config: %s", err) } diff --git a/mmv1/third_party/terraform/website/docs/d/cloud_run_service.html.markdown b/mmv1/third_party/terraform/website/docs/d/cloud_run_service.html.markdown deleted file mode 100644 index dbd57f2ec63a..000000000000 --- a/mmv1/third_party/terraform/website/docs/d/cloud_run_service.html.markdown +++ /dev/null @@ -1,37 +0,0 @@ ---- -subcategory: "Cloud Run" -description: |- - Get information about a Google Cloud Run Service. ---- - -# google_cloud_run_service - -Get information about a Google Cloud Run Service. For more information see -the [official documentation](https://cloud.google.com/run/docs/) -and [API](https://cloud.google.com/run/docs/apis). - -## Example Usage - -```hcl -data "google_cloud_run_service" "run-service" { - name = "my-service" - location = "us-central1" -} -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) The name of the Cloud Run Service. - -* `location` - (Required) The location of the cloud run instance. eg us-central1 - -- - - - -* `project` - (Optional) The project in which the resource belongs. If it - is not provided, the provider project is used. - -## Attributes Reference - -See [google_cloud_run_service](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_service#argument-reference) resource for details of the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/d/compute_region_ssl_policy.html.markdown b/mmv1/third_party/terraform/website/docs/d/compute_region_ssl_policy.html.markdown new file mode 100644 index 000000000000..92e2ba532da5 --- /dev/null +++ b/mmv1/third_party/terraform/website/docs/d/compute_region_ssl_policy.html.markdown @@ -0,0 +1,54 @@ +--- +subcategory: "Compute Engine" +description: |- + Gets a Regional SSL Policy within GCE, for use with Target HTTPS and Target SSL Proxies. +--- + +# google_compute_ssl_policy + +Gets a Regional SSL Policy within GCE from its name, for use with Target HTTPS and Target SSL Proxies. + For more information see [the official documentation](https://cloud.google.com/compute/docs/load-balancing/ssl-policies). + +## Example Usage + +```tf +data "google_compute_region_ssl_policy" "my-ssl-policy" { + name = "production-ssl-policy" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the SSL Policy. + +- - - + +* `region` - (Optional) The region in which the resource belongs. If it + is not provided, the provider region is used. + +* `project` - (Optional) The ID of the project in which the resource belongs. If it + is not provided, the provider project is used. + +## Attributes Reference + +In addition to the arguments listed above, the following attributes are exported: + +* `enabled_features` - The set of enabled encryption ciphers as a result of the policy config + +* `description` - Description of this SSL Policy. + +* `min_tls_version` - The minimum supported TLS version of this policy. + +* `post_quantum_key_exchange` - The post-quantum key exchange setting of this policy. + +* `profile` - The Google-curated or custom profile used by this policy. + +* `custom_features` - If the `profile` is `CUSTOM`, these are the custom encryption + ciphers supported by the profile. If the `profile` is *not* `CUSTOM`, this + attribute will be empty. + +* `fingerprint` - Fingerprint of this resource. + +* `self_link` - The URI of the created resource. \ No newline at end of file diff --git a/mmv1/third_party/terraform/website/docs/d/compute_service_attachment.html.markdown b/mmv1/third_party/terraform/website/docs/d/compute_service_attachment.html.markdown new file mode 100644 index 000000000000..c3c37542b249 --- /dev/null +++ b/mmv1/third_party/terraform/website/docs/d/compute_service_attachment.html.markdown @@ -0,0 +1,39 @@ +--- +subcategory: "Compute Engine" +description: |- + A data source to retrieve a service attachment. +--- + +# `google_compute_service_attachment` + +Get a specific [service attachment](https://cloud.google.com/vpc/docs/configure-private-service-connect-services) within a region. For more information see the +[official documentation](https://cloud.google.com/vpc/docs/configure-private-service-connect-services) +and [API](https://cloud.google.com/compute/docs/reference/rest/v1/serviceAttachments/get). + +## Example Usage + +```hcl +data "google_compute_service_attachment" "default" { + project = "my-project" + name = "my-service-attachment" + region = "us-west2" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the service attachment to retrieve. + +--- + +* `region` - (Optional) The region in which the service attachment resides. + If it is not provided, the provider region is used. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + +## Attributes Reference + +See [google_compute_service_attachment](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_service_attachment#attributes-reference) resource for details of the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/d/compute_ssl_policy.html.markdown b/mmv1/third_party/terraform/website/docs/d/compute_ssl_policy.html.markdown index bf4efc6f1020..9c7be187a2cc 100644 --- a/mmv1/third_party/terraform/website/docs/d/compute_ssl_policy.html.markdown +++ b/mmv1/third_party/terraform/website/docs/d/compute_ssl_policy.html.markdown @@ -38,6 +38,8 @@ In addition to the arguments listed above, the following attributes are exported * `min_tls_version` - The minimum supported TLS version of this policy. +* `post_quantum_key_exchange` - The post-quantum key exchange setting of this policy. + * `profile` - The Google-curated or custom profile used by this policy. * `custom_features` - If the `profile` is `CUSTOM`, these are the custom encryption diff --git a/mmv1/third_party/terraform/website/docs/d/iap_client.html.markdown b/mmv1/third_party/terraform/website/docs/d/iap_client.html.markdown deleted file mode 100644 index 4fbd593b894b..000000000000 --- a/mmv1/third_party/terraform/website/docs/d/iap_client.html.markdown +++ /dev/null @@ -1,34 +0,0 @@ ---- -subcategory: "Identity-Aware Proxy" -description: |- - Contains the data that describes an Identity Aware Proxy owned client. ---- -# google_iap_client - -Get info about a Google Cloud IAP Client. - -## Example Usage - -```tf -data "google_project" "project" { - project_id = "foobar" -} - -data "google_iap_client" "project_client" { - brand = "projects/${data.google_project.project.number}/brands/[BRAND_NUMBER]" - client_id = FOO.apps.googleusercontent.com -} - -``` - -## Argument Reference - -The following arguments are supported: - -* `brand` - (Required) The name of the brand. - -* `client_id` - (Required) The client_id of the brand. - -## Attributes Reference - -See [google_iap_client](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/iap_client) resource for details of the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/d/logging_log_view.html.markdown b/mmv1/third_party/terraform/website/docs/d/logging_log_view.html.markdown new file mode 100644 index 000000000000..f5852269c01e --- /dev/null +++ b/mmv1/third_party/terraform/website/docs/d/logging_log_view.html.markdown @@ -0,0 +1,38 @@ +--- +subcategory: "Cloud (Stackdriver) Logging" +description: |- + Get information about a Google Cloud Logging Log View. +--- + +# google_logging_log_view + +Get information about a Google Cloud Logging Log View. For more information, see the +[official documentation](https://cloud.google.com/logging/docs/apis) +and [API](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.locations.buckets.views). + +## Example Usage + +```hcl +data "google_logging_log_view" "default" { + parent = "projects/my-project" + location = "global" + bucket = "_Default" + name = "my-view" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `parent` - (Required) The parent of the resource. + +* `location` - (Required) The location of the resource. + +* `bucket` - (Required) The bucket of the resource. + +* `name` - (Required) The resource name of the view. + +## Attributes Reference + +See [google_logging_log_view](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/logging_log_view) resource for details of the available attributes. \ No newline at end of file diff --git a/mmv1/third_party/terraform/website/docs/d/oracle_database_goldengate_deployment_environments.html.markdown b/mmv1/third_party/terraform/website/docs/d/oracle_database_goldengate_deployment_environments.html.markdown new file mode 100644 index 000000000000..6586418e444b --- /dev/null +++ b/mmv1/third_party/terraform/website/docs/d/oracle_database_goldengate_deployment_environments.html.markdown @@ -0,0 +1,59 @@ +--- +subcategory: "Oracle Database" +description: |- + List all GoldenGate Deployment Environments in a location. +--- + +# google_oracle_database_goldengate_deployment_environments + +List all GoldenGate Deployment Environments in a location. + +For more information see the +[API](https://cloud.google.com/oracle/database/docs/reference/rest/v1/projects.locations.goldengateDeploymentEnvironments). + +## Example Usage + +```hcl +data "google_oracle_database_goldengate_deployment_environments" "my_environments" { + location = "us-east4" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `location` - (Required) The location of resource. + +* `project` - (Optional) The project to which the resource belongs. If it + is not provided, the provider project is used. + +## Attributes reference + +The following attributes are exported: + +* `goldengate_deployment_environments` - List of GoldenGate Deployment Environments. Structure is [documented below](#nested_goldengate_deployment_environments). + + The `goldengate_deployment_environments` block supports: + +* `name` - The name of the GoldenGate Deployment Environment resource. Format: `projects/{project}/locations/{location}/goldenGateDeploymentEnvironments/{golden_gate_deployment_environment}` + +* `category` - The category of the GoldenGate Deployment Environment resource. + +* `display_name` - The display name of the GoldenGate Deployment Environment resource. + +* `default_cpu_core_count` - The default CPU core count of the GoldenGate Deployment Environment resource. + +* `environment_type` - The environment type of the GoldenGate Deployment Environment resource. + +* `auto_scaling_enabled` - Whether auto scaling is enabled by default for the GoldenGate Deployment Environment resource. + +* `max_cpu_core_count` - The max CPU core count of the GoldenGate Deployment Environment resource. + +* `memory_gb_per_cpu_core` - The memory per CPU core in GBs of the GoldenGate Deployment Environment resource. + +* `min_cpu_core_count` - The min CPU core count of the GoldenGate Deployment Environment resource. + +* `network_bandwidth_gbps_per_cpu_core` - The network bandwidth per CPU core in Gbps of the GoldenGate Deployment Environment resource. + +* `storage_usage_limit_gb_per_cpu_core` - The storage usage limit per CPU core in GBs of the GoldenGate Deployment Environment resource. diff --git a/mmv1/third_party/terraform/website/docs/d/storage_control_folder_intelligence_config.html.markdown b/mmv1/third_party/terraform/website/docs/d/storage_control_folder_intelligence_config.html.markdown deleted file mode 100644 index 5ad88b38d6f2..000000000000 --- a/mmv1/third_party/terraform/website/docs/d/storage_control_folder_intelligence_config.html.markdown +++ /dev/null @@ -1,32 +0,0 @@ ---- -subcategory: "Cloud Storage Control" -description: |- - Gets a Folder Storage Intelligence config. ---- - -# google_storage_control_folder_intelligence_config - -Use this data source to get information about a Folder Storage Intelligence config resource. -See [the official documentation](https://cloud.google.com/storage/docs/storage-intelligence/overview#resource) -and -[API](https://cloud.google.com/storage/docs/json_api/v1/intelligenceConfig). - - -## Example Usage - -```hcl -data "google_storage_control_folder_intelligence_config" "sample-config" { - name = "123456789" -} -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) The number of GCP folder. - - -## Attributes Reference - -See [google_storage_control_folder_intelligence_config](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_control_folder_intelligence_config#argument-reference) resource for details of the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/d/storage_control_organization_intelligence_config.html.markdown b/mmv1/third_party/terraform/website/docs/d/storage_control_organization_intelligence_config.html.markdown deleted file mode 100644 index 2fb52fa2d2af..000000000000 --- a/mmv1/third_party/terraform/website/docs/d/storage_control_organization_intelligence_config.html.markdown +++ /dev/null @@ -1,32 +0,0 @@ ---- -subcategory: "Cloud Storage Control" -description: |- - Gets a Organization Storage Intelligence config. ---- - -# google_storage_control_organization_intelligence_config - -Use this data source to get information about a Organization Storage Intelligence config resource. -See [the official documentation](https://cloud.google.com/storage/docs/storage-intelligence/overview#resource) -and -[API](https://cloud.google.com/storage/docs/json_api/v1/intelligenceConfig). - - -## Example Usage - -```hcl -data "google_storage_control_organization_intelligence_config" "sample-config" { - name = "123456789" -} -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) The id of GCP organization. - - -## Attributes Reference - -See [google_storage_control_organization_intelligence_config](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_control_organization_intelligence_config#argument-reference) resource for details of the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/d/storage_control_project_intelligence_config.html.markdown b/mmv1/third_party/terraform/website/docs/d/storage_control_project_intelligence_config.html.markdown deleted file mode 100644 index c687cdea7e10..000000000000 --- a/mmv1/third_party/terraform/website/docs/d/storage_control_project_intelligence_config.html.markdown +++ /dev/null @@ -1,32 +0,0 @@ ---- -subcategory: "Cloud Storage Control" -description: |- - Gets a Project Storage Intelligence config. ---- - -# google_storage_control_project_intelligence_config - -Use this data source to get information about a Project Storage Intelligence config resource. -See [the official documentation](https://cloud.google.com/storage/docs/storage-intelligence/overview#resource) -and -[API](https://cloud.google.com/storage/docs/json_api/v1/intelligenceConfig). - - -## Example Usage - -```hcl -data "google_storage_control_project_intelligence_config" "sample-config" { - name = "my-project" -} -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) The name or number of the GCP project. - - -## Attributes Reference - -See [google_storage_control_project_intelligence_config](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_control_project_intelligence_config#argument-reference) resource for details of the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/d/vmwareengine_datastore_html.markdown b/mmv1/third_party/terraform/website/docs/d/vmwareengine_datastore_html.markdown deleted file mode 100644 index bc5f2cd1b422..000000000000 --- a/mmv1/third_party/terraform/website/docs/d/vmwareengine_datastore_html.markdown +++ /dev/null @@ -1,32 +0,0 @@ ---- -subcategory: "Cloud VMware Engine" -description: |- - Get information about a datastore. ---- - -# google\_vmwareengine\_datastore - -Use this data source to get details about a datastore resource. - -To get more information about datastore, see: -* [API documentation](https://docs.cloud.google.com/vmware-engine/docs/vmware-ecosystem/concepts-nfs-datastores-overview) - -## Example Usage - -```hcl -data "google_vmwareengine_datastore" "test_ds" { - name = "example-ds" - location = "us-west2" -} -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) Name of the resource. -* `location` - (Required) either regional or zonal location of the resource. - -## Attributes Reference - -See [google_vmwareengine_datastore](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/vmwareengine_datastore#attributes-reference) resource for details of all the available attributes. diff --git a/mmv1/third_party/terraform/website/docs/list-resources/google_storage_bucket.html.markdown b/mmv1/third_party/terraform/website/docs/list-resources/google_storage_bucket.html.markdown new file mode 100644 index 000000000000..45a55906e5b2 --- /dev/null +++ b/mmv1/third_party/terraform/website/docs/list-resources/google_storage_bucket.html.markdown @@ -0,0 +1,50 @@ +--- +subcategory: "Cloud Storage" +description: |- + List Google Cloud Storage buckets in a project for use with terraform query + and .tfquery.hcl files. +--- + +# google_storage_bucket (list) + +Lists Google Cloud Storage **buckets** in a project for use with +[`terraform query`](https://developer.hashicorp.com/terraform/cli/commands/query) and +**`.tfquery.hcl`** files. Results correspond to existing +[`google_storage_bucket`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket) +managed resources. + +For how list resources work in this provider, file layout, Terraform version requirements, and +shared `list` block arguments, refer to the guide +[Use list resources with terraform query (Google Cloud provider)](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/using_list_resources_with_terraform_query). + +## Example + +```hcl +list "google_storage_bucket" "all" { + provider = google + + config { + # Optional. Defaults to the provider project when omitted. + # project = "other-project" + } +} +``` + +Run `terraform query` from the directory that contains the `.tfquery.hcl` file. + +## Configuration (`config` block) + +* `project` - (Optional) Project ID to list buckets from. If unset, the provider's configured + default project is used, matching the managed resource behavior. + +## Results + +By default each result includes **resource identity** for `google_storage_bucket` (see +[Resource identity](https://developer.hashicorp.com/terraform/language/block/import#identity)): + +* `name` - Bucket name. +* `project` - Project ID. + +With `include_resource = true` on the `list` block, results also include the full resource-style +attributes documented for the managed +[`google_storage_bucket` resource](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket#attributes-reference). \ No newline at end of file diff --git a/mmv1/third_party/terraform/website/docs/r/apigee_api.html.markdown b/mmv1/third_party/terraform/website/docs/r/apigee_api.html.markdown index 6193bf056d3f..8efce648d710 100644 --- a/mmv1/third_party/terraform/website/docs/r/apigee_api.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/apigee_api.html.markdown @@ -53,6 +53,14 @@ The following arguments are supported: (Required) Path to the config zip bundle. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/apigee_flowhook.html.markdown b/mmv1/third_party/terraform/website/docs/r/apigee_flowhook.html.markdown index 10bfd452b5b5..dbe396035941 100644 --- a/mmv1/third_party/terraform/website/docs/r/apigee_flowhook.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/apigee_flowhook.html.markdown @@ -44,6 +44,14 @@ The following arguments are supported: (Optional) Flag that specifies whether execution should continue if the flow hook throws an exception. Set to true to continue execution. Set to false to stop execution if the flow hook throws an exception. Defaults to true. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/apigee_keystores_aliases_pkcs12.html.markdown b/mmv1/third_party/terraform/website/docs/r/apigee_keystores_aliases_pkcs12.html.markdown index 2e5879d69f4d..fbc16311823b 100644 --- a/mmv1/third_party/terraform/website/docs/r/apigee_keystores_aliases_pkcs12.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/apigee_keystores_aliases_pkcs12.html.markdown @@ -39,6 +39,14 @@ The following arguments are supported: (Required) PKCS12 file content +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - * `password` - diff --git a/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow.html.markdown b/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow.html.markdown index bec53e7f9b7a..ef14b92f30b5 100644 --- a/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow.html.markdown @@ -126,6 +126,14 @@ The following arguments are supported: (Required) Path to the config zip bundle. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - diff --git a/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow_deployment.html.markdown b/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow_deployment.html.markdown index e512322624e8..35642fbaa086 100644 --- a/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow_deployment.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/apigee_sharedflow_deployment.html.markdown @@ -36,6 +36,13 @@ The following arguments are supported: (Required) Revision of the Sharedflow to be deployed. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. - - - diff --git a/mmv1/third_party/terraform/website/docs/r/apikeys_key.html.markdown b/mmv1/third_party/terraform/website/docs/r/apikeys_key.html.markdown index 261ce7030cf0..6b7d0d2c51d0 100644 --- a/mmv1/third_party/terraform/website/docs/r/apikeys_key.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/apikeys_key.html.markdown @@ -155,6 +155,13 @@ The following arguments are supported: * `service_account_email` - (Optional) The email of the service account the key is bound to. If this field is specified, the key is a service account bound key and auth enabled. See [Documentation](https://cloud.google.com/docs/authentication/api-keys?#api-keys-bound-sa) for more details. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. diff --git a/mmv1/third_party/terraform/website/docs/r/assured_workloads_workload.html.markdown b/mmv1/third_party/terraform/website/docs/r/assured_workloads_workload.html.markdown index 7fc0c7c39137..8444bfba4e24 100644 --- a/mmv1/third_party/terraform/website/docs/r/assured_workloads_workload.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/assured_workloads_workload.html.markdown @@ -200,6 +200,13 @@ Please refer to the field `effective_labels` for all of the labels present on th * `workload_options` - (Optional) Optional. Used to specify certain options for a workload during workload creation - currently only supporting KAT Optionality for Regional Controls workloads. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. diff --git a/mmv1/third_party/terraform/website/docs/r/bigquery_table.html.markdown b/mmv1/third_party/terraform/website/docs/r/bigquery_table.html.markdown index e3afb3209553..54cf7374dcdc 100644 --- a/mmv1/third_party/terraform/website/docs/r/bigquery_table.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/bigquery_table.html.markdown @@ -128,6 +128,14 @@ The following arguments are supported: * `effective_labels` - All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + * `schema` - (Optional) A JSON schema for the table. ~>**NOTE:** Because this field expects a JSON string, any changes to the diff --git a/mmv1/third_party/terraform/website/docs/r/bigtable_authorized_view.html.markdown b/mmv1/third_party/terraform/website/docs/r/bigtable_authorized_view.html.markdown index a08d26f7039d..a5d7d3d096cd 100644 --- a/mmv1/third_party/terraform/website/docs/r/bigtable_authorized_view.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/bigtable_authorized_view.html.markdown @@ -98,6 +98,13 @@ The following arguments are supported: If not provided, currently deletion protection will be set to UNPROTECTED as it is the API default value. Note this field configs the deletion protection provided by the API in the backend, and should not be confused with Terraform-side deletion protection. * `subset_view` - (Optional) An AuthorizedView permitting access to an explicit subset of a Table. Structure is documented below. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ----- diff --git a/mmv1/third_party/terraform/website/docs/r/bigtable_gc_policy.html.markdown b/mmv1/third_party/terraform/website/docs/r/bigtable_gc_policy.html.markdown index d6490d4f72b3..4256e1ec5647 100644 --- a/mmv1/third_party/terraform/website/docs/r/bigtable_gc_policy.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/bigtable_gc_policy.html.markdown @@ -161,10 +161,15 @@ The following arguments are supported: * `gc_rules` - (Optional) Serialized JSON object to represent a more complex GC policy. Conflicts with `mode`, `max_age` and `max_version`. Conflicts with `mode`, `max_age` and `max_version`. -* `deletion_policy` - (Optional) The deletion policy for the GC policy. - Setting ABANDON allows the resource to be abandoned rather than deleted. This is useful for GC policy as it cannot be deleted in a replicated instance. - - Possible values are: `ABANDON`. +* `deletion_policy` - (Optional) The deletion policy for the GC policy. Setting ABANDON allows the resource + to be abandoned rather than deleted. This is useful for GC policy as it cannot be deleted + in a replicated instance. + + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "DELETE" or "", deleting the resource is allowed. + + Possible values: PREVENT, ABANDON, DELETE. * `ignore_warnings` - (Optional) Boolean for whether to allow ignoring warnings when updating the gc policy. Setting this to `true` allows relaxing the gc policy for replicated clusters by up to 90 days, but keep in mind this may increase how long clusters are inconsistent. Make sure diff --git a/mmv1/third_party/terraform/website/docs/r/bigtable_instance.html.markdown b/mmv1/third_party/terraform/website/docs/r/bigtable_instance.html.markdown index 4f524b69f0ac..a23fc42efcdd 100644 --- a/mmv1/third_party/terraform/website/docs/r/bigtable_instance.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/bigtable_instance.html.markdown @@ -114,8 +114,18 @@ to default to the backend value. See [structure below](#nested_cluster). * `effective_labels` - All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + * `tags` - (Optional) A set of key/value label pairs to assign to the resource. Tags must follow the requirements at [create and manage tags](https://docs.cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing). +* `edition` (Optional) The edition of the Bigtable instance. One of "ENTERPRISE" or "ENTERPRISE_PLUS". Defaults to "ENTERPRISE". Details can be found at the [Cloud Bigtable editions page](https://docs.cloud.google.com/bigtable/docs/editions-overview). + ----- The `cluster` block supports the following arguments: diff --git a/mmv1/third_party/terraform/website/docs/r/bigtable_table.html.markdown b/mmv1/third_party/terraform/website/docs/r/bigtable_table.html.markdown index ef0f71085b91..a8a674bad295 100644 --- a/mmv1/third_party/terraform/website/docs/r/bigtable_table.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/bigtable_table.html.markdown @@ -101,6 +101,13 @@ to delete/recreate the entire `google_bigtable_table` resource. * `change_stream_retention` - (Optional) Duration to retain change stream data for the table. Set to 0 to disable. Must be between 1 and 7 days. * `automated_backup_policy` - (Optional) Defines an automated backup policy for a table, specified by Retention Period and Frequency. To _create_ a table with automated backup disabled, either omit the automated_backup_policy argument, or set both Retention Period and Frequency properties to "0". To disable automated backup on an _existing_ table that has automated backup enabled, set _both_ Retention Period and Frequency properties to "0". When updating an existing table, to modify the Retention Period or Frequency properties of the resource's automated backup policy, set the respective property to a non-zero value. If the automated_backup_policy argument is not provided in the configuration on update, the resource's automated backup policy will _not_ be modified. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ----- diff --git a/mmv1/third_party/terraform/website/docs/r/cloudbuild_worker_pool.html.markdown b/mmv1/third_party/terraform/website/docs/r/cloudbuild_worker_pool.html.markdown index 50005f52291f..e81daf78c5d1 100644 --- a/mmv1/third_party/terraform/website/docs/r/cloudbuild_worker_pool.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/cloudbuild_worker_pool.html.markdown @@ -92,7 +92,13 @@ The following arguments are supported: * `worker_config` - (Optional) Configuration to be used for a creating workers in the `WorkerPool`. Structure is [documented below](#nested_worker_config). - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `network_config` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/clouddeploy_delivery_pipeline.html.markdown b/mmv1/third_party/terraform/website/docs/r/clouddeploy_delivery_pipeline.html.markdown index 8a361fa093ca..394c46d880b4 100644 --- a/mmv1/third_party/terraform/website/docs/r/clouddeploy_delivery_pipeline.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/clouddeploy_delivery_pipeline.html.markdown @@ -274,7 +274,13 @@ Please refer to the field `effective_labels` for all of the labels present on th * `suspended` - (Optional) When suspended, no new releases or rollouts can be created, but in-progress ones will complete. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `serial_pipeline` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/clouddeploy_target.html.markdown b/mmv1/third_party/terraform/website/docs/r/clouddeploy_target.html.markdown index 148a70be6de9..f2dabe7393dc 100644 --- a/mmv1/third_party/terraform/website/docs/r/clouddeploy_target.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/clouddeploy_target.html.markdown @@ -189,7 +189,13 @@ Please refer to the field `effective_labels` for all of the labels present on th * `run` - (Optional) Information specifying a Cloud Run deployment target. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `anthos_cluster` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/cloudfunctions_function.html.markdown b/mmv1/third_party/terraform/website/docs/r/cloudfunctions_function.html.markdown index 5e046ace814b..8a5988975e82 100644 --- a/mmv1/third_party/terraform/website/docs/r/cloudfunctions_function.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/cloudfunctions_function.html.markdown @@ -183,6 +183,13 @@ Please refer to the field 'effective_labels' for all of the labels present on th * `on_deploy_update_policy` - (Optional) Security patches are only applied when a function is redeployed. This should be specified as an empty block and cannot be set alongside `automatic_update_policy`. Structure is [documented below](#nested_on_deploy_update_policy). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `event_trigger` block supports: * `event_type` - (Required) The type of event to observe. For example: `"google.storage.object.finalize"`. diff --git a/mmv1/third_party/terraform/website/docs/r/composer_environment.html.markdown b/mmv1/third_party/terraform/website/docs/r/composer_environment.html.markdown index 8fe18d19f732..290529e334db 100644 --- a/mmv1/third_party/terraform/website/docs/r/composer_environment.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/composer_environment.html.markdown @@ -458,6 +458,14 @@ The following arguments are supported: (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + * `storage_config` - (Optional) Configuration options for storage used by the environment. Structure is diff --git a/mmv1/third_party/terraform/website/docs/r/composer_user_workloads_secret.html.markdown b/mmv1/third_party/terraform/website/docs/r/composer_user_workloads_secret.html.markdown index 337ced525b87..0ee115ba1cbe 100644 --- a/mmv1/third_party/terraform/website/docs/r/composer_user_workloads_secret.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/composer_user_workloads_secret.html.markdown @@ -66,6 +66,13 @@ The following arguments are supported: The values for all keys have to be base64-encoded strings. For details see: https://kubernetes.io/docs/concepts/configuration/secret/ +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/compute_attached_disk.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_attached_disk.html.markdown index 4ec98cbfab7e..27b50dd0eaa8 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_attached_disk.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_attached_disk.html.markdown @@ -113,6 +113,13 @@ The following arguments are supported: "SCSI" "NVME" +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_disk_async_replication.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_disk_async_replication.html.markdown index e552268ac51a..774c7ec44870 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_disk_async_replication.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_disk_async_replication.html.markdown @@ -49,6 +49,13 @@ The following arguments are supported: * `secondary_disk` - (Required) The secondary disk (target of replication). You can specify only one value. Structure is documented below. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `secondary_disk` block includes: * `disk` - (Required) The secondary disk. diff --git a/mmv1/third_party/terraform/website/docs/r/compute_instance.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_instance.html.markdown index cf8e167cde7e..ef349f025174 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_instance.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_instance.html.markdown @@ -256,6 +256,13 @@ is desired, you will need to modify your state file manually using * `erase_windows_vss_signature` - (optional) [Beta](../guides/provider_versions.html.markdown) Specifies whether the disks restored from source snapshots or source machine image should erase Windows specific VSS signature. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + --- The `boot_disk` block supports: @@ -472,6 +479,10 @@ is desired, you will need to modify your state file manually using array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range). +* `alias_ipv6_range` - (Optional) [Beta] An + array of alias IPv6 ranges for this network interface. Can only be specified for network + interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range). + * `nic_type` - (Optional) The type of vNIC to be used on this interface. Possible values: GVNIC, VIRTIO_NET, IDPF, MRDMA, IRDMA, IDPF * `network_attachment` - (Optional) The URL of the network attachment that this interface should connect to in the following format: `projects/{projectNumber}/regions/{region_name}/networkAttachments/{network_attachment_name}`. @@ -685,9 +696,9 @@ specified, then this instance will have no external IPv6 Internet access. Struct The `confidential_instance_config` block supports: -* `enable_confidential_compute` (Optional) Defines whether the instance should have confidential compute enabled with AMD SEV. If enabled, [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. +* `enable_confidential_compute` (Optional) Defines whether the instance should have confidential compute enabled with AMD SEV. If enabled, [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"` or `"AMD Genoa"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. -* `confidential_instance_type` (Optional) Defines the confidential computing technology the instance uses. SEV is an AMD feature. TDX is an Intel feature. One of the following values is required: `SEV`, `SEV_SNP`, `TDX`. [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`confidential_instance_type`](#confidential_instance_type) is set to `SEV` and [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. If `SEV_SNP`, currently [`min_cpu_platform`](#min_cpu_platform) has to be set to `"AMD Milan"` or this will fail to create the VM. +* `confidential_instance_type` (Optional) Defines the confidential computing technology the instance uses. SEV is an AMD feature. TDX is an Intel feature. One of the following values is required: `SEV`, `SEV_SNP`, `TDX`. [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`confidential_instance_type`](#confidential_instance_type) is set to `SEV` and [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"` or `"AMD Genoa"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. If `SEV_SNP`, currently [`min_cpu_platform`](#min_cpu_platform) has to be set to `"AMD Milan"` or this will fail to create the VM. The `advanced_machine_features` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_instance_from_template.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_instance_from_template.html.markdown index e5ba14b0ea69..e12b8a43fa9f 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_instance_from_template.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_instance_from_template.html.markdown @@ -83,6 +83,7 @@ are marked [Attributes as Blocks](/docs/configuration/attr-as-blocks.html): * `service_account` * `scratch_disk` * `network_interface.alias_ip_range` +* `network_interface.alias_ipv6_range` [Beta] * `network_interface.access_config` ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/compute_instance_group.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_instance_group.html.markdown index 5d846e846bbd..82aeed9dcb7a 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_instance_group.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_instance_group.html.markdown @@ -146,6 +146,13 @@ The following arguments are supported: fails. Defaults to the network where the instances are in (if neither `network` nor `instances` is specified, this field will be blank). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `named_port` block supports: * `name` - (Required) The name which the port will be mapped to. diff --git a/mmv1/third_party/terraform/website/docs/r/compute_instance_group_manager.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_instance_group_manager.html.markdown index a25ff4d45d11..73ed263295b6 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_instance_group_manager.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_instance_group_manager.html.markdown @@ -258,6 +258,13 @@ group. You can specify only one value. Structure is [documented below](#nested_a * `target_size_policy` - (Optional) The policy that specifies how the MIG creates its VMs to achieve the target size. Structure is [documented below](#nested_target_size_policy). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - The `standby_policy` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_instance_template.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_instance_template.html.markdown index 096b82f8bba0..652037d5555b 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_instance_template.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_instance_template.html.markdown @@ -600,6 +600,10 @@ The following arguments are supported: array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range). +* `alias_ipv6_range` - (Optional) [Beta] An + array of alias IPv6 ranges for this network interface. Can only be specified for network + interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range). + * `nic_type` - (Optional) The type of vNIC to be used on this interface. Possible values: GVNIC, VIRTIO_NET, MRDMA, IRDMA, IDPF. * `igmp_query` - (Optional) Indicates whether igmp query is enabled on the network interface or not. If enabled, also indicates the version of IGMP supported. @@ -791,9 +795,9 @@ The `specific_reservation` block supports: The `confidential_instance_config` block supports: -* `enable_confidential_compute` (Optional) Defines whether the instance should have confidential compute enabled with AMD SEV. If enabled, [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. +* `enable_confidential_compute` (Optional) Defines whether the instance should have confidential compute enabled with AMD SEV. If enabled, [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"` or `"AMD Genoa"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. -* `confidential_instance_type` (Optional) Defines the confidential computing technology the instance uses. SEV is an AMD feature. TDX is an Intel feature. One of the following values is required: `SEV`, `SEV_SNP`, `TDX`. [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`confidential_instance_type`](#confidential_instance_type) is set to `SEV` and [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. If `SEV_SNP`, currently [`min_cpu_platform`](#min_cpu_platform) has to be set to `"AMD Milan"` or this will fail to create the VM. +* `confidential_instance_type` (Optional) Defines the confidential computing technology the instance uses. SEV is an AMD feature. TDX is an Intel feature. One of the following values is required: `SEV`, `SEV_SNP`, `TDX`. [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`confidential_instance_type`](#confidential_instance_type) is set to `SEV` and [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"` or `"AMD Genoa"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. If `SEV_SNP`, currently [`min_cpu_platform`](#min_cpu_platform) has to be set to `"AMD Milan"` or this will fail to create the VM. The `network_performance_config` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_network_peering.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_network_peering.html.markdown index 03aabfac59f1..8bc6fc19a08e 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_network_peering.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_network_peering.html.markdown @@ -71,6 +71,14 @@ Which IP version(s) of traffic and routes are allowed to be imported or exported * `update_strategy` - (Optional) The update strategy determines the semantics for updates and deletes to the peering connection configuration. The default value is INDEPENDENT. Possible values: ["INDEPENDENT", "CONSENSUS"] +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/compute_project_metadata.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_project_metadata.html.markdown index 2692f87100e1..33ab5b07eef5 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_project_metadata.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_project_metadata.html.markdown @@ -57,6 +57,13 @@ The following arguments are supported: * `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_project_metadata_item.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_project_metadata_item.html.markdown index ff0556f2663f..5b57ed1c241b 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_project_metadata_item.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_project_metadata_item.html.markdown @@ -33,6 +33,13 @@ The following arguments are supported: * `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_region_instance_group_manager.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_region_instance_group_manager.html.markdown index 43d3ce5e8154..078529504303 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_region_instance_group_manager.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_region_instance_group_manager.html.markdown @@ -137,6 +137,13 @@ The following arguments are supported: * `region` - (Optional) The region where the managed instance group resides. If not provided, the provider region is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - * `description` - (Optional) An optional textual description of the instance diff --git a/mmv1/third_party/terraform/website/docs/r/compute_region_instance_template.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_region_instance_template.html.markdown index 16e254d4ab36..9029da4c7196 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_region_instance_template.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_region_instance_template.html.markdown @@ -395,6 +395,13 @@ The following arguments are supported: * `key_revocation_action_type` - (optional) Action to be taken when a customer's encryption key is revoked. Supports `STOP` and `NONE`, with `NONE` being the default. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `disk` block supports: * `auto_delete` - (Optional) Whether or not the disk should be auto-deleted. @@ -562,6 +569,10 @@ The following arguments are supported: array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range). +* `alias_ipv6_range` - (Optional) [Beta] An + array of alias IPv6 ranges for this network interface. Can only be specified for network + interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range). + * `nic_type` - (Optional) The type of vNIC to be used on this interface. Possible values: GVNIC, VIRTIO_NET, MRDMA, IRDMA, IDPF. * `network_attachment` - (Optional) The URL of the network attachment that this interface should connect to in the following format: projects/{projectNumber}/regions/{region_name}/networkAttachments/{network_attachment_name}. @@ -750,9 +761,9 @@ The `specific_reservation` block supports: The `confidential_instance_config` block supports: -* `enable_confidential_compute` (Optional) Defines whether the instance should have confidential compute enabled with AMD SEV. If enabled, [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. +* `enable_confidential_compute` (Optional) Defines whether the instance should have confidential compute enabled with AMD SEV. If enabled, [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"` or `"AMD Genoa"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. -* `confidential_instance_type` (Optional) Defines the confidential computing technology the instance uses. SEV is an AMD feature. TDX is an Intel feature. One of the following values is required: `SEV`, `SEV_SNP`, `TDX`. [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`confidential_instance_type`](#confidential_instance_type) is set to `SEV` and [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. If `SEV_SNP`, currently [`min_cpu_platform`](#min_cpu_platform) has to be set to `"AMD Milan"` or this will fail to create the VM. +* `confidential_instance_type` (Optional) Defines the confidential computing technology the instance uses. SEV is an AMD feature. TDX is an Intel feature. One of the following values is required: `SEV`, `SEV_SNP`, `TDX`. [`on_host_maintenance`](#on_host_maintenance) can be set to MIGRATE if [`confidential_instance_type`](#confidential_instance_type) is set to `SEV` and [`min_cpu_platform`](#min_cpu_platform) is set to `"AMD Milan"` or `"AMD Genoa"`. Otherwise, [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM. If `SEV_SNP`, currently [`min_cpu_platform`](#min_cpu_platform) has to be set to `"AMD Milan"` or this will fail to create the VM. The `network_performance_config` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_router_interface.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_router_interface.html.markdown index 31f2f87926cc..56a051bb2fdc 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_router_interface.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_router_interface.html.markdown @@ -69,6 +69,13 @@ In addition to the above required fields, a router interface must have specified * `region` - (Optional) The region this interface's router sits in. If not specified, the project region will be used. Changing this forces a new interface to be created. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_router_peer.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_router_peer.html.markdown index f1789bc85e2a..3284122f2553 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_router_peer.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_router_peer.html.markdown @@ -535,6 +535,13 @@ The following arguments are supported: * `md5_authentication_key` - (Optional) Configuration for MD5 authentication on the BGP session. Structure is [documented below](#nested_md5_authentication_key). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `advertised_ip_ranges` block supports: * `range` - diff --git a/mmv1/third_party/terraform/website/docs/r/compute_security_policy.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_security_policy.html.markdown index 3242cbda2623..6bd6dd90b880 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_security_policy.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_security_policy.html.markdown @@ -226,6 +226,13 @@ The following arguments are supported: * `label_fingerprint` - The unique fingerprint of the labels. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `advanced_options_config` block supports: * `json_parsing` - Whether or not to JSON parse the payload body. Defaults to `DISABLED`. diff --git a/mmv1/third_party/terraform/website/docs/r/compute_shared_vpc_host_project.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_shared_vpc_host_project.html.markdown index 88d09437ee39..cfb1d63447fd 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_shared_vpc_host_project.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_shared_vpc_host_project.html.markdown @@ -41,6 +41,13 @@ The following arguments are expected: * `project` - (Required) The ID of the project that will serve as a Shared VPC host project +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/compute_target_pool.html.markdown b/mmv1/third_party/terraform/website/docs/r/compute_target_pool.html.markdown index ab3e71390ba4..db3e3e2e6ffa 100644 --- a/mmv1/third_party/terraform/website/docs/r/compute_target_pool.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/compute_target_pool.html.markdown @@ -75,6 +75,13 @@ The following arguments are supported: * `security_policy` - (Optional, [Beta](../guides/provider_versions.html.markdown)) The resource URL for the security policy associated with this target pool. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/container_aws_cluster.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_aws_cluster.html.markdown index 66fbf2744973..4de667204b42 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_aws_cluster.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_aws_cluster.html.markdown @@ -324,7 +324,13 @@ The following arguments are supported: * `networking` - (Required) Cluster-wide networking configuration. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `authorization` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/container_aws_node_pool.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_aws_node_pool.html.markdown index 986f1f4b164d..30375eefe511 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_aws_node_pool.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_aws_node_pool.html.markdown @@ -533,7 +533,13 @@ The following arguments are supported: * `version` - (Required) The Kubernetes version to run on this node pool (e.g. `1.19.10-gke.1000`). You can list all supported versions on a given Google Cloud region by calling GetAwsServerConfig. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `autoscaling` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/container_azure_client.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_azure_client.html.markdown index fce523a2c3e2..1b68feea9d48 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_azure_client.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_azure_client.html.markdown @@ -50,6 +50,13 @@ The following arguments are supported: * `project` - (Optional) The project for the resource + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. diff --git a/mmv1/third_party/terraform/website/docs/r/container_azure_cluster.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_azure_cluster.html.markdown index 091b0c590615..5a776ac55abe 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_azure_cluster.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_azure_cluster.html.markdown @@ -167,7 +167,13 @@ The following arguments are supported: * `resource_group_id` - (Required) The ARM ID of the resource group where the cluster resources are deployed. For example: `/subscriptions/*/resourceGroups/*` - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `authorization` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/container_azure_node_pool.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_azure_node_pool.html.markdown index 127c6371f325..8ee7da64894e 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_azure_node_pool.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_azure_node_pool.html.markdown @@ -154,7 +154,13 @@ The following arguments are supported: * `version` - (Required) The Kubernetes version (e.g. `1.19.10-gke.1000`) running on this node pool. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `autoscaling` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/container_cluster.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_cluster.html.markdown index e3499abf02ed..bd44fbc3be8e 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_cluster.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_cluster.html.markdown @@ -314,7 +314,7 @@ region are guaranteed to support the same version. [SecretManagerConfig](https://cloud.google.com/secret-manager/docs/secret-manager-managed-csi-component) feature. Structure is [documented below](#nested_secret_manager_config). -* `secret_sync_config` - (Optional, [Beta](../guides/provider_versions.html.markdown)) Configuration for the +* `secret_sync_config` - (Optional) Configuration for the [SecretSyncConfig](https://cloud.google.com/secret-manager/docs/sync-k8-secrets) feature. Structure is [documented below](#nested_secret_sync_config). @@ -447,6 +447,14 @@ Fleet configuration for the cluster. Structure is [documented below](#nested_fle * `rbac_binding_config` - (Optional) RBACBindingConfig allows user to restrict ClusterRoleBindings an RoleBindings that can be created. Structure is [documented below](#nested_rbac_binding_config). +* `deletion_policy` - + (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `default_snat_status` block supports * `disabled` - (Required) Whether the cluster disables default in-node sNAT rules. In-node sNAT rules will be disabled when defaultSnatStatus is disabled.When disabled is set to false, default IP masquerade rules will be applied to the nodes to prevent sNAT on cluster internal traffic @@ -463,6 +471,9 @@ Fleet configuration for the cluster. Structure is [documented below](#nested_fle It is enabled by default; set `disabled = true` to disable. +* `agent_sandbox_config` - (Optional, Beta) Configuration for the Agent Sandbox addon. Structure is documented below: + * `enabled` - (Required) Whether the Agent Sandbox addon is enabled. + * `http_load_balancing` - (Optional) The status of the HTTP (L7) load balancing controller addon, which makes it easy to set up HTTP load balancers for services in a cluster. It is enabled by default; set `disabled = true` to disable. @@ -547,7 +558,7 @@ Fleet configuration for the cluster. Structure is [documented below](#nested_fle This flag is required to workaround a port conflict with the gke-metadata-server on GKE nodes. * `disable_multi_nic` When set to true, this disables multi-NIC support for the Lustre CSI driver. By default, GKE enables multi-NIC support, which allows the Lustre CSI driver to automatically detect and configure all suitable network interfaces on a node to maximize I/O performance for demanding workloads. -* `pod_snapshot_config` - (Optional, [Beta](../guides/provider_versions.html.markdown)) The status of the Pod Snapshot addon. It is disabled by default. Set `enabled = true` to enable. +* `pod_snapshot_config` - (Optional) The status of the Pod Snapshot addon. It is disabled by default. Set `enabled = true` to enable. This example `addons_config` disables two addons: @@ -968,6 +979,8 @@ The `master_authorized_networks_config.cidr_blocks` block supports: * `enable_confidential_storage` - (Optional) Enabling Confidential Storage will create boot disk with confidential mode. It is disabled by default. +* `gpudirect_strategy` - (Optional) The type of GPUDirect strategy to enable on the node. See the [GKE network docs](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/gpu-bandwidth-gpudirect-tcpx) for information on available modes. + * `local_ssd_encryption_mode` - (Optional) Possible Local SSD encryption modes: Accepted values are: * `STANDARD_ENCRYPTION`: The given node will be encrypted using keys managed by Google infrastructure and the keys wll be deleted when the node is deleted. @@ -1359,7 +1372,7 @@ notification_config { The `secret_manager_config` block supports: * `enabled` (Required) - Enable the Secret Manager add-on for this cluster. -* `rotation_config` (Optional) - config for secret manager auto rotation. Structure is [docuemented below](#rotation_config) +* `rotation_config` (Optional) - config for secret manager auto rotation. Structure is [documented below](#rotation_config) The `rotation_config` block supports: @@ -1368,13 +1381,13 @@ notification_config { The `secret_sync_config` block supports: -* `enabled` (Required, [Beta](../guides/provider_versions.html.markdown)) - Enable the Sync as K8s secret feature for this cluster. -* `rotation_config` (Optional, [Beta](../guides/provider_versions.html.markdown)) - config for secret sync auto rotation. Structure is [docuemented below](#sync_rotation_config) +* `enabled` (Required) - Enable the Sync as K8s secret feature for this cluster. +* `rotation_config` (Optional) - config for secret sync auto rotation. Structure is [docuemented below](#sync_rotation_config) The `rotation_config` block supports: -* `enabled` (Optional, [Beta](../guides/provider_versions.html.markdown)) - Enable the roation in Sync as K8s secret feature for this cluster. -* `rotation_interval` (Optional, [Beta](../guides/provider_versions.html.markdown)) - The interval between two consecutive rotations. Default rotation interval is 2 minutes. +* `enabled` (Optional) - Enable the roation in Sync as K8s secret feature for this cluster. +* `rotation_interval` (Optional) - The interval between two consecutive rotations. Default rotation interval is 2 minutes. The `user_managed_keys_config` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/container_node_pool.html.markdown b/mmv1/third_party/terraform/website/docs/r/container_node_pool.html.markdown index 6157d8648961..fe7dbf368231 100644 --- a/mmv1/third_party/terraform/website/docs/r/container_node_pool.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/container_node_pool.html.markdown @@ -175,6 +175,13 @@ cluster. * `queued_provisioning` - (Optional) Specifies node pool-level settings of queued provisioning. Structure is [documented below](#nested_queued_provisioning). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `autoscaling` block supports (either total or per zone limits are required): * `min_node_count` - (Optional) Minimum number of nodes per zone in the NodePool. diff --git a/mmv1/third_party/terraform/website/docs/r/dataflow_flex_template_job.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataflow_flex_template_job.html.markdown index 5ec2ddd69467..86b9f883f608 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataflow_flex_template_job.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataflow_flex_template_job.html.markdown @@ -89,6 +89,8 @@ The following arguments are supported: * `container_spec_gcs_path` - (Required) The GCS path to the Dataflow job Flex Template. +* `create_ignore_already_exists` - (Optional) If true, if a 409 AlreadyExists error is returned on create, the provider will ignore it and adopt the existing resource. + - - - * `additional_experiments` - (Optional) List of experiments that should be used by the job. An example value is `["enable_stackdriver_agent_metrics"]`. @@ -152,6 +154,13 @@ and will remove the resource from terraform state and move on. See above note. * `transform_name_mapping` - (Optional) Only applicable when updating a pipeline. Map of transform name prefixes of the job to be replaced with the corresponding name prefixes of the new job.Only applicable when updating a pipeline. Map of transform name prefixes of the job to be replaced with the corresponding name prefixes of the new job. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/dataflow_job.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataflow_job.html.markdown index 98421f823577..18288b2401fe 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataflow_job.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataflow_job.html.markdown @@ -124,6 +124,12 @@ The following arguments are supported: * `ip_configuration` - (Optional) The configuration for VM IPs. Options are `"WORKER_IP_PUBLIC"` or `"WORKER_IP_PRIVATE"`. * `additional_experiments` - (Optional) List of experiments that should be used by the job. An example value is `["enable_stackdriver_agent_metrics"]`. * `enable_streaming_engine` - (Optional) Enable/disable the use of [Streaming Engine](https://cloud.google.com/dataflow/docs/guides/deploying-a-pipeline#streaming-engine) for the job. Note that Streaming Engine is enabled by default for pipelines developed against the Beam SDK for Python v2.21.0 or later when using Python 3. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/dataplex_asset.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataplex_asset.html.markdown index 847fcf9d7e4c..ef88109a02a8 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataplex_asset.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataplex_asset.html.markdown @@ -105,7 +105,13 @@ The following arguments are supported: * `resource_spec` - (Required) Required. Immutable. Specification of the resource that is referenced by this asset. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `discovery_spec` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/dataplex_lake.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataplex_lake.html.markdown index aa9140250af2..4c805e785afb 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataplex_lake.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataplex_lake.html.markdown @@ -64,6 +64,13 @@ Please refer to the field `effective_labels` for all of the labels present on th * `project` - (Optional) The project for the resource + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. diff --git a/mmv1/third_party/terraform/website/docs/r/dataplex_zone.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataplex_zone.html.markdown index 80977fc6d17b..849a3f6a7c92 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataplex_zone.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataplex_zone.html.markdown @@ -73,7 +73,13 @@ The following arguments are supported: * `type` - (Required) Required. Immutable. The type of the zone. Possible values: TYPE_UNSPECIFIED, RAW, CURATED - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `discovery_spec` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/dataproc_cluster.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataproc_cluster.html.markdown index ebc95e0994ac..6c2ebad42f02 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataproc_cluster.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataproc_cluster.html.markdown @@ -156,6 +156,14 @@ resource "google_dataproc_cluster" "accelerated_cluster" { [Duration](https://developers.google.com/protocol-buffers/docs/proto3#json)). Only supported on Dataproc image versions 1.2 and higher. For more context see the [docs](https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.clusters/patch#query-parameters) + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - The `virtual_cluster_config` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/dataproc_job.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataproc_job.html.markdown index e54719f3c400..48a2b07dff8b 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataproc_job.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataproc_job.html.markdown @@ -117,6 +117,13 @@ output "pyspark_status" { * `wait_for_completion` - (Optional) If set to true, Terraform will wait for the job to reach a terminal state (`DONE`, `ERROR`, `CANCELLED`, `ATTEMPT_FAILURE`). Otherwise, Terraform will consider the job 'created' once it is in the `RUNNING` state. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `pyspark_config` block supports: Submitting a pyspark job to the cluster. Below is an example configuration: diff --git a/mmv1/third_party/terraform/website/docs/r/dataproc_workflow_template.html.markdown b/mmv1/third_party/terraform/website/docs/r/dataproc_workflow_template.html.markdown index 51ff8476d647..42b1eaa72069 100644 --- a/mmv1/third_party/terraform/website/docs/r/dataproc_workflow_template.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dataproc_workflow_template.html.markdown @@ -155,6 +155,13 @@ The following arguments are supported: * `encryption_config` - (Optional) Encryption settings for encrypting workflow template job arguments. Structure is [documented below](#nested_encryption_config) +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `encryption_config` block supports: * `kms_key` - (Optional) The Cloud KMS key name to use for encrypting workflow template [job arguments](https://docs.docs.cloud.google.com/dataproc/docs/concepts/workflows/use-workflows). diff --git a/mmv1/third_party/terraform/website/docs/r/dns_record_set.html.markdown b/mmv1/third_party/terraform/website/docs/r/dns_record_set.html.markdown index 019f2b93d9e7..9d4b01976ac5 100644 --- a/mmv1/third_party/terraform/website/docs/r/dns_record_set.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/dns_record_set.html.markdown @@ -315,6 +315,13 @@ The following arguments are supported: * `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `routing_policy` block supports: * `wrr` - (Optional) The configuration for Weighted Round Robin based routing policy. diff --git a/mmv1/third_party/terraform/website/docs/r/firebaserules_release.html.markdown b/mmv1/third_party/terraform/website/docs/r/firebaserules_release.html.markdown index 815a3e1adda8..6d40961401d3 100644 --- a/mmv1/third_party/terraform/website/docs/r/firebaserules_release.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/firebaserules_release.html.markdown @@ -120,7 +120,13 @@ The following arguments are supported: * `project` - (Optional) The project for the resource - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/firebaserules_ruleset.html.markdown b/mmv1/third_party/terraform/website/docs/r/firebaserules_ruleset.html.markdown index f1b3ff4a0887..0b5e75f9779c 100644 --- a/mmv1/third_party/terraform/website/docs/r/firebaserules_ruleset.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/firebaserules_ruleset.html.markdown @@ -71,7 +71,13 @@ The `source` block supports: * `project` - (Optional) The project for the resource - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `files` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/gke_hub_feature_membership.html.markdown b/mmv1/third_party/terraform/website/docs/r/gke_hub_feature_membership.html.markdown index d9c75fad74e9..aea722b0a299 100644 --- a/mmv1/third_party/terraform/website/docs/r/gke_hub_feature_membership.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/gke_hub_feature_membership.html.markdown @@ -358,6 +358,13 @@ The following arguments are supported: * `project` - (Optional) The project of the feature + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. diff --git a/mmv1/third_party/terraform/website/docs/r/google_billing_subaccount.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_billing_subaccount.html.markdown index 3ee7bcb3d6b1..fdfc88859ee7 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_billing_subaccount.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_billing_subaccount.html.markdown @@ -26,7 +26,13 @@ resource "google_billing_subaccount" "subaccount" { * `deletion_policy` (Optional) - If set to "RENAME_ON_DESTROY" the billing account display_name will be changed to "Terraform Destroyed" along with a timestamp. If set to "" this will not occur. - Default is "". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", the command will behave as if set to "". + + Possible values: RENAME_ON_DESTROY, PREVENT, ABANDON, DELETE. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/google_folder.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_folder.html.markdown index 29825e8f5164..ebb2273b64a6 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_folder.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_folder.html.markdown @@ -59,6 +59,13 @@ The following arguments are supported: * `tags` - (Optional) A map of resource manager tags. Resource manager tag keys and values have the same definition as resource manager tags. Keys must be in the format tagKeys/{tag_key_id}, and values are in the format tagValues/456. The field is ignored when empty. The field is immutable and causes resource replacement when mutated. This field is only set at create time and modifying this field after creation will trigger recreation. To apply tags to an existing resource, see the `google_tags_tag_value` resource. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/google_folder_organization_policy.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_folder_organization_policy.html.markdown index b2a8d0622a1f..1b0a89e5d1e1 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_folder_organization_policy.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_folder_organization_policy.html.markdown @@ -100,6 +100,13 @@ can also be used to allow or deny all values. Structure is [documented below](#n ~> **Note:** If none of [`boolean_policy`, `list_policy`, `restore_policy`] are defined the policy for a given constraint will effectively be unset. This is represented in the UI as the constraint being 'Inherited'. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - The `boolean_policy` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/google_organization_iam_custom_role.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_organization_iam_custom_role.html.markdown index 1e419d9e4252..1f08a77c3421 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_organization_iam_custom_role.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_organization_iam_custom_role.html.markdown @@ -50,6 +50,13 @@ The following arguments are supported: * `description` - (Optional) A human-readable description for the role. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/google_organization_policy.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_organization_policy.html.markdown index f963cb47bbf8..9bcc5bfbd131 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_organization_policy.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_organization_policy.html.markdown @@ -99,6 +99,13 @@ below](#nested_boolean_policy). ~> **Note:** If none of [`boolean_policy`, `list_policy`, `restore_policy`] are defined the policy for a given constraint will effectively be unset. This is represented in the UI as the constraint being 'Inherited'. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - The `boolean_policy` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/google_project_iam.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_project_iam.html.markdown index 0a53c6377a16..13cadcd4d484 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_project_iam.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_project_iam.html.markdown @@ -239,6 +239,28 @@ The [`terraform import` command](https://developer.hashicorp.com/terraform/cli/c $ terraform import google_project_iam_member.default "{{project_id}} roles/viewer user:foo@example.com" ``` +#### Import via resource identity + +`google_project_iam_member` also supports plannable import via [resource identity](https://developer.hashicorp.com/terraform/language/resources/identities) (Terraform 1.12+): + +```tf +import { + to = google_project_iam_member.default + identity = { + project = "your-project-id" + role = "roles/viewer" + member = "user:foo@example.com" + } +} +``` + +Identity attributes: + +* `project` - (Optional) The project id. May be omitted if a default project is configured on the provider. +* `role` - (Required) The IAM role being granted. +* `member` - (Required) The identity that the role is granted to. +* `condition_title` - (Optional) Title of the IAM condition, when importing a conditional binding. + ### Importing IAM bindings IAM binding imports use space-delimited identifiers that contain the `org_id` and role, e.g. @@ -260,6 +282,26 @@ The [`terraform import` command](https://developer.hashicorp.com/terraform/cli/c terraform import google_project_iam_binding.default "{{project_id}} roles/viewer" ``` +#### Import via resource identity + +`google_project_iam_binding` also supports plannable import via [resource identity](https://developer.hashicorp.com/terraform/language/resources/identities) (Terraform 1.12+): + +```tf +import { + to = google_project_iam_binding.default + identity = { + project = "your-project-id" + role = "roles/viewer" + } +} +``` + +Identity attributes: + +* `project` - (Optional) The project id. May be omitted if a default project is configured on the provider. +* `role` - (Required) The IAM role being granted. +* `condition_title` - (Optional) Title of the IAM condition, when importing a conditional binding. + ### Importing IAM policies IAM policy imports use the identifier of the Project only. For example: @@ -281,6 +323,23 @@ The [`terraform import` command](https://developer.hashicorp.com/terraform/cli/c $ terraform import google_project_iam_policy.default {{project_id}} ``` +#### Import via resource identity + +`google_project_iam_policy` also supports plannable import via [resource identity](https://developer.hashicorp.com/terraform/language/resources/identities) (Terraform 1.12+): + +```tf +import { + to = google_project_iam_policy.default + identity = { + project = "your-project-id" + } +} +``` + +Identity attributes: + +* `project` - (Optional) The project id. May be omitted if a default project is configured on the provider. + ### Importing Audit Configs An audit config can be imported into a `google_project_iam_audit_config` resource using the resource's `project_id` and the `service`, e.g: diff --git a/mmv1/third_party/terraform/website/docs/r/google_project_iam_custom_role.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_project_iam_custom_role.html.markdown index 9c18717b0d2a..98c994c8e298 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_project_iam_custom_role.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_project_iam_custom_role.html.markdown @@ -50,6 +50,13 @@ The following arguments are supported: * `description` - (Optional) A human-readable description for the role. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/google_project_iam_member_remove.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_project_iam_member_remove.html.markdown index 4d9b3888df5b..24314642d403 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_project_iam_member_remove.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_project_iam_member_remove.html.markdown @@ -53,3 +53,10 @@ The following arguments are supported: * **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com. * **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + diff --git a/mmv1/third_party/terraform/website/docs/r/google_project_organization_policy.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_project_organization_policy.html.markdown index 67eb3c515d6b..6b1de9ab2b77 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_project_organization_policy.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_project_organization_policy.html.markdown @@ -99,6 +99,13 @@ The following arguments are supported: ~> **Note:** If none of [`boolean_policy`, `list_policy`, `restore_policy`] are defined the policy for a given constraint will effectively be unset. This is represented in the UI as the constraint being 'Inherited'. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - The `boolean_policy` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/google_project_service.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_project_service.html.markdown index 14af21053cea..f5f04e6bae3f 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_project_service.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_project_service.html.markdown @@ -60,6 +60,15 @@ services depend on this service when attempting to destroy it. If `true`, the usage of the service to be disabled will be checked and an error will be returned if the service to be disabled has usage in last 30 days. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + If `disable_on_destroy` is set to `false`, the service will still be enabled when the + Terraform resource is destroyed even if the `deletion_policy` field is set to "DELETE". + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/google_service_account.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_service_account.html.markdown index bdfabc635e50..50930b6b4a65 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_service_account.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_service_account.html.markdown @@ -53,6 +53,13 @@ The following arguments are supported: * `create_ignore_already_exists` - (Optional) If set to true, skip service account creation if a service account with the same email already exists. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/google_service_account_key.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_service_account_key.html.markdown index 0cb3eb5ac28c..ad30a9743ee6 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_service_account_key.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_service_account_key.html.markdown @@ -101,6 +101,13 @@ Valid values are listed at * `keepers` (Optional) Arbitrary map of values that, when changed, will trigger a new key to be generated. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference The following attributes are exported in addition to the arguments listed above: diff --git a/mmv1/third_party/terraform/website/docs/r/google_service_networking_peered_dns_domain.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_service_networking_peered_dns_domain.html.markdown index d4ebc11299bc..898bed8a1e40 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_service_networking_peered_dns_domain.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_service_networking_peered_dns_domain.html.markdown @@ -38,6 +38,13 @@ The following arguments are supported: * `service` - (Optional) Private service connection between service and consumer network, defaults to `servicenetworking.googleapis.com` +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/google_tags_location_tag_binding.html.markdown b/mmv1/third_party/terraform/website/docs/r/google_tags_location_tag_binding.html.markdown index ee094e88618c..a2926dcf2ff3 100644 --- a/mmv1/third_party/terraform/website/docs/r/google_tags_location_tag_binding.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/google_tags_location_tag_binding.html.markdown @@ -112,6 +112,13 @@ The following arguments are supported: (Required) Location of the target resource. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - diff --git a/mmv1/third_party/terraform/website/docs/r/logging_billing_account_bucket_config.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_billing_account_bucket_config.html.markdown index 2f481874d40f..80350856125f 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_billing_account_bucket_config.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_billing_account_bucket_config.html.markdown @@ -59,6 +59,13 @@ The following arguments are supported: * `index_configs` - (Optional) A list of indexed fields and related configuration data. Structure is [documented below](#nested_index_configs). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `index_configs` block supports: * `field_path` - The LogEntry field path to index. diff --git a/mmv1/third_party/terraform/website/docs/r/logging_billing_account_sink.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_billing_account_sink.html.markdown index 97f1b3717c24..1a71eb717d5a 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_billing_account_sink.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_billing_account_sink.html.markdown @@ -72,6 +72,13 @@ The following arguments are supported: * `exclusions` - (Optional) Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both `filter` and one of `exclusions.filter`, it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is [documented below](#nested_exclusions). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `bigquery_options` block supports: * `use_partitioned_tables` - (Required) Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables). diff --git a/mmv1/third_party/terraform/website/docs/r/logging_folder_bucket_config.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_folder_bucket_config.html.markdown index e73a8ebd95cf..7b895d3d67e6 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_folder_bucket_config.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_folder_bucket_config.html.markdown @@ -49,6 +49,13 @@ The following arguments are supported: * `index_configs` - (Optional) A list of indexed fields and related configuration data. Structure is [documented below](#nested_index_configs). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `index_configs` block supports: * `field_path` - The LogEntry field path to index. diff --git a/mmv1/third_party/terraform/website/docs/r/logging_folder_sink.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_folder_sink.html.markdown index 3741d6632d54..012e4d1e7d2a 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_folder_sink.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_folder_sink.html.markdown @@ -84,6 +84,13 @@ The following arguments are supported: * `exclusions` - (Optional) Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both `filter` and one of `exclusions.filter`, it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is [documented below](#nested_exclusions). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `bigquery_options` block supports: * `use_partitioned_tables` - (Required) Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables). diff --git a/mmv1/third_party/terraform/website/docs/r/logging_organization_bucket_config.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_organization_bucket_config.html.markdown index 9255da93ea42..17e23660339d 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_organization_bucket_config.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_organization_bucket_config.html.markdown @@ -48,6 +48,13 @@ The following arguments are supported: * `index_configs` - (Optional) A list of indexed fields and related configuration data. Structure is [documented below](#nested_index_configs). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `index_configs` block supports: * `field_path` - The LogEntry field path to index. diff --git a/mmv1/third_party/terraform/website/docs/r/logging_organization_sink.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_organization_sink.html.markdown index f9600f68555d..c0dc3fcc407e 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_organization_sink.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_organization_sink.html.markdown @@ -74,6 +74,13 @@ The following arguments are supported: * `exclusions` - (Optional) Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both `filter` and one of `exclusions.filter`, it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is [documented below](#nested_exclusions). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `bigquery_options` block supports: * `use_partitioned_tables` - (Required) Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables). diff --git a/mmv1/third_party/terraform/website/docs/r/logging_project_bucket_config.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_project_bucket_config.html.markdown index 2e57e1993f01..b546a04a802f 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_project_bucket_config.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_project_bucket_config.html.markdown @@ -131,6 +131,13 @@ The following arguments are supported: * `index_configs` - (Optional) A list of indexed fields and related configuration data. Structure is [documented below](#nested_index_configs). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `cmek_settings` block supports: * `name` - The resource name of the CMEK settings. diff --git a/mmv1/third_party/terraform/website/docs/r/logging_project_sink.html.markdown b/mmv1/third_party/terraform/website/docs/r/logging_project_sink.html.markdown index a883fa8c6d6b..ac8f4be226cd 100644 --- a/mmv1/third_party/terraform/website/docs/r/logging_project_sink.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/logging_project_sink.html.markdown @@ -203,6 +203,13 @@ The following arguments are supported: * `exclusions` - (Optional) Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both `filter` and one of `exclusions.filter`, it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is [documented below](#nested_exclusions). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `bigquery_options` block supports: * `use_partitioned_tables` - (Required) Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables). diff --git a/mmv1/third_party/terraform/website/docs/r/monitoring_dashboard.html.markdown b/mmv1/third_party/terraform/website/docs/r/monitoring_dashboard.html.markdown index b1b72bb9d2e0..55b4fb095450 100644 --- a/mmv1/third_party/terraform/website/docs/r/monitoring_dashboard.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/monitoring_dashboard.html.markdown @@ -126,6 +126,12 @@ The following arguments are supported: * `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/os_config_os_policy_assignment.html.markdown b/mmv1/third_party/terraform/website/docs/r/os_config_os_policy_assignment.html.markdown index 229383c34847..e5be5713bf2e 100644 --- a/mmv1/third_party/terraform/website/docs/r/os_config_os_policy_assignment.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/os_config_os_policy_assignment.html.markdown @@ -130,6 +130,13 @@ The following arguments are supported: * `location` - (Required) The location for the resource +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `os_policies` block supports: * `id` - (Required) The id of the OS policy with the following restrictions: diff --git a/mmv1/third_party/terraform/website/docs/r/project_usage_export_bucket.html.markdown b/mmv1/third_party/terraform/website/docs/r/project_usage_export_bucket.html.markdown index b360a36f9185..2899183e4875 100644 --- a/mmv1/third_party/terraform/website/docs/r/project_usage_export_bucket.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/project_usage_export_bucket.html.markdown @@ -36,6 +36,14 @@ resource "google_project_usage_export_bucket" "usage_export" { * `project`: (Optional) The project to set the export bucket on. If it is not provided, the provider project is used. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Timeouts This resource provides the following diff --git a/mmv1/third_party/terraform/website/docs/r/recaptcha_enterprise_key.html.markdown b/mmv1/third_party/terraform/website/docs/r/recaptcha_enterprise_key.html.markdown index e364fee56129..57f8d08eb47c 100644 --- a/mmv1/third_party/terraform/website/docs/r/recaptcha_enterprise_key.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/recaptcha_enterprise_key.html.markdown @@ -198,7 +198,13 @@ Please refer to the field `effective_labels` for all of the labels present on th * `web_settings` - (Optional) Settings for keys that can be used by websites. - + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. The `android_settings` block supports: diff --git a/mmv1/third_party/terraform/website/docs/r/runtimeconfig_config.html.markdown b/mmv1/third_party/terraform/website/docs/r/runtimeconfig_config.html.markdown index 5ac4cfd51112..eadd0840d515 100644 --- a/mmv1/third_party/terraform/website/docs/r/runtimeconfig_config.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/runtimeconfig_config.html.markdown @@ -42,6 +42,13 @@ is not provided, the provider project is used. * `description` - (Optional) The description to associate with the runtime config. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are exported: diff --git a/mmv1/third_party/terraform/website/docs/r/runtimeconfig_variable.html.markdown b/mmv1/third_party/terraform/website/docs/r/runtimeconfig_variable.html.markdown index f768471c0cdc..ebd114bcf29a 100644 --- a/mmv1/third_party/terraform/website/docs/r/runtimeconfig_variable.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/runtimeconfig_variable.html.markdown @@ -69,6 +69,13 @@ is specified, it must be base64 encoded and less than 4096 bytes in length. * `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference In addition to the arguments listed above, the following computed attributes are diff --git a/mmv1/third_party/terraform/website/docs/r/service_networking_connection.html.markdown b/mmv1/third_party/terraform/website/docs/r/service_networking_connection.html.markdown index 78af668080cb..0f0639fba6c1 100644 --- a/mmv1/third_party/terraform/website/docs/r/service_networking_connection.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/service_networking_connection.html.markdown @@ -59,7 +59,13 @@ The following arguments are supported: this service provider. Note that invoking this method with a different range when connection is already established will not reallocate already provisioned service producer subnetworks. -* `deletion_policy` - (Optional) The deletion policy for the service networking connection. Setting to ABANDON allows the resource to be abandoned rather than deleted. This will enable a successful terraform destroy when destroying CloudSQL instances. Use with care as it can lead to dangling resources. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE" or any other value, deleting the resource is allowed. * `update_on_creation_fail` - (Optional) When set to true, enforce an update of the reserved peering ranges on the existing service networking connection in case of a new connection creation failure. diff --git a/mmv1/third_party/terraform/website/docs/r/site_verification_owner.html.markdown b/mmv1/third_party/terraform/website/docs/r/site_verification_owner.html.markdown index d1eec2889f13..f8a6a32576e7 100644 --- a/mmv1/third_party/terraform/website/docs/r/site_verification_owner.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/site_verification_owner.html.markdown @@ -96,6 +96,13 @@ The following arguments are supported: (Required) The email of the user to be added as an owner. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + - - - diff --git a/mmv1/third_party/terraform/website/docs/r/sql_database_instance.html.markdown b/mmv1/third_party/terraform/website/docs/r/sql_database_instance.html.markdown index 136d417a2097..f71fb97c7267 100644 --- a/mmv1/third_party/terraform/website/docs/r/sql_database_instance.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/sql_database_instance.html.markdown @@ -289,7 +289,7 @@ resource "google_sql_database_instance" "instance" { ``` ### Cloud SQL Instance created using point_in_time_restore -~> **NOTE:** Replace `backupdr_datasource` with the full datasource path, `time_stamp` should be in the format of `YYYY-MM-DDTHH:MM:SSZ`. +~> **NOTE:** Replace `backupdr_datasource` with the full datasource path, `time_stamp` should be in the format of `YYYY-MM-DDTHH:MM:SSZ`. The `target_instance` is required field and must match the name of the resource. ```hcl resource "google_sql_database_instance" "instance" { @@ -304,14 +304,14 @@ resource "google_sql_database_instance" "instance" { } point_in_time_restore_context { datasource = "backupdr_datasource" - target_instance = "target_instance_name" + target_instance = "main-instance" point_in_time = "time_stamp" } } ``` ### Cloud SQL Instance created using point_in_time_restore using multiregion datasource -~> **NOTE:** Replace `backupdr_datasource` with the full datasource path, `time_stamp` should be in the format of `YYYY-MM-DDTHH:MM:SSZ` and `region` with the target instance region. +~> **NOTE:** Replace `backupdr_datasource` with the full datasource path, `time_stamp` should be in the format of `YYYY-MM-DDTHH:MM:SSZ` and `region` with the target instance region. The `target_instance` is required field and must match the name of the resource. ```hcl resource "google_sql_database_instance" "instance" { @@ -326,7 +326,7 @@ resource "google_sql_database_instance" "instance" { } point_in_time_restore_context { datasource = "backupdr_datasource" - target_instance = "target_instance_name" + target_instance = "main-instance" point_in_time = "time_stamp" region = "region" } @@ -420,6 +420,13 @@ includes an up-to-date reference of supported versions. **NOTE:** Restoring from a backup is an imperative action and not recommended via Terraform. Adding or modifying this block during resource creation/update will trigger the restore action after the resource is created/updated. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `settings` block supports: * `tier` - (Required) The machine type to use. See [tiers](https://cloud.google.com/sql/docs/admin-api/v1beta4/tiers) @@ -467,11 +474,11 @@ The `settings` block supports: * `disk_size` - (Optional) The size of data disk, in GB. Size of a running instance cannot be reduced but can be increased. The minimum value is 10GB for `PD_SSD`, `PD_HDD` and 20GB for `HYPERDISK_BALANCED`. Note that this value will override the resizing from `disk_autoresize` if that feature is enabled. To avoid this, set `lifecycle.ignore_changes` on this field. -* `disk_type` - (Optional) The type of data disk: `PD_SSD`, `PD_HDD`, or `HYPERDISK_BALANCED`. Defaults to `PD_SSD`. `HYPERDISK_BALANCED` is preview. +* `disk_type` - (Optional) The type of data disk: `PD_SSD`, `PD_HDD`, or `HYPERDISK_BALANCED`. Defaults to `PD_SSD`. -* `data_disk_provisioned_iops` - (Optional, Beta) Provisioned number of I/O operations per second for the data disk. This field is only used for `HYPERDISK_BALANCED` disk types. +* `data_disk_provisioned_iops` - (Optional) Provisioned number of I/O operations per second for the data disk. This field is only used for `HYPERDISK_BALANCED` disk types. -* `data_disk_provisioned_throughput` - (Optional, Beta) Provisioned throughput measured in MiB per second for the data disk. This field is only used for `HYPERDISK_BALANCED` disk types. +* `data_disk_provisioned_throughput` - (Optional) Provisioned throughput measured in MiB per second for the data disk. This field is only used for `HYPERDISK_BALANCED` disk types. * `node_count` - For a read pool instance, the number of nodes in the read pool. For read pools with auto scaling enabled, this field is read only. diff --git a/mmv1/third_party/terraform/website/docs/r/sql_ssl_cert.html.markdown b/mmv1/third_party/terraform/website/docs/r/sql_ssl_cert.html.markdown index 156e29ba10e4..58788fea847f 100644 --- a/mmv1/third_party/terraform/website/docs/r/sql_ssl_cert.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/sql_ssl_cert.html.markdown @@ -47,6 +47,12 @@ The following arguments are supported: * `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/sql_user.html.markdown b/mmv1/third_party/terraform/website/docs/r/sql_user.html.markdown index 62330dee50dd..be7e6440ad4d 100644 --- a/mmv1/third_party/terraform/website/docs/r/sql_user.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/sql_user.html.markdown @@ -161,11 +161,14 @@ The following arguments are supported: [Postgres](https://cloud.google.com/sql/docs/postgres/admin-api/rest/v1beta4/users#sqlusertype) and [MySQL](https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/users#sqlusertype). -* `deletion_policy` - (Optional) The deletion policy for the user. - Setting `ABANDON` allows the resource to be abandoned rather than deleted. This is useful +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. This is useful for Postgres, where users cannot be deleted from the API if they have been granted SQL roles. - Possible values are: `ABANDON`. + When set to "DELETE", deleting the resource is allowed. - - - diff --git a/mmv1/third_party/terraform/website/docs/r/storage_bucket.html.markdown b/mmv1/third_party/terraform/website/docs/r/storage_bucket.html.markdown index 48525bf17c91..43f9fce19819 100644 --- a/mmv1/third_party/terraform/website/docs/r/storage_bucket.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/storage_bucket.html.markdown @@ -238,6 +238,13 @@ The following arguments are supported: * `ip_filter` - (Optional) The bucket IP filtering configuration. Specifies the network sources that can access the bucket, as well as its underlying objects. Structure is [documented below](#nested_ip_filter). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `lifecycle_rule` block supports: * `action` - (Required) The Lifecycle Rule's action configuration. A single block of this type is supported. Structure is [documented below](#nested_action). @@ -446,6 +453,18 @@ import { } ``` +In Terraform v1.12.0 and later, use an [`identity` block](https://developer.hashicorp.com/terraform/language/block/import#identity) to import Storage buckets using identity values. For example: + +```tf +import { + identity = { + project = "{{project_id}}" + name = "{{bucket}}" + } + to = google_storage_bucket.default +} +``` + When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), Storage buckets can be imported using one of the formats above. For example: ``` diff --git a/mmv1/third_party/terraform/website/docs/r/storage_bucket_acl.html.markdown b/mmv1/third_party/terraform/website/docs/r/storage_bucket_acl.html.markdown index e5ae8ba871ec..768d822f111d 100644 --- a/mmv1/third_party/terraform/website/docs/r/storage_bucket_acl.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/storage_bucket_acl.html.markdown @@ -49,6 +49,13 @@ resource "google_storage_bucket_acl" "image-store-acl" { * `default_acl` - (Optional) Configure this ACL to be the default ACL. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference Only the arguments listed above are exposed as attributes. diff --git a/mmv1/third_party/terraform/website/docs/r/storage_bucket_object.html.markdown b/mmv1/third_party/terraform/website/docs/r/storage_bucket_object.html.markdown index 8802718e1093..3d2d810ee209 100644 --- a/mmv1/third_party/terraform/website/docs/r/storage_bucket_object.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/storage_bucket_object.html.markdown @@ -113,7 +113,13 @@ One of the following is required: * `force_empty_content_type` - (Optional) When set to true, it ensure the object's Content-Type is empty. -* `deletion_policy` - (Optional) When set to ABANDON, the object won't be deleted from storage bucket. Instead, it will only be removed from terraform's state file. + +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. * `contexts` - (Optional) Contexts attached to an object, in key-value pairs. For more information about object contexts, see [Object contexts overview](https://cloud.google.com/storage/docs/object-contexts). Structure is [documented below](#nested_contexts). diff --git a/mmv1/third_party/terraform/website/docs/r/storage_default_object_acl.html.markdown b/mmv1/third_party/terraform/website/docs/r/storage_default_object_acl.html.markdown index ecac34f2d89d..6824efe3e1dc 100644 --- a/mmv1/third_party/terraform/website/docs/r/storage_default_object_acl.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/storage_default_object_acl.html.markdown @@ -49,6 +49,13 @@ resource "google_storage_default_object_acl" "image-store-default-acl" { See [GCS Object ACL documentation](https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls) for more details. Omitting the field is the same as providing an empty list. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + ## Attributes Reference Only the arguments listed above are exposed as attributes. diff --git a/mmv1/third_party/terraform/website/docs/r/storage_object_acl.html.markdown b/mmv1/third_party/terraform/website/docs/r/storage_object_acl.html.markdown index 368f1e7fdacb..9b10ec646ec9 100644 --- a/mmv1/third_party/terraform/website/docs/r/storage_object_acl.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/storage_object_acl.html.markdown @@ -62,6 +62,12 @@ Must be set if `predefined_acl` is not. adds that role/entity pair to your `terraform plan` results when it is omitted in your config; `terraform plan` will show the correct final state at every point except for at `Create` time, where the object role/entity pair is omitted if not explicitly set. +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. ## Attributes Reference diff --git a/mmv1/third_party/terraform/website/docs/r/storage_transfer_job.html.markdown b/mmv1/third_party/terraform/website/docs/r/storage_transfer_job.html.markdown index f506647350d2..a004ac000ab8 100644 --- a/mmv1/third_party/terraform/website/docs/r/storage_transfer_job.html.markdown +++ b/mmv1/third_party/terraform/website/docs/r/storage_transfer_job.html.markdown @@ -148,6 +148,13 @@ The following arguments are supported: * `logging_config` - (Optional) Logging configuration. Structure [documented below](#nested_logging_config). +* `deletion_policy` - (Optional) Whether Terraform will be prevented from destroying the resource. Defaults to "DELETE". + When a 'terraform destroy' or 'terraform apply' would delete the resource, + the command will fail if this field is set to "PREVENT" in Terraform state. + When set to "ABANDON", the command will remove the resource from Terraform + management without updating or deleting the resource in the API. + When set to "DELETE", deleting the resource is allowed. + The `transfer_spec` block supports: * `source_agent_pool_name` - (Optional) Specifies the agent pool name associated with the posix data source. When unspecified, the default name is used. diff --git a/mmv1/third_party/tgc/getconfig.go b/mmv1/third_party/tgc/getconfig.go index 3df0005713d7..b2b98c363714 100644 --- a/mmv1/third_party/tgc/getconfig.go +++ b/mmv1/third_party/tgc/getconfig.go @@ -33,7 +33,6 @@ func NewConfig(ctx context.Context, project, zone, region string, offline bool, "GOOGLE_IMPERSONATE_SERVICE_ACCOUNT", }) - transport_tpg.ConfigureBasePaths(cfg) if !offline { if err := cfg.LoadAndValidate(ctx); err != nil { return nil, errors.Wrap(err, "load and validate config") diff --git a/mmv1/third_party/tgc/services/storage/iam_storage_bucket.go b/mmv1/third_party/tgc/services/storage/iam_storage_bucket.go index 57258ff0466d..0afd6cbe812d 100644 --- a/mmv1/third_party/tgc/services/storage/iam_storage_bucket.go +++ b/mmv1/third_party/tgc/services/storage/iam_storage_bucket.go @@ -3,6 +3,7 @@ package storage import ( "fmt" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/services/storage" "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgiamresource" "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" @@ -156,7 +157,7 @@ func (u *StorageBucketIamUpdater) SetResourceIamPolicy(policy *cloudresourcemana } func (u *StorageBucketIamUpdater) qualifyBucketUrl(methodIdentifier string) (string, error) { - urlTemplate := fmt.Sprintf("{{StorageBasePath}}%s/%s", fmt.Sprintf("b/%s", u.bucket), methodIdentifier) + urlTemplate := fmt.Sprintf(transport_tpg.BaseUrl(storage.Product, u.Config)+"%s/%s", fmt.Sprintf("b/%s", u.bucket), methodIdentifier) url, err := tpgresource.ReplaceVars(u.d, u.Config, urlTemplate) if err != nil { return "", err diff --git a/mmv1/third_party/tgc_next/go.mod b/mmv1/third_party/tgc_next/go.mod index 2a9d68a88d87..10a4d1666edb 100644 --- a/mmv1/third_party/tgc_next/go.mod +++ b/mmv1/third_party/tgc_next/go.mod @@ -40,7 +40,6 @@ require ( ) require ( - bitbucket.org/creachadair/stringset v0.0.11 // indirect cel.dev/expr v0.25.1 // indirect cloud.google.com/go v0.123.0 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect diff --git a/mmv1/third_party/tgc_next/pkg/services/container/node_config.go b/mmv1/third_party/tgc_next/pkg/services/container/node_config.go index e47af63c4254..9639a3720dd5 100644 --- a/mmv1/third_party/tgc_next/pkg/services/container/node_config.go +++ b/mmv1/third_party/tgc_next/pkg/services/container/node_config.go @@ -2544,22 +2544,23 @@ func flattenNodeConfig(v interface{}, _ interface{}) []map[string]interface{} { "min_cpu_platform": c["minCpuPlatform"], "shielded_instance_config": flattenShieldedInstanceConfig(c["shieldedInstanceConfig"]), "sandbox_config": flattenSandboxConfig(c["sandboxConfig"]), - "taint": flattenEffectiveTaints(c["taints"]), - "workload_metadata_config": flattenWorkloadMetadataConfig(c["workloadMetadataConfig"]), - "confidential_nodes": flattenConfidentialNodes(c["confidentialNodes"]), - "boot_disk_kms_key": c["bootDiskKmsKey"], - "kubelet_config": flattenKubeletConfig(c["kubeletConfig"]), - "linux_node_config": flattenLinuxNodeConfig(c["linuxNodeConfig"]), - "windows_node_config": flattenWindowsNodeConfig(c["windowsNodeConfig"]), - "node_group": c["nodeGroup"], - "advanced_machine_features": flattenAdvancedMachineFeaturesConfig(c["advancedMachineFeatures"]), - "max_run_duration": c["maxRunDuration"], - "flex_start": c["flexStart"], - "sole_tenant_config": flattenSoleTenantConfig(c["soleTenantConfig"]), - "fast_socket": flattenFastSocket(c["fastSocket"]), - "resource_manager_tags": flattenResourceManagerTags(c["resourceManagerTags"]), - "enable_confidential_storage": c["enableConfidentialStorage"], - "local_ssd_encryption_mode": c["localSsdEncryptionMode"], + // TODO: need to differentiate the new resource and existing resource + // "taint": flattenEffectiveTaints(c["taints"]), + "workload_metadata_config": flattenWorkloadMetadataConfig(c["workloadMetadataConfig"]), + "confidential_nodes": flattenConfidentialNodes(c["confidentialNodes"]), + "boot_disk_kms_key": c["bootDiskKmsKey"], + "kubelet_config": flattenKubeletConfig(c["kubeletConfig"]), + "linux_node_config": flattenLinuxNodeConfig(c["linuxNodeConfig"]), + "windows_node_config": flattenWindowsNodeConfig(c["windowsNodeConfig"]), + "node_group": c["nodeGroup"], + "advanced_machine_features": flattenAdvancedMachineFeaturesConfig(c["advancedMachineFeatures"]), + "max_run_duration": c["maxRunDuration"], + "flex_start": c["flexStart"], + "sole_tenant_config": flattenSoleTenantConfig(c["soleTenantConfig"]), + "fast_socket": flattenFastSocket(c["fastSocket"]), + "resource_manager_tags": flattenResourceManagerTags(c["resourceManagerTags"]), + "enable_confidential_storage": c["enableConfidentialStorage"], + "local_ssd_encryption_mode": c["localSsdEncryptionMode"], } // Suppress Default Value diff --git a/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster.go b/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster.go index 678112cbcb06..0d5d24265be0 100644 --- a/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster.go +++ b/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster.go @@ -106,6 +106,7 @@ var ( "addons_config.0.istio_config", "addons_config.0.kalm_config", "addons_config.0.slice_controller_config", + "addons_config.0.pod_snapshot_config", } privateClusterConfigKeys = []string{ @@ -536,6 +537,23 @@ func ResourceContainerCluster() *schema.Resource { }, }, }, + "pod_snapshot_config": { + Type: schema.TypeList, + Optional: true, + Computed: true, + AtLeastOneOf: addonsConfigKeys, + MaxItems: 1, + Description: `Configuration for the Pod Snapshot feature.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Required: true, + Description: `Whether the Pod Snapshot feature is enabled for this cluster.`, + }, + }, + }, + }, "stateful_ha_config": { Type: schema.TypeList, Optional: true, diff --git a/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_cai2hcl.go b/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_cai2hcl.go index 4c9a0fd56499..e322832f6e19 100644 --- a/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_cai2hcl.go +++ b/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_cai2hcl.go @@ -122,8 +122,6 @@ func (c *ContainerClusterCai2hclConverter) convertResourceData(asset caiasset.As hclData["node_locations"] = locations } } - hclData["min_master_version"] = asset.Resource.Data["currentNodeVersion"] - hclData["node_version"] = asset.Resource.Data["currentNodeVersion"] hclData["logging_service"] = asset.Resource.Data["loggingService"] hclData["monitoring_service"] = asset.Resource.Data["monitoringService"] hclData["node_config"] = flattenNodeConfig(asset.Resource.Data["nodeConfig"], nil) @@ -211,6 +209,7 @@ func (c *ContainerClusterCai2hclConverter) convertResourceData(asset caiasset.As hclData["master_authorized_networks_config"] = flattenMasterAuthorizedNetworksConfig(asset.Resource.Data["masterAuthorizedNetworksConfig"]) hclData["pod_autoscaling"] = flattenPodAutoscaling(asset.Resource.Data["podAutoscaling"]) hclData["secret_manager_config"] = flattenSecretManagerConfig(asset.Resource.Data["secretManagerConfig"]) + hclData["secret_sync_config"] = flattenSecretSyncConfig(asset.Resource.Data["secretSyncConfig"]) hclData["resource_usage_export_config"] = flattenResourceUsageExportConfig(asset.Resource.Data["resourceUsageExportConfig"]) hclData["mesh_certificates"] = flattenMeshCertificates(asset.Resource.Data["meshCertificates"]) hclData["cost_management_config"] = flattenManagementConfig(asset.Resource.Data["costManagementConfig"]) @@ -623,6 +622,19 @@ func flattenClusterAddonsConfig(v interface{}, enableAutopilot bool) []map[strin } } + if val, ok := c["podSnapshotConfig"].(map[string]interface{}); ok { + enabled := false + if v, ok := val["enabled"]; ok && v != nil { + enabled = v.(bool) + } + + result["pod_snapshot_config"] = []map[string]interface{}{ + { + "enabled": enabled, + }, + } + } + return []map[string]interface{}{result} } @@ -707,6 +719,7 @@ func flattenPrivateClusterConfig(cpec, pcc, nc interface{}) []map[string]interfa if cpec != nil { if c, ok := cpec.(map[string]interface{}); ok { // Note the change in semantics from private to public endpoint. + r["enable_private_endpoint"] = true if ipEndpointsConfig, ok := c["ipEndpointsConfig"].(map[string]interface{}); ok { if v, ok := ipEndpointsConfig["enablePublicEndpoint"].(bool); ok { r["enable_private_endpoint"] = !v @@ -1177,11 +1190,11 @@ func flattenClusterAutoscaling(v interface{}, enableAutopilot bool) []map[string if !enableAutopilot { transformed["enabled"] = true } - } else if !enableAutopilot { - transformed["enabled"] = false + transformed["auto_provisioning_defaults"] = flattenAutoProvisioningDefaults(a["autoprovisioningNodePoolDefaults"]) + } + if v := a["autoprovisioningLocations"]; v != nil { + transformed["auto_provisioning_locations"] = v } - transformed["auto_provisioning_defaults"] = flattenAutoProvisioningDefaults(a["autoprovisioningNodePoolDefaults"]) - transformed["auto_provisioning_locations"] = a["autoprovisioningLocations"] if v := a["autoscalingProfile"]; v != nil && v != "BALANCED" { transformed["autoscaling_profile"] = v } @@ -1189,6 +1202,9 @@ func flattenClusterAutoscaling(v interface{}, enableAutopilot bool) []map[string transformed["default_compute_class_enabled"] = dccc["enabled"] } + if len(transformed) == 0 { + return nil + } return []map[string]interface{}{transformed} } @@ -1439,6 +1455,47 @@ func flattenSecretManagerConfig(v interface{}) []map[string]interface{} { return []map[string]interface{}{result} } +func flattenSecretSyncConfig(v interface{}) []map[string]interface{} { + if v == nil { + return []map[string]interface{}{ + { + "enabled": false, + }, + } + } + c, ok := v.(map[string]interface{}) + if !ok { + return nil + } + + result := make(map[string]interface{}) + if val, ok := c["enabled"]; ok && val != nil { + result["enabled"] = val + } else { + result["enabled"] = false + } + + rotationList := []map[string]interface{}{} + if rotationConfig, ok := c["rotationConfig"].(map[string]interface{}); ok && rotationConfig != nil { + rotationConfigMap := map[string]interface{}{} + if rVal, ok := rotationConfig["enabled"]; ok && rVal != nil { + rotationConfigMap["enabled"] = rVal + } else { + rotationConfigMap["enabled"] = false + } + + if interval, ok := rotationConfig["rotationInterval"].(string); ok && interval != "" { + rotationConfigMap["rotation_interval"] = interval + } + rotationList = append(rotationList, rotationConfigMap) + } + + if len(rotationList) > 0 { + result["rotation_config"] = rotationList + } + return []map[string]interface{}{result} +} + func flattenResourceUsageExportConfig(v interface{}) []map[string]interface{} { if v == nil { return nil diff --git a/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_tfplan2cai.go b/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_tfplan2cai.go index df655392137a..15eeb7cbd311 100644 --- a/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_tfplan2cai.go +++ b/mmv1/third_party/tgc_next/pkg/services/container/resource_container_cluster_tfplan2cai.go @@ -155,6 +155,7 @@ func expandContainerCluster(project string, d tpgresource.TerraformResourceData, NodePoolAutoConfig: expandNodePoolAutoConfig(d.Get("node_pool_auto_config")), CostManagementConfig: expandCostManagementConfig(d.Get("cost_management_config")), EnableK8sBetaApis: expandEnableK8sBetaApis(d.Get("enable_k8s_beta_apis"), nil), + SecretSyncConfig: expandSecretSyncConfig(d.Get("secret_sync_config")), } v := d.Get("enable_shielded_nodes") @@ -482,6 +483,14 @@ func expandClusterAddonsConfig(configured interface{}) *container.AddonsConfig { } } + if v, ok := config["pod_snapshot_config"]; ok && len(v.([]interface{})) > 0 { + addon := v.([]interface{})[0].(map[string]interface{}) + ac.PodSnapshotConfig = &container.PodSnapshotConfig{ + Enabled: addon["enabled"].(bool), + ForceSendFields: []string{"Enabled"}, + } + } + return ac } @@ -1313,6 +1322,39 @@ func expandSecretManagerConfig(configured interface{}) *container.SecretManagerC return sc } +func expandSecretSyncConfig(configured interface{}) *container.SecretSyncConfig { + l := configured.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil + } + + config := l[0].(map[string]interface{}) + sc := &container.SecretSyncConfig{ + Enabled: config["enabled"].(bool), + ForceSendFields: []string{"Enabled"}, + } + if autoRotation, ok := config["rotation_config"]; ok { + if autoRotationList, ok := autoRotation.([]interface{}); ok { + if len(autoRotationList) > 0 { + autoRotationConfig := autoRotationList[0].(map[string]interface{}) + if rotationInterval, ok := autoRotationConfig["rotation_interval"].(string); ok && rotationInterval != "" { + sc.RotationConfig = &container.SyncRotationConfig{ + Enabled: autoRotationConfig["enabled"].(bool), + RotationInterval: rotationInterval, + ForceSendFields: []string{"Enabled"}, + } + } else { + sc.RotationConfig = &container.SyncRotationConfig{ + Enabled: autoRotationConfig["enabled"].(bool), + ForceSendFields: []string{"Enabled"}, + } + } + } + } + } + return sc +} + func expandDefaultMaxPodsConstraint(v interface{}) *container.MaxPodsConstraint { if v == nil { return nil diff --git a/mmv1/third_party/tgc_next/pkg/services/container/resource_node_pool_cai2hcl.go b/mmv1/third_party/tgc_next/pkg/services/container/resource_node_pool_cai2hcl.go index 613874821417..8be629a0c5a8 100644 --- a/mmv1/third_party/tgc_next/pkg/services/container/resource_node_pool_cai2hcl.go +++ b/mmv1/third_party/tgc_next/pkg/services/container/resource_node_pool_cai2hcl.go @@ -119,11 +119,20 @@ func flattenNodePoolUpgradeSettings(v interface{}) []map[string]interface{} { if !ok { return nil } + if len(us) == 0 { + return nil + } upgradeSettings := make(map[string]interface{}) - upgradeSettings["blue_green_settings"] = flattenNodePoolBlueGreenSettings(us["blueGreenSettings"]) - upgradeSettings["max_surge"] = us["maxSurge"] - upgradeSettings["max_unavailable"] = us["maxUnavailable"] + if v := flattenNodePoolBlueGreenSettings(us["blueGreenSettings"]); v != nil { + upgradeSettings["blue_green_settings"] = v + } + if v := us["maxSurge"]; v != nil { + upgradeSettings["max_surge"] = v + } + if v := us["maxUnavailable"]; v != nil { + upgradeSettings["max_unavailable"] = v + } // "SHORT_LIVED" strategy is not supported by the Terraform provider yet. // Suppress Default Value "SURGE" @@ -131,6 +140,10 @@ func flattenNodePoolUpgradeSettings(v interface{}) []map[string]interface{} { upgradeSettings["strategy"] = strategy } + if len(upgradeSettings) == 0 { + return nil + } + return []map[string]interface{}{upgradeSettings} } diff --git a/mmv1/third_party/tgc_next/pkg/tfplan2cai/transport/getconfig.go b/mmv1/third_party/tgc_next/pkg/tfplan2cai/transport/getconfig.go index 15116ca45453..e8d0149a2dec 100644 --- a/mmv1/third_party/tgc_next/pkg/tfplan2cai/transport/getconfig.go +++ b/mmv1/third_party/tgc_next/pkg/tfplan2cai/transport/getconfig.go @@ -43,7 +43,6 @@ func NewConfig(ctx context.Context, project, zone, region string, offline bool, "GOOGLE_IMPERSONATE_SERVICE_ACCOUNT", }) - transport_tpg.ConfigureBasePaths(cfg) if !offline { if client != nil { cfg.Client = client diff --git a/mmv1/third_party/tgc_next/test/utils.go b/mmv1/third_party/tgc_next/test/utils.go index ddb43715714d..f866404c1dc0 100644 --- a/mmv1/third_party/tgc_next/test/utils.go +++ b/mmv1/third_party/tgc_next/test/utils.go @@ -10,7 +10,7 @@ import ( "strings" ) -// Writes the data into a JSON file +// Writes the data into a JSON file test func writeJSONFile(filename string, data interface{}) error { jsonData, err := json.MarshalIndent(data, "", " ") if err != nil { diff --git a/tools/diff-processor/detector/detector.go b/tools/diff-processor/detector/detector.go index 383cdf8bb152..be3537960f4f 100644 --- a/tools/diff-processor/detector/detector.go +++ b/tools/diff-processor/detector/detector.go @@ -62,6 +62,13 @@ func getChangedFieldsFromSchemaDiff(schemaDiff diff.SchemaDiff) map[string]Resou // Skip the project field. continue } + if field == "deletion_policy" { + //Skip tests for deletion policy. + //With the addition of the universal policy, these don't need to be detected on a resource basis. + // + //To-Do: don't skip if `deletion_policy_exclude` is flagged + continue + } // Ignore condition fields on iam resources because we always generate them whether or not // they're supported. // Longer-term fix tracked at https://github.com/hashicorp/terraform-provider-google/issues/18412 diff --git a/tools/diff-processor/go.mod b/tools/diff-processor/go.mod index 25caf57f390f..f269327a60ab 100644 --- a/tools/diff-processor/go.mod +++ b/tools/diff-processor/go.mod @@ -29,7 +29,6 @@ require ( ) require ( - bitbucket.org/creachadair/stringset v0.0.8 // indirect cel.dev/expr v0.15.0 // indirect cloud.google.com/go v0.115.1 // indirect cloud.google.com/go/auth v0.9.0 // indirect diff --git a/tools/go-changelog/go.mod b/tools/go-changelog/go.mod index 5f35ee263dab..60daf3d8df70 100644 --- a/tools/go-changelog/go.mod +++ b/tools/go-changelog/go.mod @@ -3,9 +3,8 @@ module github.com/hashicorp/go-changelog go 1.26.0 toolchain go1.24.8 - require ( - github.com/go-git/go-billy/v5 v5.6.2 + github.com/go-git/go-billy/v5 v5.9.0 github.com/go-git/go-git/v5 v5.16.5 github.com/google/go-github/v68 v68.0.0 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d @@ -17,7 +16,7 @@ require ( github.com/Microsoft/go-winio v0.6.2 // indirect github.com/ProtonMail/go-crypto v1.1.6 // indirect github.com/cloudflare/circl v1.6.3 // indirect - github.com/cyphar/filepath-securejoin v0.4.1 // indirect + github.com/cyphar/filepath-securejoin v0.6.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect @@ -29,9 +28,9 @@ require ( github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect github.com/skeema/knownhosts v1.3.1 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect - golang.org/x/crypto v0.45.0 // indirect - golang.org/x/net v0.47.0 // indirect - golang.org/x/sys v0.38.0 // indirect + golang.org/x/crypto v0.50.0 // indirect + golang.org/x/net v0.53.0 // indirect + golang.org/x/sys v0.43.0 // indirect google.golang.org/appengine v1.4.0 // indirect google.golang.org/protobuf v1.33.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect diff --git a/tools/go-changelog/go.sum b/tools/go-changelog/go.sum index 8ed374f9a723..669e502d83c8 100644 --- a/tools/go-changelog/go.sum +++ b/tools/go-changelog/go.sum @@ -12,8 +12,8 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= -github.com/cyphar/filepath-securejoin v0.4.1 h1:JyxxyPEaktOD+GAnqIqTf9A8tHyAG22rowi7HkoSU1s= -github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI= +github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE= +github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -25,8 +25,8 @@ github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c= github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= -github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM= -github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU= +github.com/go-git/go-billy/v5 v5.9.0 h1:jItGXszUDRtR/AlferWPTMN4j38BQ88XnXKbilmmBPA= +github.com/go-git/go-billy/v5 v5.9.0/go.mod h1:jCnQMLj9eUgGU7+ludSTYoZL/GGmii14RxKFj7ROgHw= github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4= github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII= github.com/go-git/go-git/v5 v5.16.5 h1:mdkuqblwr57kVfXri5TTH+nMFLNUxIj9Z7F5ykFbw5s= @@ -72,20 +72,20 @@ github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= -golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= -golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= +golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= +golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= +golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -97,15 +97,15 @@ golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= +golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY= +golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= +golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= diff --git a/tools/issue-labeler/labeler/enrolled_teams.yml b/tools/issue-labeler/labeler/enrolled_teams.yml index 064f15bdee0c..3718120f54a7 100755 --- a/tools/issue-labeler/labeler/enrolled_teams.yml +++ b/tools/issue-labeler/labeler/enrolled_teams.yml @@ -616,6 +616,9 @@ service/networkmanagement-connectivity-test: service/networkmanagement-insights: resources: - google_network_management_network_monitoring_provider +service/networkmanagement-vpc-flow-logs: + resources: + - google_network_management_vpc_flow_logs_config service/networksecurity-intercept: resources: - google_network_security_intercept.* diff --git a/tools/template-check/cmd/testdata/resource1.yaml b/tools/template-check/cmd/testdata/resource1.yaml index 23e0b7095803..d214cee8f592 100644 --- a/tools/template-check/cmd/testdata/resource1.yaml +++ b/tools/template-check/cmd/testdata/resource1.yaml @@ -58,3 +58,10 @@ properties: type: String description: Service id of the App Engine application required: true + +samples: + - name: "sample1" + steps: + - name: "step1" + - name: "step2" + config_path: "custom/path/to/step2.tf.tmpl" diff --git a/tools/template-check/cmd/unusedtmpl.go b/tools/template-check/cmd/unusedtmpl.go index b826e906aaa6..c3f74d32d10c 100644 --- a/tools/template-check/cmd/unusedtmpl.go +++ b/tools/template-check/cmd/unusedtmpl.go @@ -16,6 +16,7 @@ import ( const unusedTmplDesc = "Check whether any template files are not used in product yamls" var exampleFilePathReg = regexp.MustCompile(".*mmv1/templates/terraform/examples/([a-zA-Z0-9_-]+).tf.tmpl") +var sampleFilePathReg = regexp.MustCompile(".*mmv1/templates/terraform/samples/services/.*\\.tf\\.tmpl") type unusedTmplOptions struct { rootOptions *rootOptions @@ -29,8 +30,15 @@ type tree struct { type resourceYaml struct { Examples []struct { - Name string - } + Name string `yaml:"name"` + } `yaml:"examples,omitempty"` + Samples []struct { + Name string `yaml:"name"` + Steps []struct { + Name string `yaml:"name"` + ConfigPath string `yaml:"config_path,omitempty"` + } `yaml:"steps"` + } `yaml:"samples,omitempty"` } func newUnusedTmplCmd(rootOptions *rootOptions) *cobra.Command { @@ -54,7 +62,7 @@ func (o *unusedTmplOptions) run() error { if len(o.fileList) == 0 { return nil } - newCustomTmpls, newExamples := processInputFiles(o.fileList) + newCustomTmpls, newExamples, newSamples, newBaseTmpls := processInputFiles(o.fileList) found := false // get repo dir from tmpl files @@ -93,17 +101,50 @@ func (o *unusedTmplOptions) run() error { } } + if len(newSamples) > 0 { + samples, err := findSamples(productFiles) + if err != nil { + return err + } + for _, file := range newSamples { + templatePath := strings.ReplaceAll(file, repoPath+"/mmv1/", "") + if _, ok := samples[templatePath]; !ok { + found = true + fmt.Fprintf(os.Stderr, "File %s not used in any product yaml.\n", file) + } + } + } + if len(newBaseTmpls) > 0 { + codeTmpls, err := findCodeReferencedTmpls(filepath.Join(repoPath, "mmv1")) + if err != nil { + return err + } + for _, file := range newBaseTmpls { + templatePath := strings.ReplaceAll(file, repoPath+"/mmv1/", "") + templatePath = strings.TrimPrefix(templatePath, "mmv1/") + if _, ok := codeTmpls[templatePath]; !ok { + found = true + fmt.Fprintf(os.Stderr, "Base generator template %s not referenced in any mmv1 Go code or base template.\n", file) + } + } + } if found { return fmt.Errorf("found templates not used") } return nil } -func processInputFiles(fileList []string) (customTmpls []string, examples []string) { +func processInputFiles(fileList []string) (customTmpls []string, examples []string, samples []string, baseTmpls []string) { for _, v := range fileList { if exampleFilePathReg.MatchString(v) { examples = append(examples, v) + } else if sampleFilePathReg.MatchString(v) { + samples = append(samples, v) } else if strings.Contains(v, "mmv1/templates/terraform") && strings.HasSuffix(v, ".tmpl") { + if strings.HasSuffix(filepath.Dir(v), "mmv1/templates/terraform") || strings.Contains(v, "/base_configs/") || strings.Contains(v, "/static/") { + baseTmpls = append(baseTmpls, v) + continue + } customTmpls = append(customTmpls, v) } else { fmt.Printf("Skipping check for file %s\n", v) @@ -254,3 +295,60 @@ func findExamples(yamlFiles []string) (map[string]bool, error) { } return allExamples, nil } + +// findSamples parsed yaml files to get samples. +// It returns a map of samples where the key is the inferred sample path. +func findSamples(yamlFiles []string) (map[string]bool, error) { + allSamples := map[string]bool{} + for _, yamlFile := range yamlFiles { + b, err := os.ReadFile(yamlFile) + if err != nil { + return nil, err + } + + var r resourceYaml + if err := yaml.Unmarshal(b, &r); err != nil { + return nil, fmt.Errorf("failed to unmarshal yaml file for samples %s: %s", yamlFile, err) + } + packageName := filepath.Base(filepath.Dir(yamlFile)) + for _, sample := range r.Samples { + for _, step := range sample.Steps { + var tmplPath string + if step.ConfigPath != "" { + tmplPath = step.ConfigPath + } else { + tmplPath = fmt.Sprintf("templates/terraform/samples/services/%s/%s.tf.tmpl", packageName, step.Name) + } + allSamples[tmplPath] = true + } + } + } + return allSamples, nil +} + +var templateRefReg = regexp.MustCompile("[\"`](templates/terraform/[^\"`]+\\.tmpl)[\"`]") + +func findCodeReferencedTmpls(dir string) (map[string]bool, error) { + refs := map[string]bool{} + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() { + return nil + } + ext := filepath.Ext(path) + if ext == ".go" || ext == ".tmpl" { + b, err := os.ReadFile(path) + if err != nil { + return nil + } + matches := templateRefReg.FindAllStringSubmatch(string(b), -1) + for _, m := range matches { + refs[m[1]] = true + } + } + return nil + }) + return refs, err +} diff --git a/tools/template-check/cmd/unusedtmpl_test.go b/tools/template-check/cmd/unusedtmpl_test.go index a9c1961b808f..7552f455d863 100644 --- a/tools/template-check/cmd/unusedtmpl_test.go +++ b/tools/template-check/cmd/unusedtmpl_test.go @@ -12,14 +12,22 @@ func TestProcessInput(t *testing.T) { "mmv1/templates/terraform/examples/abc.go.tmpl", "mmv1/templates/terraform/examples/subfolder/abc.tf.tmpl", "mmv1/templates/terraform/custom_flatten/abc.go.tmpl", + "mmv1/templates/terraform/samples/services/workstations/workstation_cluster_custom_urls.tf.tmpl", + "mmv1/templates/terraform/list_resource.go.tmpl", + "mmv1/templates/terraform/samples/base_configs/query_test_file.go.tmpl", } - tmpl, examples := processInputFiles(fileList) - wantTmpl, wantExamples := []string{ + tmpl, examples, samples, baseTmpls := processInputFiles(fileList) + wantTmpl, wantExamples, wantSamples, wantBaseTmpls := []string{ "mmv1/templates/terraform/examples/abc.go.tmpl", "mmv1/templates/terraform/examples/subfolder/abc.tf.tmpl", "mmv1/templates/terraform/custom_flatten/abc.go.tmpl", }, []string{ "mmv1/templates/terraform/examples/abc.tf.tmpl", + }, []string{ + "mmv1/templates/terraform/samples/services/workstations/workstation_cluster_custom_urls.tf.tmpl", + }, []string{ + "mmv1/templates/terraform/list_resource.go.tmpl", + "mmv1/templates/terraform/samples/base_configs/query_test_file.go.tmpl", } if diff := cmp.Diff(wantTmpl, tmpl); diff != "" { @@ -28,6 +36,12 @@ func TestProcessInput(t *testing.T) { if diff := cmp.Diff(wantExamples, examples); diff != "" { t.Errorf("processInputFiles() got diff(-want, got) for example files = %s", diff) } + if diff := cmp.Diff(wantSamples, samples); diff != "" { + t.Errorf("processInputFiles() got diff(-want, got) for sample files = %s", diff) + } + if diff := cmp.Diff(wantBaseTmpls, baseTmpls); diff != "" { + t.Errorf("processInputFiles() got diff(-want, got) for base template files = %s", diff) + } } func TestFindTmpls(t *testing.T) { @@ -52,6 +66,7 @@ func TestFindTmpls(t *testing.T) { "templates/terraform/custom_flatten/bigquery_dataset_ref.go.tmpl": true, "templates/terraform/iam/example_config_body/app_engine_service.tf.tmpl": true, "templates/terraform/state_migrations/big_query_job.go.tmpl": true, + "custom/path/to/step2.tf.tmpl": true, } if diff := cmp.Diff(want, got); diff != "" { t.Errorf("findTmpls() got unexpected diff(-want, got) = %s", diff) @@ -84,3 +99,32 @@ func TestFindExamples(t *testing.T) { t.Errorf("findExamples() got unexpected diff(-want, got) = %s", diff) } } + +func TestFindSamples(t *testing.T) { + yamlFiles := []string{"testdata/resource1.yaml"} + got, err := findSamples(yamlFiles) + if err != nil { + t.Fatal(err) + } + + want := map[string]bool{ + "templates/terraform/samples/services/testdata/step1.tf.tmpl": true, + "custom/path/to/step2.tf.tmpl": true, + } + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("findSamples() got unexpected diff(-want, got) = %s", diff) + } +} + +func TestFindCodeReferencedTmpls(t *testing.T) { + got, err := findCodeReferencedTmpls("../../../mmv1") + if err != nil { + t.Fatal(err) + } + if !got["templates/terraform/resource.go.tmpl"] { + t.Errorf("findCodeReferencedTmpls() expected to find templates/terraform/resource.go.tmpl") + } + if !got["templates/terraform/examples/base_configs/test_file.go.tmpl"] { + t.Errorf("findCodeReferencedTmpls() expected to find templates/terraform/examples/base_configs/test_file.go.tmpl") + } +} diff --git a/tpgtools/BUILD.bazel b/tpgtools/BUILD.bazel deleted file mode 100644 index a26c4323dd55..000000000000 --- a/tpgtools/BUILD.bazel +++ /dev/null @@ -1,358 +0,0 @@ -load("@rules_go//go:def.bzl", "go_binary", "go_library") - -RESOURCES = { - "apikeys_key": { - "service": "apikeys", - "resource": "key", - "docs": True, - "sweeper": True, - "test": True, - }, - "assured_workloads_workload": { - "service": "assuredworkloads", - "resource": "workload", - "docs": True, - "sweeper": False, - "test": True, - }, - "cloudbuild_worker_pool": { - "service": "cloudbuild", - "resource": "worker_pool", - "docs": False, - "sweeper": True, - "test": False, - }, - "clouddeploy_delivery_pipeline": { - "service": "clouddeploy", - "resource": "delivery_pipeline", - "docs": True, - "sweeper": True, - "test": True, - }, - "clouddeploy_target": { - "service": "clouddeploy", - "resource": "target", - "docs": True, - "sweeper": True, - "test": True, - }, - "container_aws_cluster": { - "service": "containeraws", - "resource": "cluster", - "docs": True, - "sweeper": False, - "test": True, - }, - "container_aws_node_pool": { - "service": "containeraws", - "resource": "node_pool", - "docs": True, - "sweeper": False, - "test": True, - }, - "container_azure_client": { - "service": "containerazure", - "resource": "client", - "docs": True, - "sweeper": False, - "test": True, - }, - "container_azure_cluster": { - "service": "containerazure", - "resource": "cluster", - "docs": True, - "sweeper": False, - "test": True, - }, - "container_azure_node_pool": { - "service": "containerazure", - "resource": "node_pool", - "docs": True, - "sweeper": False, - "test": True, - }, - "dataplex_asset": { - "service": "dataplex", - "resource": "asset", - "docs": True, - "sweeper": False, - "test": True, - }, - "dataplex_lake": { - "service": "dataplex", - "resource": "lake", - "docs": True, - "sweeper": True, - "test": True, - }, - "dataplex_zone": { - "service": "dataplex", - "resource": "zone", - "docs": True, - "sweeper": False, - "test": True, - }, - "dataproc_workflow_template": { - "service": "dataproc", - "resource": "workflow_template", - "docs": False, - "sweeper": True, - "test": False, - }, - "firebaserules_release": { - "service": "firebaserules", - "resource": "release", - "docs": True, - "sweeper": True, - "test": True, - }, - "firebaserules_ruleset": { - "service": "firebaserules", - "resource": "ruleset", - "docs": True, - "sweeper": True, - "test": True, - }, - "gke_hub_feature_membership": { - "service": "gkehub", - "resource": "feature_membership", - "docs": False, - "sweeper": False, - "test": False, - }, - "recaptcha_enterprise_key": { - "service": "recaptchaenterprise", - "resource": "key", - "docs": True, - "sweeper": True, - "test": True, - }, -} - -SERVICES = set([v["service"] for k, v in RESOURCES.items()]) - -filegroup( - name = "api", - srcs = glob([ - "api/**/*", - ]), -) - -filegroup( - name = "overrides", - srcs = glob([ - "overrides/**/*", - ]), -) - -filegroup( - name = "templates", - srcs = glob([ - "templates/**/*", - ]), -) - -genrule( - name = "empty_serialization", - srcs = [ - "serialization.go.base", - ], - outs = ["empty_serialization.go"], - cmd = "cp $< $@", - visibility = ["//visibility:private"], -) - -genrule( - name = "bootstrapped_serialization", - srcs = [ - ":api", - ":overrides", - ":templates", - ], - outs = ["serialization.go"], - cmd = "$(location :bootstrap_tpgtools) --overrides tpgtools/overrides --path tpgtools/api --templates tpgtools/templates --mode serialization --output $(@D)", - tools = [":bootstrap_tpgtools"], - visibility = ["//visibility:private"], -) - -go_binary( - name = "bootstrap_tpgtools", - srcs = [ - "documentation.go", - "file_utils.go", - "id.go", - "main.go", - "main_helpers.go", - "misc_utils.go", - "names.go", - "override.go", - "override_details.go", - "product.go", - "property.go", - "property_helpers.go", - "resource.go", - "sample.go", - "serialization_helpers.go", - "strings.go", - "type.go", - "versions.go", - ":empty_serialization", - ], - visibility = ["//visibility:private"], - deps = [ - "@com_github_golang_glog//:glog", - "@com_github_googlecloudplatform_declarative_resource_client_library//dcl", - "@com_github_googlecloudplatform_declarative_resource_client_library//services", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager/alpha", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager/beta", - "@com_github_hashicorp_hcl//hcl/fmtcmd", - "@com_github_kylelemons_godebug//pretty", - "@com_github_nasa9084_go_openapi//:go-openapi", - "@in_gopkg_yaml_v2//:yaml_v2", - "@org_bitbucket_creachadair_stringset//:stringset", - ], -) - -go_binary( - name = "tpgtools_compiler", - srcs = [ - "documentation.go", - "file_utils.go", - "id.go", - "main.go", - "main_helpers.go", - "misc_utils.go", - "names.go", - "override.go", - "override_details.go", - "product.go", - "property.go", - "property_helpers.go", - "resource.go", - "sample.go", - "serialization_helpers.go", - "strings.go", - "type.go", - "versions.go", - ":bootstrapped_serialization", - ], - visibility = ["//visibility:private"], - deps = [ - "@com_github_golang_glog//:glog", - "@com_github_googlecloudplatform_declarative_resource_client_library//dcl", - "@com_github_googlecloudplatform_declarative_resource_client_library//services", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager/alpha", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager/beta", - "@com_github_hashicorp_hcl//hcl/fmtcmd", - "@com_github_kylelemons_godebug//pretty", - "@com_github_nasa9084_go_openapi//:go-openapi", - "@in_gopkg_yaml_v2//:yaml_v2", - "@org_bitbucket_creachadair_stringset//:stringset", - ] + ["@com_github_googlecloudplatform_declarative_resource_client_library//services/google/" + s for s in SERVICES] + - ["@com_github_googlecloudplatform_declarative_resource_client_library//services/google/" + s + "/beta" for s in SERVICES], -) - -genrule( - name = "tpgtools", - srcs = [ - ":api", - ":overrides", - ":templates", - ], - outs = [ - "terraform-provider-google/google/provider/provider_dcl_resources.go", - "terraform-provider-google/google/transport/provider_dcl_client_creation.go", - ] + ["terraform-provider-google/google/services/{}/resource_{}.go".format( - v["service"], - k, - ) for (k, v) in RESOURCES.items()] + - ["terraform-provider-google/google/services/{}/resource_{}_sweeper.go".format( - v["service"], - k, - ) for (k, v) in RESOURCES.items() if v["sweeper"] == True] + - ["terraform-provider-google/google/services/{}/resource_{}_generated_test.go".format( - v["service"], - k, - ) for (k, v) in RESOURCES.items() if v["test"] == True] + - ["terraform-provider-google/website/docs/r/{}.html.markdown".format(k) for (k, v) in RESOURCES.items() if v["docs"] == True], - cmd = "$(location :tpgtools_compiler) --overrides tpgtools/overrides --path tpgtools/api --templates tpgtools/templates --version ga --output $(RULEDIR)/terraform-provider-google", - tools = [":tpgtools_compiler"], - visibility = ["//visibility:public"], -) - -genrule( - name = "tpgtools_beta", - srcs = [ - ":api", - ":overrides", - ":templates", - ], - outs = [ - "terraform-provider-google-beta/google-beta/provider/provider_dcl_resources.go", - "terraform-provider-google-beta/google-beta/transport/provider_dcl_client_creation.go", - ] + ["terraform-provider-google-beta/google-beta/services/{}/resource_{}.go".format( - v["service"], - k, - ) for (k, v) in RESOURCES.items()] + - ["terraform-provider-google-beta/google-beta/services/{}/resource_{}_sweeper.go".format( - v["service"], - k, - ) for (k, v) in RESOURCES.items() if v["sweeper"] == True] + - ["terraform-provider-google-beta/google-beta/services/{}/resource_{}_generated_test.go".format( - v["service"], - k, - ) for (k, v) in RESOURCES.items() if v["test"] == True] + - ["terraform-provider-google-beta/website/docs/r/{}.html.markdown".format(k) for (k, v) in RESOURCES.items() if v["docs"] == True], - cmd = "$(location :tpgtools_compiler) --overrides tpgtools/overrides --path tpgtools/api --templates tpgtools/templates --version beta --output $(RULEDIR)/terraform-provider-google-beta", - tools = [":tpgtools_compiler"], - visibility = ["//visibility:public"], -) - -# The tpgtools_lib is generated by gazelle but is unused by the other targets -# in this file, which need to specifically depend on either the initial empty -# version of serialization.go or the generated version. The `gazelle:exclude` -# line here makes the target buildable even though it's unused, allowing -# bazel build //tpgtools/... to succeed. -# -# gazelle:exclude serialization.go -go_library( - name = "tpgtools_lib", - srcs = [ - "documentation.go", - "empty_serialization.go", - "file_utils.go", - "id.go", - "main.go", - "main_helpers.go", - "misc_utils.go", - "names.go", - "override.go", - "override_details.go", - "product.go", - "property.go", - "property_helpers.go", - "resource.go", - "sample.go", - "serialization_helpers.go", - "strings.go", - "type.go", - "versions.go", - ], - importpath = "github.com/GoogleCloudPlatform/magic-modules/tpgtools", - visibility = ["//visibility:private"], - deps = [ - "@com_github_golang_glog//:glog", - "@com_github_googlecloudplatform_declarative_resource_client_library//dcl", - "@com_github_googlecloudplatform_declarative_resource_client_library//services", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager/alpha", - "@com_github_googlecloudplatform_declarative_resource_client_library//services/google/cloudresourcemanager/beta", - "@com_github_hashicorp_hcl//hcl/fmtcmd", # keep - "@com_github_kylelemons_godebug//pretty", - "@com_github_nasa9084_go_openapi//:go-openapi", - "@in_gopkg_yaml_v2//:yaml_v2", - "@org_bitbucket_creachadair_stringset//:stringset", - ], -) diff --git a/tpgtools/README.md b/tpgtools/README.md deleted file mode 100644 index 8ae74dddbfd9..000000000000 --- a/tpgtools/README.md +++ /dev/null @@ -1,263 +0,0 @@ -# tpgtools - -`tpgtools` is the generator responsible for creating DCL-based resources in the -Terraform provider for Google Cloud (TPG). The DCL provides -[OpenAPI schema objects](https://swagger.io/specification/#schema-object) to -describe the available types, and `tpgtools` uses those to construct Terraform -resource schemas. - -## Usage - -`tpgtools` expects to run targeting a "root service directory", a dir-of-dirs -where the child dirs contain OpenApi specs for resources such as the `api/` path -above. Additionally, overrides are expected in a similar structure (as seen in -the `overrides/` path. For example: - -``` -go run . --path "api" --overrides "overrides" -``` - -This will output the file contents of each resource to stdout, for fast -iteration. You can filter by service and resource to make it more useful: - -``` -go run . --path "api" --overrides "overrides" --service redis --resource instance -``` - -To persist the output(s) to files you can specify an output path. This is the -most familiar experience for MMv1 developers. For example: - -``` -go run . --path "api" --overrides "overrides" --output ~/tpg-fork -``` - -If generation fails, an error should be logged showing what went wrong. The raw -output will be returned, and line numbers (if available in the error) will -correspond to the line numbers in the output. - -### Version - -You can specify a version such as `beta` using the `--version`: - -``` -go run . --path "api" --overrides "overrides" --output ~/tpg-fork --version "beta" -``` - -### Accessory Code - -To generate accessory code such as `serializarion`, you can specify the -`--mode`: - -``` -go run . --path "api" --overrides "overrides" --output ~/some/dir --mode "serialization" -``` - -## New Resource Guide - -This guide is written to document the process for adding a resource to the -Terraform provider for Google Cloud (TPG) after it has been added to the -[DCL](https://github.com/GoogleCloudPlatform/declarative-resource-client-library). - -### Adding Resource Overrides - -Every resource added via tpgtools needs an override file for every version it is -available at. This file should be empty, but must exist. A resource available at -GA (TPG) must also exist at beta (TPGB) and needs a corresponding override file -at beta. These override files are often identical between versions. This file -should exist at tpgtools/overrides/$PRODUCT_NAME/$VERSION/$RESOURCE.yaml. For -example, -[this override](https://github.com/GoogleCloudPlatform/magic-modules/blob/main/tpgtools/overrides/assuredworkloads/beta/workload.yaml) -exists for the product assuredworkloads resource workload at beta version. - -Override files contain information on how the Terraform representation of the -resource should be different from the DCL's representation. This could be naming -or behavior differences, but for a new resource implemented through tpgtools -there should be no differences from the DCL's representation. - -### Adding Samples - -For a deeper understanding on test anatomy please read the accompanying -[Tests and Sample Anatomy](#tests-and-sample-anatomy) - -#### Create a meta.yaml file - -Create a meta.yaml file in the overrides directory for the resource. For -example, -[this meta.yaml](https://github.com/GoogleCloudPlatform/magic-modules/blob/main/tpgtools/overrides/assuredworkloads/samples/workload/meta.yaml) -file exists for the assured workloads resource. This file will merge with any -tests. You can customize behavior of the tests and examples generated dcl -samples data (injections, hiding, ect..). See -[the section of the meta.yaml file](#the-metayaml-file) for a more detailed -dive. - -#### Adding DCL Tests - -Start by copying the relevant samples from the DCL for your new resource. These -will be added to the -[tpgtools/api folder](https://github.com/GoogleCloudPlatform/magic-modules/tree/main/tpgtools/api) -under the relevant product. These samples can be found under the samples/ folder -within the DCL for the resource being added. For example, assured workloads can -be found -[here](https://github.com/GoogleCloudPlatform/declarative-resource-client-library/tree/main/services/google/assuredworkloads/samples). - -Re-serialize `serialization.go` to enable generating configs from samples by -running: - -``` -make serialize -``` - -#### Adding a Non DCL Test - -In some cases you may need to add a non DCL test when either the current tests -are insufficient or you want to showcase/test some specific behavior not present -in the dcl tests. - -If you need to write tests manually you can add terraform templates to the -relevant `./overrides//samples/` folder. - -A terraform template test has the following anatomy. - -* `.yaml` - this is the test definition -* `.tf.tmpl` - this is the accompanying terraform configuration. A companion to the definition if you will. - -The `.yaml` test specific configurations. For example it lists the -variables to replace in the template companion. You can also add additional -templates as updates. This will act as sequential applies and are useful for -testing update specific behavior. Make sure any templates added as an update has -the `_update.tf.tmpl` extension. - -The following is an example test definition. - -```yaml -updates: -- resource: ./basic_update.tf.tmpl -variables: - - name: "name" - type: "resource_name" - - name: "region" - type: "region" -``` - -The `.tf.tmpl` file is simply a terraform configuration. Any -replacements should be surrounding by double brackets `{{ }}`. The variable name -from the test definition will be used to key into and replace these. - -### Adding Documentation - -Provided you have added samples for the resource, documentation will be -automatically generated based on the resource description in the DCL and -examples will be generated from the samples for this resource. If you did not -provide samples for the resource, then documentation will need to be written by -hand. - -### Handwritten Tests - -Sometimes you may need to test unusual resource behavior in a way that does not -fit well with generated tests. In this circumstance you can write a -[handwritten test file](https://github.com/GoogleCloudPlatform/magic-modules/blob/main/mmv1/third_party/terraform/README.md#testing) -and add it -[here](https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/third_party/terraform/tests). - -These tests can be used for more granular testing of specific behavior and add -custom checks. Tests in these files will not have examples generated for them, -so handwritten tests should not be considered a replacement for samples. - -## Development - -`tpgtools` builds resources using Go Templates, with the templates stored under -the `templates/` directory. They're fed the `Resource` type, which contains -resource-level metadata and a list of `Property` types which represent top-level -fields in a Terraform resource. Additionally, `Property`s can contain other -`Property` objects to create a nested structure of fields. - -`main.go` parses the OpenAPI schemas you've selected into Go structs and then -transforms them into `Resource`/`Property` before running them through Go -Templates. - -### Overrides - -Overrides are specified per-resource, with a directory structure parallel to the -OpenAPI specs. Inside each resource file is an unordered array of overrides made -up of an override type (like `CUSTOM_DESCRIPTION` or `VIRTUAL_FIELD`) as well as -a field they affect (if a field is omitted, they affect the resource) and an -optional `details` object that will be parsed for additional metadata. - -For example, override entries will look like the following: - -```yaml -- type: CUSTOM_DESCRIPTION - field: lifecycle.rule.condition.age - details: - description: Custom description here. -``` - -### Tests and Sample Anatomy - -Adding samples is essential for generating tests and documentation. In fact -Documentation won't generate without it! - -Tests come from two sources. - -* The top level api (`./api`) folder. If you look -in here you'll see a bunch of yaml files and json files. These are DCL tests! -Forked from the dcl library. -* The override folder -(`./overrides//samples/`). This contains `meta.yaml` a file -used for managing resource-wide test configurations and custom non-dcl tests. - -In either case, DCL or non-DCL, every test definition is a yaml file which takes -in variables. - -```yaml -variables: - - name: "name" - type: "resource_name" - - name: "org_id" - type: "org_id" -``` - -`type` is inferred from `sample.go`'s translation map to figure out what needs -to be placed in the field. `name` is used for substitution in the file itself -and in the case of `resource_name`, actually used to create the value itself. - -#### The meta.yaml file - -In the `./overrides//samples/` a `meta.yaml` file exists -which controls configuration which applies to multiple tests or hiding/showing -specific tests. - -If you need to hide sample from a doc or disable a sample from the tests you can -do so here. - -```yaml -doc_hide: - - basic.tf.tmpl - - full.tf.tmpl -test_hide: - - basic_workload.yaml -``` - -If you want to add additional rules the following options are currently supported within `meta.yaml` - -```yaml -ignore_read: - - "billing_account" - - "kms_settings" - - "resource_settings" - - "provisioned_resources_parent" -check: - - deleteAssuredWorkloadProvisionedResources(t) -extra_dependencies: - - "time" - - "log" - - "strconv" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -code_inject: - - delete_assured_workload_provisioned_resources.go -doc_hide: - - basic.tf.tmpl # basic_update.tf.tmpl auto hides - - full.tf.tmpl -test_hide: - - basic_workload.yaml -``` diff --git a/tpgtools/api/apikeys/samples/android.key.json b/tpgtools/api/apikeys/samples/android.key.json deleted file mode 100755 index 65b3de5011e1..000000000000 --- a/tpgtools/api/apikeys/samples/android.key.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "androidKeyRestrictions": { - "allowedApplications": [ - { - "packageName": "com.example.app123", - "sha1Fingerprint": "1699466a142d4682a5f91b50fdf400f2358e2b0b" - } - ] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/android_key.yaml b/tpgtools/api/apikeys/samples/android_key.yaml deleted file mode 100755 index 31ced31a3b37..000000000000 --- a/tpgtools/api/apikeys/samples/android_key.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: android_key -description: A basic example of a android api keys key -type: key -versions: -- ga -resource: samples/android.key.json -updates: -- resource: samples/android_update.key.json -variables: -- name: app - type: resource_name -- name: billing_account - type: billing_account -- name: key - type: resource_name -- name: org_id - type: org_id diff --git a/tpgtools/api/apikeys/samples/android_update.key.json b/tpgtools/api/apikeys/samples/android_update.key.json deleted file mode 100755 index 4d565fbcbc8c..000000000000 --- a/tpgtools/api/apikeys/samples/android_update.key.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "androidKeyRestrictions": { - "allowedApplications": [ - { - "packageName": "com.example.app124", - "sha1Fingerprint": "1cf89aa28625da86a7e5a7550cf7fd33d611f6fd" - } - ] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/apikeys.serviceusage.service.json b/tpgtools/api/apikeys/samples/apikeys.serviceusage.service.json deleted file mode 100755 index 8a59d7ec7bcb..000000000000 --- a/tpgtools/api/apikeys/samples/apikeys.serviceusage.service.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "apikeys.googleapis.com", - "state": "ENABLED" -} diff --git a/tpgtools/api/apikeys/samples/basic.key.json b/tpgtools/api/apikeys/samples/basic.key.json deleted file mode 100755 index ad86c006519d..000000000000 --- a/tpgtools/api/apikeys/samples/basic.key.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "browserKeyRestrictions": { - "allowedReferrers": [".*"] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/basic_key.yaml b/tpgtools/api/apikeys/samples/basic_key.yaml deleted file mode 100755 index a43631f4924b..000000000000 --- a/tpgtools/api/apikeys/samples/basic_key.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: basic_key -description: A basic example of a api keys key -type: key -versions: -- ga -resource: samples/basic.key.json -updates: -- resource: samples/update.key.json -variables: -- name: app - type: resource_name -- name: billing_account - type: billing_account -- name: key - type: resource_name -- name: org_id - type: org_id diff --git a/tpgtools/api/apikeys/samples/ios.key.json b/tpgtools/api/apikeys/samples/ios.key.json deleted file mode 100755 index fd8c0f87188b..000000000000 --- a/tpgtools/api/apikeys/samples/ios.key.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "iosKeyRestrictions": { - "allowedBundleIds": ["com.google.app.macos"] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/ios_key.yaml b/tpgtools/api/apikeys/samples/ios_key.yaml deleted file mode 100755 index 5af5d1714b33..000000000000 --- a/tpgtools/api/apikeys/samples/ios_key.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: ios_key -description: A basic example of a ios api keys key -type: key -versions: -- ga -resource: samples/ios.key.json -updates: -- resource: samples/ios_update.key.json -variables: -- name: app - type: resource_name -- name: billing_account - type: billing_account -- name: key - type: resource_name -- name: org_id - type: org_id diff --git a/tpgtools/api/apikeys/samples/ios_update.key.json b/tpgtools/api/apikeys/samples/ios_update.key.json deleted file mode 100755 index a218d9aefdec..000000000000 --- a/tpgtools/api/apikeys/samples/ios_update.key.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "iosKeyRestrictions": { - "allowedBundleIds": ["com.google.alex.ios"] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/minimal.key.json b/tpgtools/api/apikeys/samples/minimal.key.json deleted file mode 100755 index 351f34304e8c..000000000000 --- a/tpgtools/api/apikeys/samples/minimal.key.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key" -} diff --git a/tpgtools/api/apikeys/samples/minimal_key.yaml b/tpgtools/api/apikeys/samples/minimal_key.yaml deleted file mode 100755 index a1e424a4a2c7..000000000000 --- a/tpgtools/api/apikeys/samples/minimal_key.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: minimal_key -description: A minimal example of a api keys key -type: key -versions: -- ga -resource: samples/minimal.key.json -variables: -- name: app - type: resource_name -- name: billing_account - type: billing_account -- name: key - type: resource_name -- name: org_id - type: org_id diff --git a/tpgtools/api/apikeys/samples/server.key.json b/tpgtools/api/apikeys/samples/server.key.json deleted file mode 100755 index 083c18cc22b8..000000000000 --- a/tpgtools/api/apikeys/samples/server.key.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "serverKeyRestrictions": { - "allowedIps": ["127.0.0.1"] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/server_key.yaml b/tpgtools/api/apikeys/samples/server_key.yaml deleted file mode 100755 index ed36aaf9e6b4..000000000000 --- a/tpgtools/api/apikeys/samples/server_key.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: server_key -description: A basic example of a server api keys key -type: key -versions: -- ga -resource: samples/server.key.json -updates: -- resource: samples/server_update.key.json -variables: -- name: app - type: resource_name -- name: billing_account - type: billing_account -- name: key - type: resource_name -- name: org_id - type: org_id diff --git a/tpgtools/api/apikeys/samples/server_update.key.json b/tpgtools/api/apikeys/samples/server_update.key.json deleted file mode 100755 index aa5927b712ed..000000000000 --- a/tpgtools/api/apikeys/samples/server_update.key.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{key}}", - "displayName": "sample-key", - "restrictions": { - "serverKeyRestrictions": { - "allowedIps": ["127.0.0.2", "192.168.1.1"] - }, - "apiTargets": [ - { - "service": "translate.googleapis.com", - "methods": ["GET*"] - } - ] - } -} diff --git a/tpgtools/api/apikeys/samples/update.key.json b/tpgtools/api/apikeys/samples/update.key.json deleted file mode 100755 index 05925b608e37..000000000000 --- a/tpgtools/api/apikeys/samples/update.key.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name":"{{key}}", - "displayName": "sample-key-update", - "restrictions": { - "browserKeyRestrictions": { - "allowedReferrers": [".*com"] - }, - "apiTargets": [ - { - "service": "maps.googleapis.com", - "methods": ["POST*"] - } - ] - } -} diff --git a/tpgtools/api/assuredworkloads/samples/basic.workload.json b/tpgtools/api/assuredworkloads/samples/basic.workload.json deleted file mode 100755 index eacbc711d185..000000000000 --- a/tpgtools/api/assuredworkloads/samples/basic.workload.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "organization": "{{org_id}}", - "location": "{{region}}", - "displayName": "{{display}}", - "complianceRegime": "FEDRAMP_MODERATE", - "billingAccount": "billingAccounts/{{billing_account}}", - "labels": { - "label-one": "value-one" - }, - "provisionedResourcesParent": "folders/519620126891", - "violationNotificationsEnabled": true, - "kmsSettings": { - "nextRotationTime": "9999-10-02T15:01:23Z", - "rotationPeriod": "10368000s" - }, - "workloadOptions": { - "kajEnrollmentType": "KEY_ACCESS_TRANSPARENCY_OFF" - }, - "resourceSettings": [ - { - "resourceType": "CONSUMER_FOLDER", - "displayName": "{{name}}" - }, - { - "resourceType": "ENCRYPTION_KEYS_PROJECT" - }, - { - "resourceId": "{{ring}}", - "resourceType": "KEYRING" - } - ] -} \ No newline at end of file diff --git a/tpgtools/api/assuredworkloads/samples/basic_workload.yaml b/tpgtools/api/assuredworkloads/samples/basic_workload.yaml deleted file mode 100755 index 8a27e677a25b..000000000000 --- a/tpgtools/api/assuredworkloads/samples/basic_workload.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -description: A basic test of a assuredworkloads api -name: basic_workload -resource: samples/basic.workload.json -updates: -- resource: samples/update.workload.json -variables: -- name: region - type: region -- name: ring - type: resource_name -- name: org_id - type: org_id -- name: billing_account - type: billing_account -versions: -- ga -- beta diff --git a/tpgtools/api/assuredworkloads/samples/sovereign_controls.workload.json b/tpgtools/api/assuredworkloads/samples/sovereign_controls.workload.json deleted file mode 100644 index f75313bc7777..000000000000 --- a/tpgtools/api/assuredworkloads/samples/sovereign_controls.workload.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "organization": "{{org_id}}", - "location": "europe-west9", - "displayName": "{{display}}", - "complianceRegime": "EU_REGIONS_AND_SUPPORT", - "billingAccount": "billingAccounts/{{billing_account}}", - "labels": { - "label-one": "value-one" - }, - "enableSovereignControls": true, - "kmsSettings": { - "nextRotationTime": "9999-10-02T15:01:23Z", - "rotationPeriod": "10368000s" - }, - "resourceSettings": [ - { - "resourceType": "CONSUMER_FOLDER" - }, - { - "resourceType": "ENCRYPTION_KEYS_PROJECT" - }, - { - "resourceId": "{{ring}}", - "resourceType": "KEYRING" - } - ] -} \ No newline at end of file diff --git a/tpgtools/api/assuredworkloads/samples/sovereign_controls_workload.yaml b/tpgtools/api/assuredworkloads/samples/sovereign_controls_workload.yaml deleted file mode 100644 index bcb6e5fbd7ea..000000000000 --- a/tpgtools/api/assuredworkloads/samples/sovereign_controls_workload.yaml +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2023 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: sovereign_controls_workload -description: A Sovereign Controls test of the assuredworkloads api -type: workload -versions: -- beta -resource: samples/sovereign_controls.workload.json -updates: -- resource: samples/update_sovereign_controls.workload.json - dependencies: [] -variables: -- name: billing_account - type: billing_account -- name: display - type: resource_name -- name: org_id - type: org_id -- name: ring - type: resource_name \ No newline at end of file diff --git a/tpgtools/api/assuredworkloads/samples/split_billing_partner.workload.json b/tpgtools/api/assuredworkloads/samples/split_billing_partner.workload.json deleted file mode 100644 index 75652da283f5..000000000000 --- a/tpgtools/api/assuredworkloads/samples/split_billing_partner.workload.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "organization": "{{org_id}}", - "location": "europe-west8", - "displayName": "{{display}}", - "complianceRegime": "ASSURED_WORKLOADS_FOR_PARTNERS", - "billingAccount": "billingAccounts/{{billing_account}}", - "partnerServicesBillingAccount": "billingAccounts/01BF3F-2C6DE5-30C607", - "labels": { - "label-one": "value-one" - }, - "partner": "SOVEREIGN_CONTROLS_BY_PSN", - "partnerPermissions": { - "dataLogsViewer": true, - "serviceAccessApprover": true, - "assuredWorkloadsMonitoring": true - }, - "violationNotificationsEnabled": true, - "resourceSettings": [ - { - "resourceType": "CONSUMER_FOLDER" - }, - { - "resourceType": "ENCRYPTION_KEYS_PROJECT" - }, - { - "resourceId": "{{ring}}", - "resourceType": "KEYRING" - } - ] - } \ No newline at end of file diff --git a/tpgtools/api/assuredworkloads/samples/split_billing_partner_workload.yaml b/tpgtools/api/assuredworkloads/samples/split_billing_partner_workload.yaml deleted file mode 100644 index 92533710e151..000000000000 --- a/tpgtools/api/assuredworkloads/samples/split_billing_partner_workload.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2024 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: split_billing_partner_workload -description: A Split billing partner test of the assuredworkloads api -type: workload -versions: -- beta -resource: samples/split_billing_partner.workload.json -variables: -- name: billing_account - type: billing_account -- name: display - type: resource_name -- name: org_id - type: org_id -- name: ring - type: resource_name \ No newline at end of file diff --git a/tpgtools/api/assuredworkloads/samples/update.workload.json b/tpgtools/api/assuredworkloads/samples/update.workload.json deleted file mode 100755 index 2e1262782b92..000000000000 --- a/tpgtools/api/assuredworkloads/samples/update.workload.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "{{ref:basic.workload.json:name}}", - "organization": "{{org_id}}", - "location": "{{region}}", - "displayName": "updated-example", - "billingAccount": "billingAccounts/{{billing_account}}", - "complianceRegime": "FEDRAMP_MODERATE", - "labels": { - "label-two": "value-two" - } -} diff --git a/tpgtools/api/assuredworkloads/samples/update_sovereign_controls.workload.json b/tpgtools/api/assuredworkloads/samples/update_sovereign_controls.workload.json deleted file mode 100644 index 99fa43989bb9..000000000000 --- a/tpgtools/api/assuredworkloads/samples/update_sovereign_controls.workload.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "{{ref:__state__:name}}", - "organization": "{{org_id}}", - "location": "europe-west9", - "displayName": "updated-example", - "billingAccount": "billingAccounts/{{billing_account}}", - "complianceRegime": "EU_REGIONS_AND_SUPPORT", - "labels": { - "label-two": "value-two-eu-regions-and-support" - } -} \ No newline at end of file diff --git a/tpgtools/api/cloudbuildv2/samples/gle_priv.connection.json b/tpgtools/api/cloudbuildv2/samples/gle_priv.connection.json deleted file mode 100755 index dee42db482f1..000000000000 --- a/tpgtools/api/cloudbuildv2/samples/gle_priv.connection.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "{{connection}}", - "gitlabConfig": { - "hostUri": "https://gle-us.gle-us-private.com", - "serviceDirectoryConfig": { - "service": "projects/407304063574/locations/us-west1/namespaces/private-conn/services/gitlab-private" - }, - "sslCa": "-----BEGIN CERTIFICATE-----\nMIIDcTCCAlmgAwIBAgIUbxJ3jxaRf5IPcUiQWRPRqpLL4s4wDQYJKoZIhvcNAQEL\nBQAwTjELMAkGA1UEBhMCVVMxGzAZBgNVBAoMEkdvb2dsZSBDbG91ZCBCdWlsZDEi\nMCAGA1UEAwwZZ2xlLXVzLmdsZS11cy1wcml2YXRlLmNvbTAeFw0yMzEwMjAxNjQ3\nNDJaFw0yNDEwMTkxNjQ3NDJaME4xCzAJBgNVBAYTAlVTMRswGQYDVQQKDBJHb29n\nbGUgQ2xvdWQgQnVpbGQxIjAgBgNVBAMMGWdsZS11cy5nbGUtdXMtcHJpdmF0ZS5j\nb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDRE84wKcuzc+beQ323\nIsNVVOF1+WZ975LvXpIt8Mw1bcYeYUcvgBXSXAByHGMtef8OBb9BUvLOVZdT3Xow\nCUbhCiK3zQy29pCn0rsneIvzGUXQgQRXK/Zap1N/hif4E7CIgjuvCN0Mn6BfDV/H\nXFm6EV3YUJrRPBr1rZik7doaYYwaJshCSTBtZxXZdvsG/OBuAXbJ9GB0B62EiTBz\n5g6yRdATut+PbgfzaWlPsgL3TTH+HPNCMO+ULnFupfZwRCtV+dJng76QYGs8fmFo\ntiWeElcsU8W7aqmjOkKRWcFsHpxPNXp8GG+jsZrVAnMOR3QeRLvowysSQD99IrGH\nAhwlAgMBAAGjRzBFMCQGA1UdEQQdMBuCGWdsZS11cy5nbGUtdXMtcHJpdmF0ZS5j\nb20wHQYDVR0OBBYEFKCIp5BruT4fpeDFQ2bKgdUvpfbWMA0GCSqGSIb3DQEBCwUA\nA4IBAQAQ4pUQmmd7eNIu9MQGna9lHYRFL0/G3mrK6Dcfm2As9qdcRw3dph8/iute\nxKDdBsnt6jDHrsjN0Na7Eq0040oBJrxG/NtqGX0zHNdpAT61bQ6j9reAT+KOrHys\nDJXH2lPuFW183AU7mmvcbXTEwkKex1i+DNoEdGYUbBfnWWeuhGzFog+/f9mtjoHL\nplcmx0VWHBQ5KO9Aq4OR/86DSg5QRPk76W9k3cM2ShXMm3TmTBZ+taJFfjZo5jP+\n7PLt2z9grSvFSXh2jnMyAs2yP4c+WezOXZLijqROr378AGBaksQK0CP+CYjZRpn1\nvndr1njLbvSjIypwKgZROb4P6XVa\n-----END CERTIFICATE-----\n", - "authorizerCredential": { - "userTokenSecretVersion": "projects/407304063574/secrets/gle-private-api/versions/1" - }, - "readAuthorizerCredential": { - "userTokenSecretVersion": "projects/407304063574/secrets/gle-private-read-token/versions/1" - }, - "webhookSecretSecretVersion":"projects/407304063574/secrets/gle-webhook-secret/versions/latest" - }, - "project": "{{project}}", - "location": "us-west1" -} \ No newline at end of file diff --git a/tpgtools/api/clouddeploy/samples/add_first_execution_config.target.json b/tpgtools/api/clouddeploy/samples/add_first_execution_config.target.json deleted file mode 100644 index e6f5150ca91f..000000000000 --- a/tpgtools/api/clouddeploy/samples/add_first_execution_config.target.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "requireApproval": true, - "gke": { - "cluster": "projects/{{project}}/locations/{{region}}/clusters/different-example-cluster-name", - "internalIp": true - }, - "executionConfigs": [ - { - "usages": ["RENDER", "DEPLOY"], - "serviceAccount": "pool-owner@{{project}}.iam.gserviceaccount.com", - "artifactStorage": "gs://my-bucket/my-dir" - } - ] -} diff --git a/tpgtools/api/clouddeploy/samples/add_second_execution_config.target.json b/tpgtools/api/clouddeploy/samples/add_second_execution_config.target.json deleted file mode 100644 index 095161084ee3..000000000000 --- a/tpgtools/api/clouddeploy/samples/add_second_execution_config.target.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "requireApproval": true, - "gke": { - "cluster": "projects/{{project}}/locations/{{region}}/clusters/different-example-cluster-name", - "internalIp": true - }, - "executionConfigs": [ - { - "usages": ["RENDER"], - "serviceAccount": "pool-owner@{{project}}.iam.gserviceaccount.com", - "artifactStorage": "gs://my-bucket/my-dir" - }, - { - "usages": ["DEPLOY"], - "workerPool": "projects/{{project}}/locations/{{region}}/workerPools/my-deploy-pool", - "serviceAccount": "deploy-pool-owner@{{project}}.iam.gserviceaccount.com", - "artifactStorage": "gs://deploy-bucket/deploy-dir" - } - ] -} diff --git a/tpgtools/api/clouddeploy/samples/basic.delivery_pipeline.json b/tpgtools/api/clouddeploy/samples/basic.delivery_pipeline.json deleted file mode 100644 index ba6a8b6f7260..000000000000 --- a/tpgtools/api/clouddeploy/samples/basic.delivery_pipeline.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "{{pipeline}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "basic description", - "annotations": { - "my_first_annotation": "example-annotation-1", - "my_second_annotation": "example-annotation-2" - }, - "labels": { - "my_first_label": "example-label-1", - "my_second_label": "example-label-2" - }, - "serialPipeline": { - "stages": [ - { - "targetId": "example-target-one", - "profiles": [ - "example-profile-one", - "example-profile-two" - ], - "deployParameters": [ - { - "values": { - "deployParameterKey": "deployParameterValue" - }, - "match_target_labels": { - "my_first_label": "example-label-1" - } - } - ] - }, - { - "targetId": "example-target-two", - "profiles": [] - } - - ] - } -} diff --git a/tpgtools/api/clouddeploy/samples/basic.target.json b/tpgtools/api/clouddeploy/samples/basic.target.json deleted file mode 100644 index d185d12184f6..000000000000 --- a/tpgtools/api/clouddeploy/samples/basic.target.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "basic description", - "annotations": { - "my_first_annotation": "example-annotation-1", - "my_second_annotation": "example-annotation-2" - }, - "labels": { - "my_first_label": "example-label-1", - "my_second_label": "example-label-2" - }, - "requireApproval": false, - "gke": { - "cluster": "projects/{{project}}/locations/{{region}}/clusters/example-cluster-name" - }, - "deployParameters": { - "deployParameterKey": "deployParameterValue" - } -} diff --git a/tpgtools/api/clouddeploy/samples/canary_delivery_pipeline.yaml b/tpgtools/api/clouddeploy/samples/canary_delivery_pipeline.yaml deleted file mode 100644 index a22f6479cb2b..000000000000 --- a/tpgtools/api/clouddeploy/samples/canary_delivery_pipeline.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: canary_delivery_pipeline -description: Creates a basic Cloud Deploy delivery pipeline -type: delivery_pipeline -versions: -- beta -resource: samples/basic.delivery_pipeline.json -updates: -- resource: samples/updatecanary.delivery_pipeline.json -variables: -- name: project - type: project -- name: region - type: region -- name: pipeline - type: resource_name - diff --git a/tpgtools/api/clouddeploy/samples/canary_service_networking_delivery_pipeline.yaml b/tpgtools/api/clouddeploy/samples/canary_service_networking_delivery_pipeline.yaml deleted file mode 100644 index 5ef393e50ac0..000000000000 --- a/tpgtools/api/clouddeploy/samples/canary_service_networking_delivery_pipeline.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: canary_service_networking_delivery_pipeline -description: Creates a basic Cloud Deploy delivery pipeline -type: delivery_pipeline -versions: -- beta -resource: samples/basic.delivery_pipeline.json -updates: -- resource: samples/updatecanaryservicenetworking.delivery_pipeline.json -variables: -- name: project - type: project -- name: region - type: region -- name: pipeline - type: resource_name - diff --git a/tpgtools/api/clouddeploy/samples/canaryrun_delivery_pipeline.yaml b/tpgtools/api/clouddeploy/samples/canaryrun_delivery_pipeline.yaml deleted file mode 100644 index 93be4f336d97..000000000000 --- a/tpgtools/api/clouddeploy/samples/canaryrun_delivery_pipeline.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: canaryrun_delivery_pipeline -description: Creates a basic Cloud Deploy delivery pipeline -type: delivery_pipeline -versions: -- beta -resource: samples/basic.delivery_pipeline.json -updates: -- resource: samples/updatecanaryrun.delivery_pipeline.json -variables: -- name: project - type: project -- name: region - type: region -- name: pipeline - type: resource_name - diff --git a/tpgtools/api/clouddeploy/samples/delivery_pipeline.yaml b/tpgtools/api/clouddeploy/samples/delivery_pipeline.yaml deleted file mode 100644 index fa1a3d57a377..000000000000 --- a/tpgtools/api/clouddeploy/samples/delivery_pipeline.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: delivery_pipeline -description: Creates a basic Cloud Deploy delivery pipeline -type: delivery_pipeline -versions: -- ga -resource: samples/basic.delivery_pipeline.json -updates: -- resource: samples/update.delivery_pipeline.json -variables: -- name: project - type: project -- name: region - type: region -- name: pipeline - type: resource_name - diff --git a/tpgtools/api/clouddeploy/samples/multi.target.json b/tpgtools/api/clouddeploy/samples/multi.target.json deleted file mode 100644 index 95f7994e76e5..000000000000 --- a/tpgtools/api/clouddeploy/samples/multi.target.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "multi-target description", - "annotations": { - "my_first_annotation": "example-annotation-1", - "my_second_annotation": "example-annotation-2" - }, - "labels": { - "my_first_label": "example-label-1", - "my_second_label": "example-label-2" - }, - "requireApproval": false, - "multiTarget": { - "targetIds": [ - "1", - "2" - ] - }, - "executionConfigs": [ - { - "usages": ["RENDER", "DEPLOY"], - "executionTimeout": "3600s" - } - ] -} diff --git a/tpgtools/api/clouddeploy/samples/multi_target.yaml b/tpgtools/api/clouddeploy/samples/multi_target.yaml deleted file mode 100644 index 081dfa084e2f..000000000000 --- a/tpgtools/api/clouddeploy/samples/multi_target.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2023 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: multi_target -description: tests creating and updating a multi-target -type: target -versions: -- beta -resource: samples/multi.target.json -updates: -- resource: samples/update_multi.target.json - dependencies: [] -variables: -- name: project - type: project -- name: region - type: region -- name: target - type: resource_name diff --git a/tpgtools/api/clouddeploy/samples/run.target.json b/tpgtools/api/clouddeploy/samples/run.target.json deleted file mode 100644 index e596925eab35..000000000000 --- a/tpgtools/api/clouddeploy/samples/run.target.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "basic description", - "annotations": { - "my_first_annotation": "example-annotation-1", - "my_second_annotation": "example-annotation-2" - }, - "labels": { - "my_first_label": "example-label-1", - "my_second_label": "example-label-2" - }, - "requireApproval": false, - "run": { - "location": "projects/{{project}}/locations/{{region}}" - }, - "executionConfigs": [ - { - "usages": ["RENDER", "DEPLOY"], - "executionTimeout": "3600s" - } - ] -} diff --git a/tpgtools/api/clouddeploy/samples/run_target.yaml b/tpgtools/api/clouddeploy/samples/run_target.yaml deleted file mode 100644 index d453bb5f559a..000000000000 --- a/tpgtools/api/clouddeploy/samples/run_target.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: run_target -description: tests creating and updating a cloud run target -type: target -versions: -- beta -resource: samples/run.target.json -updates: -- resource: samples/updaterun.target.json - dependencies: [] -variables: -- name: project - type: project -- name: region - type: region -- name: target - type: resource_name diff --git a/tpgtools/api/clouddeploy/samples/target.yaml b/tpgtools/api/clouddeploy/samples/target.yaml deleted file mode 100644 index cce9efb688e1..000000000000 --- a/tpgtools/api/clouddeploy/samples/target.yaml +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: target -description: Creates a basic Cloud Deploy target -type: target -versions: -- ga -resource: samples/basic.target.json -updates: -- resource: samples/update.target.json - dependencies: [] -- resource: samples/add_first_execution_config.target.json - dependencies: [] -- resource: samples/add_second_execution_config.target.json - dependencies: [] -- resource: samples/update_execution_env.target.json - dependencies: [] -variables: -- name: project - type: project -- name: region - type: region -- name: target - type: resource_name diff --git a/tpgtools/api/clouddeploy/samples/update.delivery_pipeline.json b/tpgtools/api/clouddeploy/samples/update.delivery_pipeline.json deleted file mode 100644 index f4bcf03b4b8b..000000000000 --- a/tpgtools/api/clouddeploy/samples/update.delivery_pipeline.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "{{pipeline}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "serialPipeline": { - "stages": [ - { - "targetId": "example-target-two", - "profiles": ["new-example-profile"] - }, - { - "targetId": "example-target-three", - "profiles": [ - "example-profile-four", - "example-profile-five" - ] - } - ] - }, - "suspended": true -} diff --git a/tpgtools/api/clouddeploy/samples/update.target.json b/tpgtools/api/clouddeploy/samples/update.target.json deleted file mode 100644 index d5ad05cba07d..000000000000 --- a/tpgtools/api/clouddeploy/samples/update.target.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "requireApproval": true, - "gke": { - "cluster": "projects/{{project}}/locations/{{region}}/clusters/different-example-cluster-name", - "internalIp": true - } -} diff --git a/tpgtools/api/clouddeploy/samples/update_execution_env.target.json b/tpgtools/api/clouddeploy/samples/update_execution_env.target.json deleted file mode 100644 index 1923e47c75a3..000000000000 --- a/tpgtools/api/clouddeploy/samples/update_execution_env.target.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "requireApproval": true, - "gke": { - "cluster": "projects/{{project}}/locations/{{region}}/clusters/different-example-cluster-name", - "internalIp": true, - "proxyUrl": "http://10.0.0.1" - }, - "executionConfigs": [ - { - "usages": [ - "RENDER" - ], - "serviceAccount": "other-owner@{{project}}.iam.gserviceaccount.com", - "artifactStorage": "gs://other-bucket/other-dir", - "verbose": true - }, - { - "usages": [ - "DEPLOY" - ], - "workerPool": "projects/{{project}}/locations/{{region}}/workerPools/my-deploy-pool", - "serviceAccount": "deploy-pool-owner@{{project}}.iam.gserviceaccount.com", - "artifactStorage": "gs://deploy-bucket/deploy-dir" - } - ] -} \ No newline at end of file diff --git a/tpgtools/api/clouddeploy/samples/update_multi.target.json b/tpgtools/api/clouddeploy/samples/update_multi.target.json deleted file mode 100644 index 201a0e86cb54..000000000000 --- a/tpgtools/api/clouddeploy/samples/update_multi.target.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated mutli-target description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "example-label-2", - "my_third_label": "example-label-3" - }, - "requireApproval": true, - "multiTarget": { - "targetIds": [ - "1", - "2", - "3" - ] - } -} diff --git a/tpgtools/api/clouddeploy/samples/updatecanary.delivery_pipeline.json b/tpgtools/api/clouddeploy/samples/updatecanary.delivery_pipeline.json deleted file mode 100644 index cdfb5862ff5c..000000000000 --- a/tpgtools/api/clouddeploy/samples/updatecanary.delivery_pipeline.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "name": "{{pipeline}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "serialPipeline": { - "stages": [ - { - "targetId": "example-target-two", - "profiles": ["new-example-profile"], - "strategy" : { - "canary" : { - "runtimeConfig" : { - "kubernetes" : { - "gatewayServiceMesh" : { - "httpRoute": "example-http-route", - "service": "example-service", - "deployment": "example-deployment", - "podSelectorLabel": "example.com/app-name" - } - } - }, - "customCanaryDeployment" : { - "phaseConfigs" : [ - { - "phaseId": "first", - "percentage": 50, - "verify": true - }, - { - "phaseId": "stable", - "percentage": 100, - "verify": false - } - ] - } - } - } - }, - { - "targetId": "example-target-three", - "strategy" : { - "canary" : { - "runtimeConfig" : { - "kubernetes" : { - "gatewayServiceMesh" : { - "httpRoute": "example-http-route", - "service": "example-service", - "deployment": "example-deployment", - "podSelectorLabel": "example.com/app-name", - "routeDestinations": { - "destinationIds": ["example-destination-id"], - "propagateService": true - } - } - } - }, - "canaryDeployment" : { - "percentages": [0, 5, 20], - "verify": true - } - } - }, - "profiles": [ - "example-profile-four", - "example-profile-five" - ] - } - ] - } - } \ No newline at end of file diff --git a/tpgtools/api/clouddeploy/samples/updatecanaryrun.delivery_pipeline.json b/tpgtools/api/clouddeploy/samples/updatecanaryrun.delivery_pipeline.json deleted file mode 100644 index ee85160ae911..000000000000 --- a/tpgtools/api/clouddeploy/samples/updatecanaryrun.delivery_pipeline.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "{{pipeline}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "serialPipeline": { - "stages": [ - { - "targetId": "example-target-two", - "profiles": ["new-example-profile"], - "strategy" : { - "canary" : { - "runtimeConfig" : { - "cloudRun" : { - "automaticTrafficControl": true - } - }, - "canaryDeployment" : { - "percentages" : [25], - "verify": true - } - } - } - } - ] - } - } \ No newline at end of file diff --git a/tpgtools/api/clouddeploy/samples/updatecanaryservicenetworking.delivery_pipeline.json b/tpgtools/api/clouddeploy/samples/updatecanaryservicenetworking.delivery_pipeline.json deleted file mode 100644 index 19311b6a7f2a..000000000000 --- a/tpgtools/api/clouddeploy/samples/updatecanaryservicenetworking.delivery_pipeline.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "{{pipeline}}", - "location": "{{region}}", - "project": "{{project}}", - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "serialPipeline": { - "stages": [ - { - "targetId": "example-target-two", - "profiles": [ - "new-example-profile" - ], - "strategy": { - "canary": { - "runtimeConfig": { - "kubernetes": { - "serviceNetworking": { - "service": "example-service", - "deployment": "example-deployment", - "podSelectorLabel": "example.com/app-name" - } - } - }, - "canaryDeployment": { - "percentages": [ - 25 - ], - "verify": true - } - } - } - } - ] - } -} \ No newline at end of file diff --git a/tpgtools/api/clouddeploy/samples/updaterun.target.json b/tpgtools/api/clouddeploy/samples/updaterun.target.json deleted file mode 100644 index 52f4fd163f48..000000000000 --- a/tpgtools/api/clouddeploy/samples/updaterun.target.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "{{target}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "basic description", - "annotations": { - "my_first_annotation": "example-annotation-1", - "my_second_annotation": "example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_first_label": "example-label-1", - "my_second_label": "example-label-2" - }, - "requireApproval": true, - "run": { - "location": "projects/{{project}}/locations/{{region}}" - } -} diff --git a/tpgtools/api/clouddeploy/samples/updateverify.delivery_pipeline.json b/tpgtools/api/clouddeploy/samples/updateverify.delivery_pipeline.json deleted file mode 100644 index 9ae717a54f44..000000000000 --- a/tpgtools/api/clouddeploy/samples/updateverify.delivery_pipeline.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "{{pipeline}}", - "location": "{{region}}", - "project": "{{project}}", - - "description": "updated description", - "annotations": { - "my_second_annotation": "updated-example-annotation-2", - "my_third_annotation": "example-annotation-3" - }, - "labels": { - "my_second_label": "updated-example-label-2", - "my_third_label": "example-label-3" - }, - "serialPipeline": { - "stages": [ - { - "targetId": "example-target-two", - "profiles": ["new-example-profile"], - "strategy" : { - "standard" : { - "verify": true - } - } - }, - { - "targetId": "example-target-three", - "profiles": [ - "example-profile-four", - "example-profile-five" - ] - } - ] - } -} diff --git a/tpgtools/api/clouddeploy/samples/verify_delivery_pipeline.yaml b/tpgtools/api/clouddeploy/samples/verify_delivery_pipeline.yaml deleted file mode 100644 index f095649846d5..000000000000 --- a/tpgtools/api/clouddeploy/samples/verify_delivery_pipeline.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: verify_delivery_pipeline -description: tests creating and updating a delivery pipeline with deployment verification - strategy -type: delivery_pipeline -versions: -- beta -resource: samples/basic.delivery_pipeline.json -updates: -- resource: samples/updateverify.delivery_pipeline.json - dependencies: [] -variables: -- name: project - type: project -- name: region - type: region -- name: pipeline - type: resource_name diff --git a/tpgtools/api/dataplex/samples/basic.lake.json b/tpgtools/api/dataplex/samples/basic.lake.json deleted file mode 100755 index 8c2c56b7b3e2..000000000000 --- a/tpgtools/api/dataplex/samples/basic.lake.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "{{lake}}", - "displayName": "Lake for DCL", - "location": "{{region}}", - "project": "{{project}}", - "labels": { - "my-lake": "exists" - }, - "description": "Lake for DCL" -} diff --git a/tpgtools/api/dataplex/samples/basic.zone.json b/tpgtools/api/dataplex/samples/basic.zone.json deleted file mode 100644 index e188b5058aaa..000000000000 --- a/tpgtools/api/dataplex/samples/basic.zone.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{zone}}", - "displayName": "Zone for DCL", - "location": "{{region}}", - "project": "{{project}}", - "lake": "{{ref:basic.lake.json:name}}", - "description": "Zone for DCL", - "type": "RAW", - "discoverySpec": { - "enabled": false - }, - "resourceSpec": { - "locationType": "MULTI_REGION" - } -} \ No newline at end of file diff --git a/tpgtools/api/dataplex/samples/basic_lake.yaml b/tpgtools/api/dataplex/samples/basic_lake.yaml deleted file mode 100755 index d2c53b43b00e..000000000000 --- a/tpgtools/api/dataplex/samples/basic_lake.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: basic_lake -description: A basic example of a dataplex lake -type: lake -versions: -- ga -- v1 -resource: samples/basic.lake.json -updates: -- resource: samples/update.lake.json - dependencies: [] -variables: -- name: lake - type: resource_name -- name: project - type: project -- name: region - type: region diff --git a/tpgtools/api/dataplex/samples/basic_zone.yaml b/tpgtools/api/dataplex/samples/basic_zone.yaml deleted file mode 100644 index 8762e45e77a0..000000000000 --- a/tpgtools/api/dataplex/samples/basic_zone.yaml +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: basic_zone -description: A basic example of a dataplex zone -type: zone -versions: -- ga -resource: samples/basic.zone.json -dependencies: -- samples/basic.lake.json -updates: -- resource: samples/update.zone.json - dependencies: - - samples/basic.lake.json -variables: -- name: lake - type: resource_name -- name: project - type: project -- name: region - type: region -- name: zone - type: resource_name diff --git a/tpgtools/api/dataplex/samples/update.lake.json b/tpgtools/api/dataplex/samples/update.lake.json deleted file mode 100755 index 1b2418256784..000000000000 --- a/tpgtools/api/dataplex/samples/update.lake.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "{{lake}}", - "displayName": "Lake for DCL", - "location": "{{region}}", - "project": "{{project}}", - "labels": { - "my-lake": "exists" - }, - "description": "Updated description for lake" -} diff --git a/tpgtools/api/dataplex/samples/update.zone.json b/tpgtools/api/dataplex/samples/update.zone.json deleted file mode 100644 index 6c350179cae8..000000000000 --- a/tpgtools/api/dataplex/samples/update.zone.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "{{zone}}", - "displayName": "Zone for DCL", - "location": "{{region}}", - "project": "{{project}}", - "lake": "{{ref:basic.lake.json:name}}", - "labels": { - "updated_label": "exists" - }, - "description": "Zone for DCL Updated", - "type": "RAW", - "discoverySpec": { - "enabled": false - }, - "resourceSpec": { - "locationType": "MULTI_REGION" - } -} diff --git a/tpgtools/api/firebaserules/samples/basic.ruleset.json b/tpgtools/api/firebaserules/samples/basic.ruleset.json deleted file mode 100644 index 3982d8fb052c..000000000000 --- a/tpgtools/api/firebaserules/samples/basic.ruleset.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "{{ruleset}}", - "project": "{{project}}", - "source": { - "files": [{ - "name": "firestore.rules", - "content": "service cloud.firestore {match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } }", - "fingerprint": "" - }], - "language": "" - }, - "metadata": { - "services": ["cloud.firestore"] - } -} \ No newline at end of file diff --git a/tpgtools/api/firebaserules/samples/basic_ruleset.yaml b/tpgtools/api/firebaserules/samples/basic_ruleset.yaml deleted file mode 100644 index 025f94adb3ab..000000000000 --- a/tpgtools/api/firebaserules/samples/basic_ruleset.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: basic_ruleset -description: Creates a basic Firestore ruleset -type: ruleset -versions: -- ga -resource: samples/basic.ruleset.json -variables: -- name: project - type: project -- name: ruleset - type: resource_name \ No newline at end of file diff --git a/tpgtools/api/firebaserules/samples/minimal.ruleset.json b/tpgtools/api/firebaserules/samples/minimal.ruleset.json deleted file mode 100644 index c54691dd8355..000000000000 --- a/tpgtools/api/firebaserules/samples/minimal.ruleset.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "{{ruleset}}", - "project": "{{project}}", - "source": { - "files": [{ - "name": "firestore.rules", - "content": "service cloud.firestore {match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } }" - }] - } - } - \ No newline at end of file diff --git a/tpgtools/api/firebaserules/samples/minimal_ruleset.yaml b/tpgtools/api/firebaserules/samples/minimal_ruleset.yaml deleted file mode 100644 index af968496d221..000000000000 --- a/tpgtools/api/firebaserules/samples/minimal_ruleset.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: minimal_ruleset -description: Creates a minimal Firestore ruleset -type: ruleset -versions: -- ga -resource: samples/minimal.ruleset.json -variables: -- name: project - type: project -- name: ruleset - type: resource_name \ No newline at end of file diff --git a/tpgtools/api/monitoring/samples/basic.cloudresourcemanager.project.json b/tpgtools/api/monitoring/samples/basic.cloudresourcemanager.project.json deleted file mode 100755 index ecb8396416a9..000000000000 --- a/tpgtools/api/monitoring/samples/basic.cloudresourcemanager.project.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "{{id}}", - "parent": "organizations/{{org_id}}" -} diff --git a/tpgtools/api/monitoring/samples/basic.monitored_project.json b/tpgtools/api/monitoring/samples/basic.monitored_project.json deleted file mode 100755 index 2ae0a9f4ea78..000000000000 --- a/tpgtools/api/monitoring/samples/basic.monitored_project.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "{{ref:basic.cloudresourcemanager.project.json:name}}", - "metricsScope": "{{project}}" -} diff --git a/tpgtools/api/monitoring/samples/basic_monitored_project.yaml b/tpgtools/api/monitoring/samples/basic_monitored_project.yaml deleted file mode 100755 index f5d65f8073ee..000000000000 --- a/tpgtools/api/monitoring/samples/basic_monitored_project.yaml +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -dependencies: -- samples/basic.cloudresourcemanager.project.json -description: A basic example of a monitoring monitored project -name: basic_monitored_project -resource: samples/basic.monitored_project.json -type: monitored_project -variables: -- name: id - type: resource_name - docs_value: my-monitored-project -- name: org_id - type: org_id -- name: project - type: project - docs_value: existing-metrics-scope-project -versions: -- beta -- ga - diff --git a/tpgtools/api/networkconnectivity/samples/basic.hub.json b/tpgtools/api/networkconnectivity/samples/basic.hub.json deleted file mode 100644 index 4e513a26d92c..000000000000 --- a/tpgtools/api/networkconnectivity/samples/basic.hub.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "{{hub}}", - "project": "{{project}}", - "labels": { - "label-one": "value-one" - }, - "description": "A sample hub" -} \ No newline at end of file diff --git a/tpgtools/api/networkconnectivity/samples/basic_hub.yaml b/tpgtools/api/networkconnectivity/samples/basic_hub.yaml deleted file mode 100644 index 88114cdc4753..000000000000 --- a/tpgtools/api/networkconnectivity/samples/basic_hub.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: basic_hub -description: A basic test of a networkconnectivity hub -type: hub -versions: -- ga -- beta -resource: samples/basic.hub.json -updates: -- resource: samples/update.hub.json - dependencies: [] -variables: -- name: hub - type: resource_name -- name: project - type: project \ No newline at end of file diff --git a/tpgtools/api/networkconnectivity/samples/update.hub.json b/tpgtools/api/networkconnectivity/samples/update.hub.json deleted file mode 100644 index d984f8351b6f..000000000000 --- a/tpgtools/api/networkconnectivity/samples/update.hub.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "{{hub}}", - "project": "{{project}}", - "labels": { - "label-two": "value-one" - }, - "description": "An updated sample hub" -} \ No newline at end of file diff --git a/tpgtools/api/osconfig/samples/fixed.os_policy_assignment.json b/tpgtools/api/osconfig/samples/fixed.os_policy_assignment.json deleted file mode 100755 index d4beb5178ed1..000000000000 --- a/tpgtools/api/osconfig/samples/fixed.os_policy_assignment.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "name": "{{assignment}}", - "project": "{{project}}", - "location": "{{zone}}", - "description": "A test os policy assignment", - "osPolicies": [ - { - "id": "policy", - "description": "A test os policy", - "mode": "VALIDATION", - "resourceGroups": [ - { - "inventoryFilters": [ - { - "osShortName": "centos", - "osVersion": "8.*" - } - ], - "resources": [ - { - "id": "apt", - "pkg": { - "desiredState": "INSTALLED", - "apt": { - "name": "bazel" - } - } - } - ] - } - ], - "allowNoResourceGroupMatch": false - } - ], - "instanceFilter": { - "all": false, - "inclusionLabels": [ - { - "labels": { - "label-one": "value-one" - } - } - ], - "exclusionLabels": [ - { - "labels": { - "label-two": "value-two" - } - } - ], - "inventories": [ - { - "osShortName": "centos", - "osVersion": "8.*" - } - ] - }, - "rollout": { - "disruptionBudget": { - "fixed": 1 - }, - "minWaitDuration": "3.5s" - } -} diff --git a/tpgtools/api/osconfig/samples/fixed_os_policy_assignment.yaml b/tpgtools/api/osconfig/samples/fixed_os_policy_assignment.yaml deleted file mode 100755 index 0565f7dd85e6..000000000000 --- a/tpgtools/api/osconfig/samples/fixed_os_policy_assignment.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: fixed_os_policy_assignment -description: An example of an osconfig os policy assignment with fixed rollout disruption - budget -type: os_policy_assignment -versions: -- ga -- beta -- alpha -resource: samples/fixed.os_policy_assignment.json -variables: -- name: assignment - type: resource_name -- name: project - type: project -- name: zone - type: zone diff --git a/tpgtools/api/privateca/samples/basic.certificate_template.json b/tpgtools/api/privateca/samples/basic.certificate_template.json deleted file mode 100755 index 1e06a1f5af75..000000000000 --- a/tpgtools/api/privateca/samples/basic.certificate_template.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "name": "{{template}}", - "project": "{{project}}", - "location": "{{region}}", - "maximumLifetime": "86400s", - "predefinedValues": { - "keyUsage": { - "baseKeyUsage": { - "digitalSignature": true, - "contentCommitment": true, - "keyEncipherment": true, - "dataEncipherment": true, - "keyAgreement": true, - "certSign": false, - "crlSign": false, - "encipherOnly": true, - "decipherOnly": true - }, - "extendedKeyUsage": { - "serverAuth": true, - "clientAuth": true, - "codeSigning": true, - "emailProtection": true, - "timeStamping": true, - "ocspSigning": true - }, - "unknownExtendedKeyUsages": [ - { - "objectIdPath": [1, 6] - } - ] - }, - "caOptions": { - "isCa": false, - "maxIssuerPathLength": 6 - }, - "policyIds": [ - { - "objectIdPath": [1, 6] - } - ], - "aiaOcspServers": [ - "string" - ], - "additionalExtensions": [ - { - "objectId": { - "objectIdPath": [1, 6] - }, - "critical": true, - "value": "c3RyaW5nCg==" - } - ] - }, - "identityConstraints": { - "celExpression": { - "title": "Sample expression", - "description": "Always true", - "expression": "true", - "location": "any.file.anywhere" - }, - "allowSubjectPassthrough": true, - "allowSubjectAltNamesPassthrough": true - }, - "passthroughExtensions": { - "knownExtensions": [ - "EXTENDED_KEY_USAGE" - ], - "additionalExtensions": [ - { - "objectIdPath": [1, 6] - } - ] - }, - "description": "An updated sample certificate template", - "labels": { - "label-two": "value-two" - } -} diff --git a/tpgtools/api/privateca/samples/basic_certificate_template.yaml b/tpgtools/api/privateca/samples/basic_certificate_template.yaml deleted file mode 100755 index e415a08b9789..000000000000 --- a/tpgtools/api/privateca/samples/basic_certificate_template.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: basic_certificate_template -description: An example of a basic privateca certificate template -type: certificate_template -versions: -- ga -- beta -resource: samples/basic.certificate_template.json -updates: -- resource: samples/update.certificate_template.json - dependencies: [] -variables: -- name: region - type: region -- name: template - type: resource_name -- name: project - type: project diff --git a/tpgtools/api/privateca/samples/update.certificate_template.json b/tpgtools/api/privateca/samples/update.certificate_template.json deleted file mode 100755 index 90b423f6d11a..000000000000 --- a/tpgtools/api/privateca/samples/update.certificate_template.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "name": "{{template}}", - "project": "{{project}}", - "location": "{{region}}", - "maximumLifetime": "172800s", - "predefinedValues": { - "keyUsage": { - "baseKeyUsage": { - "digitalSignature": false, - "contentCommitment": false, - "keyEncipherment": false, - "dataEncipherment": false, - "keyAgreement": false, - "certSign": true, - "crlSign": true, - "encipherOnly": false, - "decipherOnly": false - }, - "extendedKeyUsage": { - "serverAuth": false, - "clientAuth": false, - "codeSigning": false, - "emailProtection": false, - "timeStamping": false, - "ocspSigning": false - }, - "unknownExtendedKeyUsages": [ - { - "objectIdPath": [1, 7] - } - ] - }, - "caOptions": { - "isCa": true, - "maxIssuerPathLength": 7 - }, - "policyIds": [ - { - "objectIdPath": [1, 7] - } - ], - "aiaOcspServers": [ - "new-string" - ], - "additionalExtensions": [ - { - "objectId": { - "objectIdPath": [1, 7] - }, - "critical": false, - "value": "bmV3LXN0cmluZw==" - } - ] - }, - "identityConstraints": { - "celExpression": { - "title": "New sample expression", - "description": "Always false", - "expression": "false", - "location": "update.certificate_template.json" - }, - "allowSubjectPassthrough": false, - "allowSubjectAltNamesPassthrough": false - }, - "passthroughExtensions": { - "knownExtensions": [ - "BASE_KEY_USAGE" - ], - "additionalExtensions": [ - { - "objectIdPath": [1, 7] - } - ] - }, - "description": "A sample certificate template", - "labels": { - "label-one": "value-one" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/android.key.json b/tpgtools/api/recaptchaenterprise/samples/android.key.json deleted file mode 100755 index 4a1fdfe8dab6..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/android.key.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "displayName": "display-name-one", - "project": "{{project}}", - "androidSettings": { - "allowAllPackageNames": true, - "allowedPackageNames": [] - }, - "testingOptions": { - "testingScore": 0.8 - }, - "labels": { - "label-one": "value-one" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/android_key.yaml b/tpgtools/api/recaptchaenterprise/samples/android_key.yaml deleted file mode 100755 index 4248daf9c2ac..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/android_key.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: android_key -description: A basic test of recaptcha enterprise key that can be used by Android - apps -type: key -versions: -- ga -- beta -resource: samples/android.key.json -updates: -- resource: samples/update_android.key.json - dependencies: [] -variables: -- name: project - type: project diff --git a/tpgtools/api/recaptchaenterprise/samples/ios.key.json b/tpgtools/api/recaptchaenterprise/samples/ios.key.json deleted file mode 100755 index 3e9bc9d8dc94..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/ios.key.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "displayName": "display-name-one", - "project": "{{project}}", - "iosSettings": { - "allowAllBundleIds": true, - "allowedBundleIds": [] - }, - "testingOptions": { - "testingScore": 1 - }, - "labels": { - "label-one": "value-one" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/ios_key.yaml b/tpgtools/api/recaptchaenterprise/samples/ios_key.yaml deleted file mode 100755 index b0f8e8c2a5f6..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/ios_key.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: ios_key -description: A basic test of recaptcha enterprise key that can be used by iOS apps -type: key -versions: -- ga -- beta -resource: samples/ios.key.json -updates: -- resource: samples/update_ios.key.json - dependencies: [] -variables: -- name: project - type: project diff --git a/tpgtools/api/recaptchaenterprise/samples/minimal.key.json b/tpgtools/api/recaptchaenterprise/samples/minimal.key.json deleted file mode 100755 index 195b9c1af9c4..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/minimal.key.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "displayName": "display-name-one", - "project": "{{project}}", - "webSettings": { - "allowAllDomains": true, - "integrationType": "SCORE" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/update_android.key.json b/tpgtools/api/recaptchaenterprise/samples/update_android.key.json deleted file mode 100755 index 47765c20c5a3..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/update_android.key.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "{{ref:__state__:name}}", - "displayName": "display-name-two", - "project": "{{project}}", - "androidSettings": { - "allowAllPackageNames": false, - "allowedPackageNames": [ - "com.android.application" - ] - }, - "testingOptions": { - "testingScore": 0.8 - }, - "labels": { - "label-two": "value-two" - } - -} diff --git a/tpgtools/api/recaptchaenterprise/samples/update_ios.key.json b/tpgtools/api/recaptchaenterprise/samples/update_ios.key.json deleted file mode 100755 index 5fa3c1de1877..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/update_ios.key.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "{{ref:__state__:name}}", - "displayName": "display-name-two", - "project": "{{project}}", - "iosSettings": { - "allowAllBundleIds": false, - "allowedBundleIds": [ - "com.companyname.appname" - ] - }, - "testingOptions": { - "testingScore": 1 - }, - "labels": { - "label-two": "value-two" - } - -} diff --git a/tpgtools/api/recaptchaenterprise/samples/update_web.key.json b/tpgtools/api/recaptchaenterprise/samples/update_web.key.json deleted file mode 100755 index 4db482f63338..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/update_web.key.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "{{ref:__state__:name}}", - "displayName": "display-name-two", - "project": "{{project}}", - "webSettings": { - "allowAllDomains": false, - "allowedDomains": [ - "subdomain.example.com" - ], - "integrationType": "CHECKBOX", - "challengeSecurityPreference": "SECURITY" - }, - "testingOptions": { - "testingScore": 0.5, - "testingChallenge": "NOCAPTCHA" - }, - "labels": { - "label-two": "value-two" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/update_web_score.key.json b/tpgtools/api/recaptchaenterprise/samples/update_web_score.key.json deleted file mode 100755 index bec47a57d3e3..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/update_web_score.key.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "{{ref:__state__:name}}", - "displayName": "display-name-two", - "project": "{{project}}", - "webSettings": { - "allowAllDomains": false, - "allowedDomains": [ - "subdomain.example.com" - ], - "allowAmpTraffic": true, - "integrationType": "SCORE" - }, - "testingOptions": { - "testingScore": 0.5 - }, - "labels": { - "label-two": "value-two" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/waf.key.json b/tpgtools/api/recaptchaenterprise/samples/waf.key.json deleted file mode 100755 index 1e9f5c12750f..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/waf.key.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "displayName": "display-name-one", - "project": "{{project}}", - "webSettings": { - "allowAllDomains": true, - "allowedDomains": [], - "integrationType": "INVISIBLE", - "challengeSecurityPreference": "USABILITY" - }, - "wafSettings": { - "wafFeature": "CHALLENGE_PAGE", - "wafService": "CA" - }, - "testingOptions": { - "testingScore": 0.5, - "testingChallenge": "NOCAPTCHA" - }, - "labels": { - "label-one": "value-one" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/waf_key.yaml b/tpgtools/api/recaptchaenterprise/samples/waf_key.yaml deleted file mode 100755 index db726a20f886..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/waf_key.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2023 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: waf_key -description: A basic test of recaptcha enterprise key that includes WAF settings -type: key -versions: -- ga -resource: samples/waf.key.json -variables: -- name: project - type: project diff --git a/tpgtools/api/recaptchaenterprise/samples/web.key.json b/tpgtools/api/recaptchaenterprise/samples/web.key.json deleted file mode 100755 index e205f8475f25..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/web.key.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "displayName": "display-name-one", - "project": "{{project}}", - "webSettings": { - "allowAllDomains": true, - "allowedDomains": [], - "integrationType": "CHECKBOX", - "challengeSecurityPreference": "USABILITY" - }, - "testingOptions": { - "testingScore": 0.5, - "testingChallenge": "NOCAPTCHA" - }, - "labels": { - "label-one": "value-one" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/web_key.yaml b/tpgtools/api/recaptchaenterprise/samples/web_key.yaml deleted file mode 100755 index bf8c4c166984..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/web_key.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: web_key -description: A basic test of recaptcha enterprise key that can be used by websites -type: key -versions: -- ga -- beta -resource: samples/web.key.json -updates: -- resource: samples/update_web.key.json - dependencies: [] -variables: -- name: project - type: project diff --git a/tpgtools/api/recaptchaenterprise/samples/web_score.key.json b/tpgtools/api/recaptchaenterprise/samples/web_score.key.json deleted file mode 100755 index 0bf51e91db65..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/web_score.key.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "displayName": "display-name-one", - "project": "{{project}}", - "webSettings": { - "allowAllDomains": true, - "allowedDomains": [], - "allowAmpTraffic": false, - "integrationType": "SCORE" - }, - "testingOptions": { - "testingScore": 0.5 - }, - "labels": { - "label-one": "value-one" - } -} diff --git a/tpgtools/api/recaptchaenterprise/samples/web_score_key.yaml b/tpgtools/api/recaptchaenterprise/samples/web_score_key.yaml deleted file mode 100755 index 3c8b7b99d5b9..000000000000 --- a/tpgtools/api/recaptchaenterprise/samples/web_score_key.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: web_score_key -description: A basic test of recaptcha enterprise key with score integration type - that can be used by websites -type: key -versions: -- ga -- beta -resource: samples/web_score.key.json -updates: -- resource: samples/update_web_score.key.json - dependencies: [] -variables: -- name: project - type: project diff --git a/tpgtools/documentation.go b/tpgtools/documentation.go deleted file mode 100644 index 07bd6092adc7..000000000000 --- a/tpgtools/documentation.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "bytes" - "fmt" - "io/ioutil" - "path" - "path/filepath" - "sort" - "text/template" - - "github.com/golang/glog" -) - -// Merges beta and GA resources for doc generation for a particular resource. -func mergeResource(res *Resource, resources map[Version][]*Resource, version *Version) *Resource { - resourceAcrossVersions := make(map[Version]*Resource) - for v, resList := range resources { - for _, r := range resList { - // Name is not unique, TerraformName must be - if r.TerraformName() == res.TerraformName() { - resourceAcrossVersions[v] = r - } - } - } - ga, gaExists := resourceAcrossVersions[GA_VERSION] - beta, betaExists := resourceAcrossVersions[BETA_VERSION] - alpha, alphaExists := resourceAcrossVersions[ALPHA_VERSION] - if alphaExists { - return alpha - } - if gaExists { - if betaExists { - return mergeResources(ga, beta) - } - return ga - } - beta.Description = fmt.Sprintf("Beta only: %s", beta.Description) - return beta -} - -func mergeResources(ga, beta *Resource) *Resource { - beta.Properties = mergeProperties(ga.Properties, beta.Properties) - - return beta -} - -// Marks any sub properties as beta only -func mergeProperties(ga, beta []Property) []Property { - gaProps := make(map[string]Property) - for _, p := range ga { - gaProps[p.title] = p - } - betaProps := make(map[string]Property) - for _, p := range beta { - betaProps[p.title] = p - } - inOrder := make([]string, 0) - for k := range betaProps { - inOrder = append(inOrder, k) - } - sort.Strings(inOrder) - modifiedProps := make([]Property, 0) - for _, name := range inOrder { - v := betaProps[name] - if gaProp, ok := gaProps[name]; !ok { - v.Description = fmt.Sprintf("(Beta only) %s", v.Description) - } else if len(v.Properties) != 0 { - // Look for sub-properties that might be beta only. - // If the top-level property is beta only, sub-properties don't need to be marked - v.Properties = mergeProperties(gaProp.Properties, v.Properties) - } - modifiedProps = append(modifiedProps, v) - } - - return modifiedProps -} - -func generateResourceWebsiteFile(res *Resource, resources map[Version][]*Resource, version *Version) { - res = mergeResource(res, resources, version) - - if len(res.DocSamples()) <= 0 { - fmt.Printf(" %-40s no samples, skipping doc generation\n", res.TerraformName()) - return - } - - // Generate resource website file - tmplInput := ResourceInput{ - Resource: *res, - } - - tmpl, err := template.New("resource.html.markdown.tmpl").Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, "resource.html.markdown.tmpl"), - ) - if err != nil { - glog.Exit(err) - } - - contents := bytes.Buffer{} - if err = tmpl.ExecuteTemplate(&contents, "resource.html.markdown.tmpl", tmplInput); err != nil { - glog.Exit(err) - } - - source := contents.Bytes() - - if oPath == nil || *oPath == "" { - fmt.Printf("%v\n", string(source)) - } else { - outname := fmt.Sprintf("%s_%s.html.markdown", res.ProductName(), res.Name()) - err := ioutil.WriteFile(path.Join(*oPath, "website/docs/r", outname), source, 0644) - if err != nil { - glog.Exit(err) - } - } -} diff --git a/tpgtools/file_utils.go b/tpgtools/file_utils.go deleted file mode 100644 index 0ddb2687b76e..000000000000 --- a/tpgtools/file_utils.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "io/ioutil" - "os" - - "gopkg.in/yaml.v2" -) - -func mergeYaml(fileA, fileB string) ([]byte, error) { - var objA map[string]interface{} - bs, err := ioutil.ReadFile(fileA) - if err != nil { - return nil, err - } - if err := yaml.Unmarshal(bs, &objA); err != nil { - return nil, err - } - - var objB map[string]interface{} - bs, err = ioutil.ReadFile(fileB) - if err != nil { - return nil, err - } - if err := yaml.Unmarshal(bs, &objB); err != nil { - return nil, err - } - - for k, v := range objB { - objA[k] = v - } - - out, err := yaml.Marshal(objA) - if err != nil { - return nil, err - } - return out, nil -} - -func pathExists(filePath string) bool { - if _, err := os.Stat(filePath); os.IsNotExist(err) { - return false - } - return true -} diff --git a/tpgtools/go.mod b/tpgtools/go.mod deleted file mode 100644 index a6f92d6a4b67..000000000000 --- a/tpgtools/go.mod +++ /dev/null @@ -1,39 +0,0 @@ -module github.com/GoogleCloudPlatform/magic-modules/tpgtools - -go 1.26 - -require ( - bitbucket.org/creachadair/stringset v0.0.11 - github.com/GoogleCloudPlatform/declarative-resource-client-library v1.84.0 - github.com/golang/glog v1.1.2 - github.com/hashicorp/hcl v1.0.0 - github.com/kylelemons/godebug v1.1.0 - github.com/nasa9084/go-openapi v0.0.0-20210722142352-4a81d737faf6 - gopkg.in/yaml.v2 v2.4.0 -) - -require ( - cloud.google.com/go/compute v1.23.0 // indirect - cloud.google.com/go/compute/metadata v0.2.3 // indirect - github.com/cenkalti/backoff v2.2.1+incompatible // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/go-cmp v0.5.9 // indirect - github.com/google/go-cpy v0.0.0-20211218193943-a9c933c06932 // indirect - github.com/google/s2a-go v0.1.7 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.2.5 // indirect - github.com/kr/text v0.2.0 // indirect - github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect - go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.13.0 // indirect - golang.org/x/net v0.15.0 // indirect - golang.org/x/oauth2 v0.12.0 // indirect - golang.org/x/sys v0.12.0 // indirect - golang.org/x/text v0.13.0 // indirect - google.golang.org/api v0.138.0 // indirect - google.golang.org/appengine v1.6.8 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect - google.golang.org/grpc v1.57.0 // indirect - google.golang.org/protobuf v1.31.0 // indirect - gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect -) diff --git a/tpgtools/go.sum b/tpgtools/go.sum deleted file mode 100644 index f97291e20d91..000000000000 --- a/tpgtools/go.sum +++ /dev/null @@ -1,178 +0,0 @@ -bitbucket.org/creachadair/stringset v0.0.11 h1:6Sv4CCv14Wm+OipW4f3tWOb0SQVpBDLW0knnJqUnmZ8= -bitbucket.org/creachadair/stringset v0.0.11/go.mod h1:wh0BHewFe+j0HrzWz7KcGbSNpFzWwnpmgPRlB57U5jU= -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go/compute v1.23.0 h1:tP41Zoavr8ptEqaW6j+LQOnyBBhO7OkOMAGrgLopTwY= -cloud.google.com/go/compute v1.23.0/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= -cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= -cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/GoogleCloudPlatform/declarative-resource-client-library v1.84.0 h1:OMv1P/bdgFwfKBczyo/MqdWU7wwehcaPKAgx23S6oM8= -github.com/GoogleCloudPlatform/declarative-resource-client-library v1.84.0/go.mod h1:/2OJTqC+kGnid2P2oeily9jQJ/TnHpiu2We2Igy9+rc= -github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= -github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.1.2 h1:DVjP2PbBOzHyzA+dn3WhHIq4NdVu3Q+pvivFICf/7fo= -github.com/golang/glog v1.1.2/go.mod h1:zR+okUeTbrL6EL3xHUDxZuEtGv04p5shwip1+mL/rLQ= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cpy v0.0.0-20211218193943-a9c933c06932 h1:5/4TSDzpDnHQ8rKEEQBjRlYx77mHOvXu08oGchxej7o= -github.com/google/go-cpy v0.0.0-20211218193943-a9c933c06932/go.mod h1:cC6EdPbj/17GFCPDK39NRarlMI+kt+O60S12cNB5J9Y= -github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= -github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvkiqTYKBCKLNmlge2eVjoZfySzM= -github.com/googleapis/enterprise-certificate-proxy v0.2.5/go.mod h1:RxW0N9901Cko1VOCW3SXCpWP+mlIEkk2tP7jnHy9a3w= -github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/nasa9084/go-openapi v0.0.0-20210722142352-4a81d737faf6 h1:EgeFHuf1nYbw8nN/04bzCHjUL+ZGOMi+b5DXH+TVNJE= -github.com/nasa9084/go-openapi v0.0.0-20210722142352-4a81d737faf6/go.mod h1:oY7A58oP7/O7+8Ob5s6uGrdVlLQj/BGgUUIsj6IMrQw= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= -go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8= -golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.12.0 h1:smVPGxink+n1ZI5pkQa8y6fZT0RW0MgCO5bFpepy4B4= -golang.org/x/oauth2 v0.12.0/go.mod h1:A74bZ3aGXgCY0qaIC9Ahg6Lglin4AMAco8cIv9baba4= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.138.0 h1:K/tVp05MxNVbHShRw9m7e9VJGdagNeTdMzqPH7AUqr0= -google.golang.org/api v0.138.0/go.mod h1:4xyob8CxC+0GChNBvEUAk8VBKNvYOTWM9T3v3UfRxuY= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= -google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d h1:uvYuEyMHKNt+lT4K3bN6fGswmK8qSvcreM3BwjDh+y4= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d/go.mod h1:+Bk1OCOj40wS2hwAMA+aCW9ypzm63QTBBHp6lQ3p+9M= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.57.0 h1:kfzNeI/klCGD2YPMUlaGNT3pxvYfga7smW3Vth8Zsiw= -google.golang.org/grpc v1.57.0/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/tpgtools/id.go b/tpgtools/id.go deleted file mode 100644 index 0530368f69dc..000000000000 --- a/tpgtools/id.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "fmt" - "regexp" - "sort" - "strings" - - "bitbucket.org/creachadair/stringset" - "github.com/nasa9084/go-openapi" -) - -const PatternPart = "{{(\\w+)}}" - -func idParts(id string) (parts []string) { - r := regexp.MustCompile(PatternPart) - - // returns [["{{field}}", "field"] ...] - idTmplAndParts := r.FindAllStringSubmatch(id, -1) - for _, v := range idTmplAndParts { - parts = append(parts, v[1]) - } - - return parts -} - -// PatternToRegex formats a pattern string into a Python-compatible regex. -func PatternToRegex(s string, allowForwardSlash bool) string { - re := regexp.MustCompile(PatternPart) - if allowForwardSlash { - return re.ReplaceAllString(s, "(?P<$1>.+)") - } - return re.ReplaceAllString(s, "(?P<$1>[^/]+)") -} - -// Finds the correct resource id based on the schema and any overrides. Returns whether a custom ID override was used. -func findResourceID(schema *openapi.Schema, overrides Overrides, location string) (string, bool, error) { - id, ok := schema.Extension["x-dcl-id"].(string) - if !ok { - return "", false, fmt.Errorf("Malformed or missing x-dcl-id: %v", schema.Extension["x-dcl-id"]) - } - - // Resource Override: Custom ID - cid := CustomIDDetails{} - cidOk, err := overrides.ResourceOverrideWithDetails(CustomID, &cid, location) - if err != nil { - return "", false, fmt.Errorf("failed to decode custom id details: %v", err) - } - - if cidOk { - id = cid.ID - } - - for _, override := range overrides { - if override.Type == CustomName { - if strings.Contains(id, fmt.Sprintf("{{%s}}", *override.Field)) { - id = strings.Replace(id, fmt.Sprintf("{{%s}}", *override.Field), fmt.Sprintf("{{%s}}", override.Details.(map[interface{}]interface{})["name"].(string)), 1) - } - } - } - return id, cidOk, nil -} - -// Finds all import formats for a given id. This can include short forms and -// partial forms with inferred project/region/etc -func defaultImportFormats(id string, onlyLongFormFormat bool) (formats []string) { - if onlyLongFormFormat { - return []string{id} - } - uniqueFormats := stringset.New() - - uniqueFormats.Add(id) - - parts := idParts(id) - for i, v := range parts { - parts[i] = fmt.Sprintf("{{%s}}", v) - } - - // short form "{{project}}/{{region}}/{{name}}" - uniqueFormats[strings.Join(parts, "/")] = struct{}{} - - // short form sans project - var locationalParts []string - for _, v := range parts { - if v != "{{project}}" { - locationalParts = append(locationalParts, v) - } - } - if len(locationalParts) != 0 { - uniqueFormats.Add(strings.Join(locationalParts, "/")) - } - - // short form sans project, region, zone - var resourceParts []string - for _, v := range locationalParts { - if v != "{{zone}}" && v != "{{region}}" { - resourceParts = append(resourceParts, v) - } - } - if len(resourceParts) != 0 { - uniqueFormats.Add(strings.Join(resourceParts, "/")) - } - - for _, f := range uniqueFormats.Elements() { - formats = append(formats, f) - } - - // formats must be ordered most to least specific - sort.SliceStable(formats, formatComparator(formats)) - return formats -} - -func shouldAllowForwardSlashInFormat(id string, props []Property) bool { - parts := idParts(id) - for _, v := range parts { - for _, prop := range props { - propSnakeCaseName := jsonToSnakeCase(prop.PackageName).snakecase() - if v == propSnakeCaseName && prop.forwardSlashAllowed { - return true - } - } - } - return false -} diff --git a/tpgtools/ignored_handwritten/access_context_manager_utils.go b/tpgtools/ignored_handwritten/access_context_manager_utils.go deleted file mode 100644 index 1b776c227c1b..000000000000 --- a/tpgtools/ignored_handwritten/access_context_manager_utils.go +++ /dev/null @@ -1,41 +0,0 @@ -package google - -import ( - "fmt" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func servicePerimeterImport(d *schema.ResourceData, config *transport_tpg.Config) error { - // current import_formats can't import fields with forward slashes in their value - if err := tpgresource.ParseImportId([]string{"(?P.+)"}, d, config); err != nil { - return err - } - stringParts := strings.Split(d.Get("name").(string), "/") - if len(stringParts) < 2 { - return fmt.Errorf("Error parsing parent name. Should be in form accessPolicies/{{policy_id}}/servicePerimeters/{{short_name}}") - } - if err := d.Set("parent", fmt.Sprintf("%s/%s", stringParts[0], stringParts[1])); err != nil { - return fmt.Errorf("Error setting parent, %s", err) - } - return nil -} - -func accessLevelImport(d *schema.ResourceData, config *transport_tpg.Config) error { - // current import_formats can't import fields with forward slashes in their value - if err := tpgresource.ParseImportId([]string{"(?P.+)"}, d, config); err != nil { - return err - } - stringParts := strings.Split(d.Get("name").(string), "/") - if len(stringParts) < 2 { - return fmt.Errorf("Error parsing parent name. Should be in form accessPolicies/{{policy_id}}/accessLevels/{{short_name}}") - } - if err := d.Set("parent", fmt.Sprintf("%s/%s", stringParts[0], stringParts[1])); err != nil { - return fmt.Errorf("Error setting parent, %s", err) - } - return nil -} diff --git a/tpgtools/ignored_handwritten/common_custom_diff.go b/tpgtools/ignored_handwritten/common_custom_diff.go deleted file mode 100644 index 2ef403d0887e..000000000000 --- a/tpgtools/ignored_handwritten/common_custom_diff.go +++ /dev/null @@ -1,70 +0,0 @@ -package google - -import ( - "fmt" - "net" - - "github.com/apparentlymart/go-cidr/cidr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func IsShrinkageIpCidr(old, new, _ interface{}) bool { - _, oldCidr, oldErr := net.ParseCIDR(old.(string)) - _, newCidr, newErr := net.ParseCIDR(new.(string)) - - if oldErr != nil || newErr != nil { - // This should never happen. The ValidateFunc on the field ensures it. - return false - } - - oldStart, oldEnd := cidr.AddressRange(oldCidr) - - if newCidr.Contains(oldStart) && newCidr.Contains(oldEnd) { - // This is a CIDR range expansion, no need to ForceNew, we have an update method for it. - return false - } - - return true -} - -func resourceComputeSubnetworkSecondaryIpRangeSetStyleDiff(diff *schema.ResourceDiff, meta interface{}) error { - keys := diff.GetChangedKeysPrefix("secondary_ip_range") - if len(keys) == 0 { - return nil - } - oldCount, newCount := diff.GetChange("secondary_ip_range.#") - var count int - // There could be duplicates - worth continuing even if the counts are unequal. - if oldCount.(int) < newCount.(int) { - count = newCount.(int) - } else { - count = oldCount.(int) - } - - if count < 1 { - return nil - } - old := make([]interface{}, 0, count) - new := make([]interface{}, 0, count) - for i := 0; i < count; i++ { - o, n := diff.GetChange(fmt.Sprintf("secondary_ip_range.%d", i)) - - if o != nil { - old = append(old, o) - } - if n != nil { - new = append(new, n) - } - } - - oldSet := schema.NewSet(schema.HashResource(ResourceComputeSubnetwork().Schema["secondary_ip_range"].Elem.(*schema.Resource)), old) - newSet := schema.NewSet(schema.HashResource(ResourceComputeSubnetwork().Schema["secondary_ip_range"].Elem.(*schema.Resource)), new) - - if oldSet.Equal(newSet) { - if err := diff.Clear("secondary_ip_range"); err != nil { - return err - } - } - - return nil -} diff --git a/tpgtools/ignored_handwritten/common_custom_directive.go b/tpgtools/ignored_handwritten/common_custom_directive.go deleted file mode 100644 index 68826e0d6c74..000000000000 --- a/tpgtools/ignored_handwritten/common_custom_directive.go +++ /dev/null @@ -1,17 +0,0 @@ -package google - -import ( - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - dns "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/dns" -) - -func rrefCreateDirective(recordSet *dns.ResourceRecordSet) []dcl.ApplyOption { - if recordSet.DnsType != nil && *recordSet.DnsType == "NS" { - // NS type records may exist by default. In this case, we want to acquire - // and modify existing records - return []dcl.ApplyOption{ - dcl.WithLifecycleParam(dcl.BlockDestruction), - } - } - return CreateDirective -} diff --git a/tpgtools/ignored_handwritten/common_diff_suppress.go b/tpgtools/ignored_handwritten/common_diff_suppress.go deleted file mode 100644 index 0c4af16934ee..000000000000 --- a/tpgtools/ignored_handwritten/common_diff_suppress.go +++ /dev/null @@ -1,69 +0,0 @@ -// Contains common diff suppress functions. - -package google - -import ( - "net" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func EmptyOrDefaultStringSuppress(defaultVal string) schema.SchemaDiffSuppressFunc { - return func(k, old, new string, d *schema.ResourceData) bool { - return (old == "" && new == defaultVal) || (new == "" && old == defaultVal) - } -} - -func CaseDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { - return strings.ToUpper(old) == strings.ToUpper(new) -} - -func TimestampDiffSuppress(format string) schema.SchemaDiffSuppressFunc { - return func(_, old, new string, _ *schema.ResourceData) bool { - oldT, err := time.Parse(format, old) - if err != nil { - return false - } - - newT, err := time.Parse(format, new) - if err != nil { - return false - } - - return oldT == newT - } -} - -func comparePubsubSubscriptionExpirationPolicy(_, old, new string, _ *schema.ResourceData) bool { - trimmedNew := strings.TrimLeft(new, "0") - trimmedOld := strings.TrimLeft(old, "0") - if strings.Contains(trimmedNew, ".") { - trimmedNew = strings.TrimRight(strings.TrimSuffix(trimmedNew, "s"), "0") + "s" - } - if strings.Contains(trimmedOld, ".") { - trimmedOld = strings.TrimRight(strings.TrimSuffix(trimmedOld, "s"), "0") + "s" - } - return trimmedNew == trimmedOld -} - -func rrefDiffSuppressfunc(k, old, new string, d *schema.ResourceData) bool { - if d.Get("type") == "AAAA" { - return ipv6AddressDiffSuppress(k, old, new, d) - } - return false -} - -// This is separate from rrefDiffSuppressfunc for unit testing -func ipv6AddressDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { - oldIp := net.ParseIP(old) - newIp := net.ParseIP(new) - - return oldIp.Equal(newIp) -} - -// This is separate from CaseDiffSuppress as it strips quotation marks -func dnsRecordSetRrefsDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { - return strings.ToLower(strings.Trim(old, `"`)) == strings.ToLower(strings.Trim(new, `"`)) -} diff --git a/tpgtools/ignored_handwritten/common_set_hash.go b/tpgtools/ignored_handwritten/common_set_hash.go deleted file mode 100644 index 2b140fc14b0b..000000000000 --- a/tpgtools/ignored_handwritten/common_set_hash.go +++ /dev/null @@ -1,59 +0,0 @@ -package google - -import ( - "bytes" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" -) - -func resourceComputeFirewallRuleHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(m["protocol"].(string)))) - - // We need to make sure to sort the strings below so that we always - // generate the same hash code no matter what is in the set. - if v, ok := m["ports"]; ok && v != nil { - s := convertStringArr(v.([]interface{})) - sort.Strings(s) - - for _, v := range s { - buf.WriteString(fmt.Sprintf("%s-", v)) - } - } - - return hashcode(buf.String()) -} -func resourceDNSManagedZoneNetworkHash(v interface{}) int { - if v == nil { - return 0 - } - raw := v.(map[string]interface{}) - if url, ok := raw["network_url"]; ok { - return selfLinkNameHash(url) - } - var buf bytes.Buffer - schema.SerializeResourceForHash(&buf, raw, DnsManagedZonePrivateVisibilityConfigNetworksSchema()) - return hashcode(buf.String()) -} - -func resourceSourceRepoRepositoryPubSubConfigsHash(v interface{}) int { - if v == nil { - return 0 - } - - var buf bytes.Buffer - m := v.(map[string]interface{}) - - buf.WriteString(fmt.Sprintf("%s-", tpgresource.GetResourceNameFromSelfLink(m["topic"].(string)))) - buf.WriteString(fmt.Sprintf("%s-", m["message_format"].(string))) - if v, ok := m["service_account_email"]; ok { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - - return hashcode(buf.String()) -} diff --git a/tpgtools/ignored_handwritten/common_skip_delete.go b/tpgtools/ignored_handwritten/common_skip_delete.go deleted file mode 100644 index 535a31624de2..000000000000 --- a/tpgtools/ignored_handwritten/common_skip_delete.go +++ /dev/null @@ -1,34 +0,0 @@ -package google - -import ( - "context" - "log" - - dns "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/dns" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -// Skip delete for DNS record set if the record is for the primary NS record -func rrefSkipDelete(c *transport_tpg.Config, recordSet *dns.ResourceRecordSet) (bool, error) { - if *recordSet.DnsType != "NS" { - // Only skip for NS records in some circumstances - return false, nil - } - - mz := &dns.ManagedZone{ - Name: recordSet.ManagedZone, - Project: recordSet.Project, - } - - res, err := c.clientDnsDCL.GetManagedZone(context.Background(), mz) - if err != nil { - return false, err - } - - // Subdomains can be deleted, so check if this is one - if *res.DnsName == *recordSet.DnsName { - log.Println("[DEBUG] NS records can't be deleted due to API restrictions, so they're being left in place. See https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/dns_record_set for more information.") - return true, nil - } - return false, nil -} diff --git a/tpgtools/ignored_handwritten/compute_utils.go b/tpgtools/ignored_handwritten/compute_utils.go deleted file mode 100644 index 1c6e8d7b6a83..000000000000 --- a/tpgtools/ignored_handwritten/compute_utils.go +++ /dev/null @@ -1,52 +0,0 @@ -package google - -import ( - "context" - "fmt" - "log" - "strings" - - compute "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func deleteComputeNetworkDefaultRoutes(d *schema.ResourceData, config *transport_tpg.Config, res *compute.Network) error { - if d.Get("delete_default_routes_on_create").(bool) { - url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/global/networks") - networkLink := fmt.Sprintf("%s/%s", url, d.Get("name").(string)) - filter := fmt.Sprintf("(network=\"%s\") AND (destRange=\"0.0.0.0/0\")", networkLink) - log.Printf("[DEBUG] Getting routes for network %q with filter '%q'", d.Get("name").(string), filter) - routes, err := config.clientComputeDCL.ListRoute(context.Background(), *res.Project) - if err != nil { - return fmt.Errorf("Error listing routes in proj: %s", err) - } - log.Printf("[DEBUG] Found %d routes rules in %q network", len(routes.Items), d.Get("name").(string)) - for _, route := range routes.Items { - if *route.Network == networkLink && *route.DestRange == "0.0.0.0/0" { - err := config.clientComputeDCL.DeleteRoute(context.Background(), route) - if err != nil { - return fmt.Errorf("Error deleting route: %s", err) - } - } - } - } - - return nil -} - -func getVpnTunnelLink(config *transport_tpg.Config, project string, region string, tunnel string) (string, error) { - if !strings.Contains(tunnel, "/") { - // Tunnel value provided is just the name, lookup the tunnel SelfLink - tunnelData, err := config.clientCompute.VpnTunnels.Get( - project, region, tunnel).Do() - if err != nil { - return "", fmt.Errorf("Error reading tunnel: %s", err) - } - tunnel = tunnelData.SelfLink - } - - return tunnel, nil - -} diff --git a/tpgtools/ignored_handwritten/custom_import.go b/tpgtools/ignored_handwritten/custom_import.go deleted file mode 100644 index b50236160e00..000000000000 --- a/tpgtools/ignored_handwritten/custom_import.go +++ /dev/null @@ -1,45 +0,0 @@ -package google - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func sourceRepoImport(d *schema.ResourceData, config *transport_tpg.Config) error { - if err := tpgresource.ParseImportId([]string{ - "^projects/(?P[^/]+)/repos/(?P.+)$", - "^(?P.+)$", - }, d, config); err != nil { - return err - } - - // Replace import id for the resource id - id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/repos/{{name}}") - if err != nil { - return fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - return nil -} - -func runtimeconfigVariableImport(d *schema.ResourceData, config *transport_tpg.Config) error { - if err := tpgresource.ParseImportId([]string{ - "^projects/(?P[^/]+)/configs/(?P[^/]+)/variables/(?P.+)$", - "^(?P[^/]+)/(?P.+)$", - }, d, config); err != nil { - return err - } - - // Replace import id for the resource id - id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/configs/{{parent}}/variables/{{name}}") - if err != nil { - return fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - return nil -} diff --git a/tpgtools/ignored_handwritten/disk_utils.go b/tpgtools/ignored_handwritten/disk_utils.go deleted file mode 100644 index aa6b29971e09..000000000000 --- a/tpgtools/ignored_handwritten/disk_utils.go +++ /dev/null @@ -1,309 +0,0 @@ -package google - -import ( - "fmt" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - tpgcompute "github.com/hashicorp/terraform-provider-google/google/services/compute" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -// Is the new disk size smaller than the old one? -func isDiskShrinkage(old, new, _ interface{}) bool { - // It's okay to remove size entirely. - if old == nil || new == nil { - return false - } - return new.(int) < old.(int) -} - -// We cannot suppress the diff for the case when family name is not part of the image name since we can't -// make a network call in a DiffSuppressFunc. -func DiskImageDiffSuppress(_, old, new string, _ *schema.ResourceData) bool { - // Understand that this function solves a messy problem ("how do we tell if the diff between two images - // is 'ForceNew-worthy', without making a network call?") in the best way we can: through a series of special - // cases and regexes. If you find yourself here because you are trying to add a new special case, - // you are probably looking for the diskImageFamilyEquals function and its subfunctions. - // In order to keep this maintainable, we need to ensure that the positive and negative examples - // in resource_compute_disk_test.go are as complete as possible. - - // 'old' is read from the API. - // It always has the format 'https://www.googleapis.com/compute/v1/projects/(%s)/global/images/(%s)' - matches := resolveImageLink.FindStringSubmatch(old) - if matches == nil { - // Image read from the API doesn't have the expected format. In practice, it should never happen - return false - } - oldProject := matches[1] - oldName := matches[2] - - // Partial or full self link family - if resolveImageProjectFamily.MatchString(new) { - // Value matches pattern "projects/{project}/global/images/family/{family-name}$" - matches := resolveImageProjectFamily.FindStringSubmatch(new) - newProject := matches[1] - newFamilyName := matches[2] - - return diskImageProjectNameEquals(oldProject, newProject) && diskImageFamilyEquals(oldName, newFamilyName) - } - - // Partial or full self link image - if resolveImageProjectImage.MatchString(new) { - // Value matches pattern "projects/{project}/global/images/{image-name}$" - matches := resolveImageProjectImage.FindStringSubmatch(new) - newProject := matches[1] - newImageName := matches[2] - - return diskImageProjectNameEquals(oldProject, newProject) && diskImageEquals(oldName, newImageName) - } - - // Partial link without project family - if resolveImageGlobalFamily.MatchString(new) { - // Value is "global/images/family/{family-name}" - matches := resolveImageGlobalFamily.FindStringSubmatch(new) - familyName := matches[1] - - return diskImageFamilyEquals(oldName, familyName) - } - - // Partial link without project image - if resolveImageGlobalImage.MatchString(new) { - // Value is "global/images/{image-name}" - matches := resolveImageGlobalImage.FindStringSubmatch(new) - imageName := matches[1] - - return diskImageEquals(oldName, imageName) - } - - // Family shorthand - if resolveImageFamilyFamily.MatchString(new) { - // Value is "family/{family-name}" - matches := resolveImageFamilyFamily.FindStringSubmatch(new) - familyName := matches[1] - - return diskImageFamilyEquals(oldName, familyName) - } - - // Shorthand for image or family - if resolveImageProjectImageShorthand.MatchString(new) { - // Value is "{project}/{image-name}" or "{project}/{family-name}" - matches := resolveImageProjectImageShorthand.FindStringSubmatch(new) - newProject := matches[1] - newName := matches[2] - - return diskImageProjectNameEquals(oldProject, newProject) && - (diskImageEquals(oldName, newName) || diskImageFamilyEquals(oldName, newName)) - } - - // Image or family only - if diskImageEquals(oldName, new) || diskImageFamilyEquals(oldName, new) { - // Value is "{image-name}" or "{family-name}" - return true - } - - return false -} - -func diskImageProjectNameEquals(project1, project2 string) bool { - // Convert short project name to full name - // For instance, centos => centos-cloud - fullProjectName, ok := tpgcompute.ImageMap[project2] - if ok { - project2 = fullProjectName - } - - return project1 == project2 -} - -func diskImageEquals(oldImageName, newImageName string) bool { - return oldImageName == newImageName -} - -func diskImageFamilyEquals(imageName, familyName string) bool { - // Handles the case when the image name includes the family name - // e.g. image name: debian-11-bullseye-v20220719, family name: debian-11 - if strings.Contains(imageName, familyName) { - return true - } - - if suppressCanonicalFamilyDiff(imageName, familyName) { - return true - } - - if suppressWindowsSqlFamilyDiff(imageName, familyName) { - return true - } - - if suppressWindowsFamilyDiff(imageName, familyName) { - return true - } - - return false -} - -// e.g. image: ubuntu-1404-trusty-v20180122, family: ubuntu-1404-lts -func suppressCanonicalFamilyDiff(imageName, familyName string) bool { - parts := canonicalUbuntuLtsImage.FindStringSubmatch(imageName) - if len(parts) == 3 { - f := fmt.Sprintf("ubuntu-%s%s-lts", parts[1], parts[2]) - if f == familyName { - return true - } - } - - return false -} - -// e.g. image: sql-2017-standard-windows-2016-dc-v20180109, family: sql-std-2017-win-2016 -// e.g. image: sql-2017-express-windows-2012-r2-dc-v20180109, family: sql-exp-2017-win-2012-r2 -func suppressWindowsSqlFamilyDiff(imageName, familyName string) bool { - parts := windowsSqlImage.FindStringSubmatch(imageName) - if len(parts) == 5 { - edition := parts[2] // enterprise, standard or web. - sqlVersion := parts[1] - windowsVersion := parts[3] - - // Translate edition - switch edition { - case "enterprise": - edition = "ent" - case "standard": - edition = "std" - case "express": - edition = "exp" - } - - var f string - if revision := parts[4]; revision != "" { - // With revision - f = fmt.Sprintf("sql-%s-%s-win-%s-r%s", edition, sqlVersion, windowsVersion, revision) - } else { - // No revision - f = fmt.Sprintf("sql-%s-%s-win-%s", edition, sqlVersion, windowsVersion) - } - - if f == familyName { - return true - } - } - - return false -} - -// e.g. image: windows-server-1709-dc-core-v20180109, family: windows-1709-core -// e.g. image: windows-server-1709-dc-core-for-containers-v20180109, family: "windows-1709-core-for-containers -func suppressWindowsFamilyDiff(imageName, familyName string) bool { - updatedFamilyString := strings.Replace(familyName, "windows-", "windows-server-", 1) - updatedImageName := strings.Replace(imageName, "-dc-", "-", 1) - - return strings.Contains(updatedImageName, updatedFamilyString) -} - -func expandComputeDiskType(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) *string { - if v == "" { - return nil - } - - f, err := tpgresource.ParseZonalFieldValue("diskTypes", v.(string), "project", "zone", d, config, true) - if err != nil { - return nil - } - - rl := f.RelativeLink() - return &rl -} - -func expandComputeDiskSourceImage(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) *string { - if v == "" { - return nil - } - - if v == nil { - return nil - } - - project, err := tpgresource.GetProject(d, config) - if err != nil { - return nil - } - - f, err := tpgcompute.ResolveImage(config, project, v.(string)) - if err != nil { - return nil - } - - return &f -} - -func expandComputeDiskSnapshot(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) *string { - if v == "" { - return nil - } - - f, err := tpgresource.ParseGlobalFieldValue("snapshots", v.(string), "project", d, config, true) - if err != nil { - return nil - } - - rl := f.RelativeLink() - return &rl -} - -func ConvertSelfLinkToV1UnlessNil(v interface{}) *string { - if v == nil { - return nil - } - vptr := v.(*string) - - if vptr == nil { - return nil - } - - val := ConvertSelfLinkToV1(*vptr) - return &val -} - -func flattenComputeDiskSnapshot(v interface{}, d *schema.ResourceData, meta interface{}) *string { - config := meta.(*transport_tpg.Config) - if v == nil { - return nil - } - - vptr := v.(*string) - if vptr == nil { - return nil - } - - val, err := tpgresource.ParseGlobalFieldValue("snapshots", *vptr, "project", d, config, true) - if err != nil { - return nil - } - - rl := val.RelativeLink() - return &rl -} - -func flattenComputeDiskImage(v interface{}, d *schema.ResourceData, meta interface{}) *string { - config := meta.(*transport_tpg.Config) - if v == nil { - return nil - } - project, err := tpgresource.GetProject(d, config) - if err != nil { - return nil - } - - vptr := v.(*string) - if vptr == nil { - return nil - } - - f, err := tpgcompute.ResolveImage(config, project, *vptr) - if err != nil { - return nil - } - - return &f -} diff --git a/tpgtools/ignored_handwritten/expanders.go b/tpgtools/ignored_handwritten/expanders.go deleted file mode 100644 index 68bccf28a73a..000000000000 --- a/tpgtools/ignored_handwritten/expanders.go +++ /dev/null @@ -1,36 +0,0 @@ -package google - -import ( - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func expandComputeRouteNextHopInstance(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) *string { - if v == "" { - return nil - } - val, err := tpgresource.ParseZonalFieldValue("instances", v.(string), "project", "next_hop_instance_zone", d, config, true) - if err != nil { - return nil - } - nextInstance, err := config.clientCompute.Instances.Get(val.Project, val.Zone, val.Name).Do() - if err != nil { - return nil - } - return &nextInstance.SelfLink -} - -func expandComputeVpnTunnelRegion(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) *string { - if v == "" { - return nil - } - if reg, ok := v.(string); ok { - return ® - } - - f, err := tpgresource.ParseRegionalFieldValue("targetVpnGateways", d.Get("target_vpn_gateway").(string), "project", "region", "zone", d, config, true) - if err != nil { - return nil - } - return &f.Region -} diff --git a/tpgtools/ignored_handwritten/go.mod b/tpgtools/ignored_handwritten/go.mod deleted file mode 100644 index 8b4fa24a554a..000000000000 --- a/tpgtools/ignored_handwritten/go.mod +++ /dev/null @@ -1,2 +0,0 @@ -// This is an empty go.mod to ensure packages required -// in this folder are not considered part of tpgtools modules. \ No newline at end of file diff --git a/tpgtools/ignored_handwritten/redis_utils.go b/tpgtools/ignored_handwritten/redis_utils.go deleted file mode 100644 index 79d023b2334d..000000000000 --- a/tpgtools/ignored_handwritten/redis_utils.go +++ /dev/null @@ -1,14 +0,0 @@ -package google - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func redisInstanceGetRegionFromLocationID(d *schema.ResourceData, config *transport_tpg.Config) (string, error) { - region, err := tpgresource.GetRegionFromSchema("region", "location_id", d, config) - d.Set("region", region) - - return region, err -} diff --git a/tpgtools/ignored_handwritten/runtimeconfig_utils.go b/tpgtools/ignored_handwritten/runtimeconfig_utils.go deleted file mode 100644 index 3a9487814cea..000000000000 --- a/tpgtools/ignored_handwritten/runtimeconfig_utils.go +++ /dev/null @@ -1,21 +0,0 @@ -package google - -import ( - "fmt" - - runtimeconfig "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/runtimeconfig" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func runtimeconfigVariableValidateTextOrValueSet(d *schema.ResourceData, config *transport_tpg.Config, res *runtimeconfig.Variable) error { - // Validate that both text and value are not set - _, textSet := d.GetOk("text") - _, valueSet := d.GetOk("value") - - if !textSet && !valueSet { - return fmt.Errorf("You must specify one of value or text.") - } - - return nil -} diff --git a/tpgtools/ignored_handwritten/state_setters.go b/tpgtools/ignored_handwritten/state_setters.go deleted file mode 100644 index 1ca85ad32d4d..000000000000 --- a/tpgtools/ignored_handwritten/state_setters.go +++ /dev/null @@ -1,60 +0,0 @@ -package google - -import ( - "fmt" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -// setStateForCollapsedObject sets nested fields as top-level state values for an object that should be collapsed. -// It takes in the flattened value of the object (i.e. converted from *obj.FooBar to []interface{}{map[string]interface{}}). -// Example Usage: -// err := setStateForFieldsInFlattenedObject(d, flattenMyTopLevelNestedObject(obj.MyTopLevelNestedObject)) -func setStateForCollapsedObject(d *schema.ResourceData, v interface{}) error { - if v == nil { - return nil - } - - ls, ok := v.([]interface{}) - if !ok { - return fmt.Errorf("expected nested object value to be flattened to []interface{}") - } - if len(ls) == 0 { - return nil - } - - nestedObj := ls[0].(map[string]interface{}) - for k, kv := range nestedObj { - if err := d.Set(k, kv); err != nil { - return fmt.Errorf("error setting %s in state: %s", k, err) - } - } - return nil -} - -func setStateForTime(d *schema.ResourceData, v time.Time, name string) error { - if !v.IsZero() { - return d.Set(name, fmt.Sprintf(v.Format(time.RFC3339))) - } else { - return d.Set(name, nil) - } -} - -func generateIfNotSet(d *schema.ResourceData, field, prefix string) (string, error) { - if _, ok := d.GetOkExists(field); !ok { - if prefix == "" { - prefix = "tf-generated-" - } - v := id.PrefixedUniqueId(prefix) - if len(v) > 30 { - v = v[:30] - } - - if err := d.Set(field, v); err != nil { - return "", err - } - } - return d.Get(field).(string), nil -} diff --git a/tpgtools/ignored_handwritten/storage_utils.go b/tpgtools/ignored_handwritten/storage_utils.go deleted file mode 100644 index bbb88cfb1ff8..000000000000 --- a/tpgtools/ignored_handwritten/storage_utils.go +++ /dev/null @@ -1,12 +0,0 @@ -package google - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - storage "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/storage" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func forceDestroyBucketObjects(d *schema.ResourceData, config *transport_tpg.Config, bucket *storage.Bucket) error { - return nil -} diff --git a/tpgtools/ignored_handwritten/tpu_utils.go b/tpgtools/ignored_handwritten/tpu_utils.go deleted file mode 100644 index f4ab9e2c1dd4..000000000000 --- a/tpgtools/ignored_handwritten/tpu_utils.go +++ /dev/null @@ -1,17 +0,0 @@ -package google - -import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - -// compareTpuNodeSchedulingConfig diff suppresses for the default -// scheduling, i.e. if preemptible is false, the API may either return no -// schedulingConfig or an empty schedulingConfig. -func compareTpuNodeSchedulingConfig(k, old, new string, d *schema.ResourceData) bool { - if k == "scheduling_config.0.preemptible" { - return old == "" && new == "false" - } - if k == "scheduling_config.#" { - o, n := d.GetChange("scheduling_config.0.preemptible") - return o.(bool) == n.(bool) - } - return false -} diff --git a/tpgtools/ignored_handwritten/validation.go b/tpgtools/ignored_handwritten/validation.go deleted file mode 100644 index 070e5967072c..000000000000 --- a/tpgtools/ignored_handwritten/validation.go +++ /dev/null @@ -1,313 +0,0 @@ -package google - -import ( - "fmt" - "net" - "regexp" - "strconv" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -const ( - // Copied from the official Google Cloud auto-generated client. - ProjectRegex = "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?))" - ProjectRegexWildCard = "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)|-)" - RegionRegex = "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?" - SubnetworkRegex = "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?" - - SubnetworkLinkRegex = "projects/(" + ProjectRegex + ")/regions/(" + RegionRegex + ")/subnetworks/(" + SubnetworkRegex + ")$" - - RFC1035NameTemplate = "[a-z](?:[-a-z0-9]{%d,%d}[a-z0-9])" - CloudIoTIdRegex = "^[a-zA-Z][-a-zA-Z0-9._+~%]{2,254}$" - - // Format of default Compute service accounts created by Google - // ${PROJECT_ID}-compute@developer.gserviceaccount.com where PROJECT_ID is an int64 (max 20 digits) - ComputeServiceAccountNameRegex = "[0-9]{1,20}-compute@developer.gserviceaccount.com" - - // https://cloud.google.com/iam/docs/understanding-custom-roles#naming_the_role - IAMCustomRoleIDRegex = "^[a-zA-Z0-9_\\.]{3,64}$" -) - -var ( - // Service account name must have a length between 6 and 30. - // The first and last characters have different restrictions, than - // the middle characters. The middle characters length must be between - // 4 and 28 since the first and last character are excluded. - ServiceAccountNameRegex = fmt.Sprintf(RFC1035NameTemplate, 4, 28) - - ServiceAccountLinkRegexPrefix = "projects/" + ProjectRegexWildCard + "/serviceAccounts/" - PossibleServiceAccountNames = []string{ - ServiceDefaultAccountNameRegex, - ComputeServiceAccountNameRegex, - CreatedServiceAccountNameRegex, - } - ServiceAccountLinkRegex = ServiceAccountLinkRegexPrefix + "(" + strings.Join(PossibleServiceAccountNames, "|") + ")" - - ServiceAccountKeyNameRegex = ServiceAccountLinkRegexPrefix + "(.+)/keys/(.+)" - - // Format of service accounts created through the API - CreatedServiceAccountNameRegex = fmt.Sprintf(RFC1035NameTemplate, 4, 28) + "@" + ProjectNameInDNSFormRegex + "\\.iam\\.gserviceaccount\\.com$" - - // Format of service-created service account - // examples are: - // $PROJECTID@cloudbuild.gserviceaccount.com - // $PROJECTID@cloudservices.gserviceaccount.com - // $PROJECTID@appspot.gserviceaccount.com - ServiceDefaultAccountNameRegex = ProjectRegex + "@[a-z]+.gserviceaccount.com$" - - ProjectNameInDNSFormRegex = "[-a-z0-9\\.]{1,63}" - ProjectNameRegex = "^[A-Za-z0-9-'\"\\s!]{4,30}$" - - // Valid range for Cloud Router ASN values as per RFC6996 - // https://tools.ietf.org/html/rfc6996 - // Must be explicitly int64 to avoid overflow when building Terraform for 32bit architectures - Rfc6996Asn16BitMin = int64(64512) - Rfc6996Asn16BitMax = int64(65534) - Rfc6996Asn32BitMin = int64(4200000000) - Rfc6996Asn32BitMax = int64(4294967294) - GcpRouterPartnerAsn = int64(16550) -) - -var rfc1918Networks = []string{ - "10.0.0.0/8", - "172.16.0.0/12", - "192.168.0.0/16", -} - -func validateGCPName(v interface{}, k string) (ws []string, errors []error) { - re := `^(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)$` - return validateRegexp(re)(v, k) -} - -// Ensure that the BGP ASN value of Cloud Router is a valid value as per RFC6996 or a value of 16550 -func validateRFC6996Asn(v interface{}, k string) (ws []string, errors []error) { - value := int64(v.(int)) - if !(value >= Rfc6996Asn16BitMin && value <= Rfc6996Asn16BitMax) && - !(value >= Rfc6996Asn32BitMin && value <= Rfc6996Asn32BitMax) && - value != GcpRouterPartnerAsn { - errors = append(errors, fmt.Errorf(`expected %q to be a RFC6996-compliant Local ASN: -must be either in the private ASN ranges: [64512..65534], [4200000000..4294967294]; -or be the value of [%d], got %d`, k, GcpRouterPartnerAsn, value)) - } - return -} - -func validateRegexp(re string) schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(re).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q (%q) doesn't match regexp %q", k, value, re)) - } - - return - } -} - -func validateRFC1918Network(min, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - - s, es = validation.CIDRNetwork(min, max)(i, k) - if len(es) > 0 { - return - } - - v, _ := i.(string) - ip, _, _ := net.ParseCIDR(v) - for _, c := range rfc1918Networks { - if _, ipnet, _ := net.ParseCIDR(c); ipnet.Contains(ip) { - return - } - } - - es = append(es, fmt.Errorf("expected %q to be an RFC1918-compliant CIDR, got: %s", k, v)) - - return - } -} - -func validateRFC3339Time(v interface{}, k string) (warnings []string, errors []error) { - time := v.(string) - if len(time) != 5 || time[2] != ':' { - errors = append(errors, fmt.Errorf("%q (%q) must be in the format HH:mm (RFC3339)", k, time)) - return - } - if hour, err := strconv.ParseUint(time[:2], 10, 0); err != nil || hour > 23 { - errors = append(errors, fmt.Errorf("%q (%q) does not contain a valid hour (00-23)", k, time)) - return - } - if min, err := strconv.ParseUint(time[3:], 10, 0); err != nil || min > 59 { - errors = append(errors, fmt.Errorf("%q (%q) does not contain a valid minute (00-59)", k, time)) - return - } - return -} - -func validateRFC1035Name(min, max int) schema.SchemaValidateFunc { - if min < 2 || max < min { - return func(i interface{}, k string) (s []string, errors []error) { - if min < 2 { - errors = append(errors, fmt.Errorf("min must be at least 2. Got: %d", min)) - } - if max < min { - errors = append(errors, fmt.Errorf("max must greater than min. Got [%d, %d]", min, max)) - } - return - } - } - - return validateRegexp(fmt.Sprintf("^"+RFC1035NameTemplate+"$", min-2, max-2)) -} - -func validateIpCidrRange(v interface{}, k string) (warnings []string, errors []error) { - _, _, err := net.ParseCIDR(v.(string)) - if err != nil { - errors = append(errors, fmt.Errorf("%q is not a valid IP CIDR range: %s", k, err)) - } - return -} - -func validateIAMCustomRoleID(v interface{}, k string) (warnings []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(IAMCustomRoleIDRegex).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q (%q) doesn't match regexp %q", k, value, IAMCustomRoleIDRegex)) - } - return -} - -func orEmpty(f schema.SchemaValidateFunc) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if ok && v == "" { - return nil, nil - } - return f(i, k) - } -} - -func validateProjectID() schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - - if !regexp.MustCompile("^" + ProjectRegex + "$").MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q project_id must be 6 to 30 with lowercase letters, digits, hyphens and start with a letter. Trailing hyphens are prohibited.", value)) - } - return - } -} - -func validateProjectName() schema.SchemaValidateFunc { - return func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - - if !regexp.MustCompile(ProjectNameRegex).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q name must be 4 to 30 characters with lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point.", value)) - } - return - } -} - -func validateDuration() schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - - if _, err := time.ParseDuration(v); err != nil { - es = append(es, fmt.Errorf("expected %s to be a duration, but parsing gave an error: %s", k, err.Error())) - return - } - - return - } -} - -func validateNonNegativeDuration() schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - - dur, err := time.ParseDuration(v) - if err != nil { - es = append(es, fmt.Errorf("expected %s to be a duration, but parsing gave an error: %s", k, err.Error())) - return - } - - if dur < 0 { - es = append(es, fmt.Errorf("duration %v must be a non-negative duration", dur)) - return - } - - return - } -} - -func validateIpAddress(i interface{}, val string) ([]string, []error) { - ip := net.ParseIP(i.(string)) - if ip == nil { - return nil, []error{fmt.Errorf("could not parse %q to IP address", val)} - } - return nil, nil -} - -// StringNotInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type string and that it matches none of the element in the invalid slice. -// if ignorecase is true, case is ignored. -func StringNotInSlice(invalid []string, ignoreCase bool) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - - for _, str := range invalid { - if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { - es = append(es, fmt.Errorf("expected %s to not match any of %v, got %s", k, invalid, v)) - return - } - } - - return - } -} - -// Ensure that hourly timestamp strings "HH:MM" have the minutes zeroed out for hourly only inputs -func validateHourlyOnly(val interface{}, key string) (warns []string, errs []error) { - v := val.(string) - parts := strings.Split(v, ":") - if len(parts) != 2 { - errs = append(errs, fmt.Errorf("%q must be in the format HH:00, got: %s", key, v)) - return - } - if parts[1] != "00" { - errs = append(errs, fmt.Errorf("%q does not allow minutes, it must be in the format HH:00, got: %s", key, v)) - } - i, err := strconv.Atoi(parts[0]) - if err != nil { - errs = append(errs, fmt.Errorf("%q cannot be parsed, it must be in the format HH:00, got: %s", key, v)) - } else if i < 0 || i > 23 { - errs = append(errs, fmt.Errorf("%q does not specify a valid hour, it must be in the format HH:00 where HH : [00-23], got: %s", key, v)) - } - return -} - -func validateRFC3339Date(v interface{}, k string) (warnings []string, errors []error) { - _, err := time.Parse(time.RFC3339, v.(string)) - if err != nil { - errors = append(errors, err) - } - return -} diff --git a/tpgtools/main.go b/tpgtools/main.go deleted file mode 100644 index 479f7c5a94d7..000000000000 --- a/tpgtools/main.go +++ /dev/null @@ -1,620 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "bytes" - "errors" - "flag" - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - "text/template" - - directory "github.com/GoogleCloudPlatform/declarative-resource-client-library/services" - "github.com/golang/glog" - - "github.com/nasa9084/go-openapi" - "gopkg.in/yaml.v2" - - // Used by serialization.go.tmpl, included here to keep `go mod tidy` from removing - // the dependency from go.mod. - _ "github.com/hashicorp/hcl/hcl/fmtcmd" -) - -var fPath = flag.String("path", "", "to be removed - path to the root service directory holding samples") -var tPath = flag.String("overrides", "", "path to the root directory holding overrides files") -var cPath = flag.String("handwritten", "handwritten", "path to the root directory holding handwritten files to copy") -var gPath = flag.String("templates", "templates", "path to the templates directory") -var oPath = flag.String("output", "", "path to output generated files to") - -var sFilter = flag.String("service", "", "optional service name. If specified, only this service is generated") -var rFilter = flag.String("resource", "", "optional resource name (from filename). If specified, only resources with this name are generated") -var vFilter = flag.String("version", "", "optional version name. If specified, this version is preferred for resource generation when applicable") - -var mode = flag.String("mode", "", "mode for the generator. If unset, creates the provider. Options: 'serialization'") - -var terraformResourceDirectory = "google-beta" -var terraformProviderModule = "github.com/hashicorp/terraform-provider-google-beta" - -func main() { - resources, products, err := loadAndModelResources() - if err != nil { - glog.Exitf("Error loading resources: %w", err) - } - - if mode != nil && *mode == "serialization" { - if vFilter != nil { - glog.Warning("[WARNING] serialization mode uses all resource versions. version flag is ignored") - } - generateSerializationLogic(resources) - return - } - - var resourcesForVersion []*Resource - var productsForVersion []*ProductMetadata - var version *Version - if vFilter != nil && *vFilter != "" { - version = fromString(*vFilter) - if version == nil { - glog.Exitf("Failed finding version for input: %s", *vFilter) - } - resourcesForVersion = resources[*version] - productsForVersion = products[*version] - } else { - resourcesForVersion = resources[allVersions()[0]] - productsForVersion = products[allVersions()[0]] - } - if *version == GA_VERSION { - terraformResourceDirectory = "google" - terraformProviderModule = "github.com/hashicorp/terraform-provider-google/google" - } else if *vFilter == ALPHA_VERSION.V { - terraformResourceDirectory = "google-private" - terraformProviderModule = "github.com/hashicorp/terraform-provider-google-private" - } else if *vFilter != "" { - terraformResourceDirectory = "google-" + *vFilter - terraformProviderModule = "github.com/hashicorp/terraform-provider-google-" + *vFilter - } - - generatedResources := make([]*Resource, 0, len(resourcesForVersion)) - for _, resource := range resourcesForVersion { - // Never include serialization-only resources in the list of DCL resources - if resource.SerializationOnly { - continue - } - - // Always add the resource to the list of generated resources so that provider_dcl_resources includes them, - // even if we're only generating one product. - generatedResources = append(generatedResources, resource) - if skipResource(resource) { - continue - } - glog.Infof("Generating from resource %s", resource.TitleCaseFullName()) - - generateResourceFile(resource) - generateSweeperFile(resource) - generateResourceTestFile(resource) - } - - generateProviderResourcesFile(generatedResources) - - // GA website files are always generated for the beta version. - websiteVersion := *version - if *version == GA_VERSION { - websiteVersion = BETA_VERSION - } - for _, resource := range resources[websiteVersion] { - if skipResource(resource) { - continue - } - generateResourceWebsiteFile(resource, resources, version) - } - - // product specific generation - generateProductsFile("provider_dcl_client_creation", productsForVersion) - - if oPath == nil || *oPath == "" { - glog.Info("Skipping copying handwritten files, no output specified") - return - } - - if cPath == nil || *cPath == "" { - glog.Info("No handwritten path specified") - return - } - - // Copy DCL helper files into the folder tpgdclresource to make it easier to remove these files later. - dirPath := path.Join(*oPath, terraformResourceDirectory, "tpgdclresource") - if err := os.MkdirAll(dirPath, os.ModePerm); err != nil { - glog.Error(fmt.Errorf("error creating Terraform tpgdclresource directory %v: %v", dirPath, err)) - } -} - -func skipResource(r *Resource) bool { - // if a filter is specified, skip filtered services - if sFilter != nil && *sFilter != "" && DCLPackageName(*sFilter) != r.ProductMetadata().PackageName { - return true - } - - // skip filtered resources - if rFilter != nil && *rFilter != "" && SnakeCaseTerraformResourceName(*rFilter) != r.Name() { - return true - } - - return false -} - -func loadAndModelResources() (map[Version][]*Resource, map[Version][]*ProductMetadata, error) { - flag.Parse() - if tPath == nil || *tPath == "" { - return nil, nil, errors.New("no path specified") - } - - dirs, err := ioutil.ReadDir(*tPath) - if err != nil { - return nil, nil, err - } - resources := make(map[Version][]*Resource) - products := make(map[Version][]*ProductMetadata) - - for _, version := range allVersions() { - resources[version] = make([]*Resource, 0) - for _, v := range dirs { - // skip flat files- we're looking for service directory - if !v.IsDir() { - continue - } - - var overrideFiles []os.FileInfo - var packagePath Filepath - if version == GA_VERSION { - // GA has no separate directory - packagePath = Filepath(v.Name()) - } else { - packagePath = Filepath(path.Join(v.Name(), version.V)) - } - - overrideFiles, err = ioutil.ReadDir(path.Join(*tPath, string(packagePath))) - var newResources []*Resource - - // keep track of the last document in a service- we need one for the product later - var document *openapi.Document - for _, resourceFile := range overrideFiles { - if resourceFile.IsDir() || resourceFile.Name() == "tpgtools_product.yaml" { - continue - } - - document = &openapi.Document{} - b := directory.Services().GetResource(version.V, v.Name(), stripExt(resourceFile.Name())) - if b == nil { - return nil, nil, fmt.Errorf("could not find resource in DCL directory: %q in %q at %q", stripExt(resourceFile.Name()), packagePath, version.V) - } - - err = yaml.Unmarshal(b.Bytes(), document) - if err != nil { - return nil, nil, err - } - // TODO: the openapi library cannot handle extensions except in the Schema object. If this is ever added, - // this workaround can be removed. - if err := addInfoExtensionsToSchemaObjects(document, b.Bytes()); err != nil { - return nil, nil, err - } - - overrides := loadOverrides(packagePath, resourceFile.Name()) - if len(overrides) > 0 { - glog.Infof("Loaded overrides for %s", resourceFile.Name()) - } - - newResources = append(newResources, createResourcesFromDocumentAndOverrides(document, overrides, packagePath, version)...) - } - - // if we found no resources, just keep going - if document == nil { - continue - } - - products[version] = append(products[version], GetProductMetadataFromDocument(document, packagePath)) - glog.Infof("Loaded product %s", packagePath) - - resources[version] = append(resources[version], newResources...) - } - } - - return resources, products, nil -} - -func addInfoExtensionsToSchemaObjects(document *openapi.Document, b []byte) error { - var m map[string]interface{} - if err := yaml.Unmarshal(b, &m); err != nil { - return err - } - info := m["info"].(map[interface{}]interface{}) - for _, s := range document.Components.Schemas { - s.Extension["x-dcl-ref"] = info["x-dcl-ref"] - s.Extension["x-dcl-guides"] = info["x-dcl-guides"] - } - return nil -} - -func createResourcesFromDocumentAndOverrides(document *openapi.Document, overrides Overrides, packagePath Filepath, version Version) (resources []*Resource) { - productMetadata := GetProductMetadataFromDocument(document, packagePath) - titleParts := strings.Split(document.Info.Title, "/") - - var schema *openapi.Schema - for k, v := range document.Components.Schemas { - if k == titleParts[len(titleParts)-1] { - schema = v - } - } - - if schema == nil { - glog.Exit(fmt.Sprintf("Could not find document schema for %s", document.Info.Title)) - } - - if err := schema.Validate(); err != nil { - glog.Exit(err) - } - - lRaw := schema.Extension["x-dcl-locations"] - var schemaLocations []interface{} - if lRaw == nil { - schemaLocations = make([]interface{}, 0) - } else { - schemaLocations = lRaw.([]interface{}) - } - - typeFetcher := NewTypeFetcher(document) - var locations []string - // If the schema cannot be split into two or more locations, we specify this - // by passing a single empty location string. - if len(schemaLocations) < 2 { - locations = make([]string, 1) - } else { - locations = make([]string, 0, len(schemaLocations)) - for _, l := range schemaLocations { - locations = append(locations, l.(string)) - } - } - - for _, l := range locations { - res, err := createResource(schema, document.Info, typeFetcher, overrides, productMetadata, version, l) - if err != nil { - glog.Exit(err) - } - - resources = append(resources, res) - } - - return resources -} - -// SerializationInput contains an array of resources along with additional generation metadata. -type SerializationInput struct { - Resources map[Version][]*Resource - Packages map[string]string -} - -func generateSerializationLogic(specs map[Version][]*Resource) { - buf := bytes.Buffer{} - tmpl, err := template.New("serialization.go.tmpl").Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, "serialization.go.tmpl"), - ) - if err != nil { - glog.Exit(err) - } - - packageMap := make(map[string]string) - for v, resList := range specs { - for _, res := range resList { - var pkgName, pkgPath string - pkgName = res.Package().lowercase() + v.SerializationSuffix - if v == GA_VERSION { - pkgPath = res.Package().lowercase() - } else { - pkgPath = path.Join(res.Package().lowercase(), v.V) - } - - if _, ok := packageMap[pkgPath]; !ok { - packageMap[pkgName] = pkgPath - } - } - } - - tmplInput := SerializationInput{ - Resources: specs, - Packages: packageMap, - } - - if err = tmpl.ExecuteTemplate(&buf, "serialization.go.tmpl", tmplInput); err != nil { - glog.Exit(err) - } - - formatted, err := formatSource(&buf) - if err != nil { - glog.Error(fmt.Errorf("error formatting serialization logic: %v", err)) - } - - if oPath == nil || *oPath == "" { - fmt.Printf("%v", string(formatted)) - } else { - err := ioutil.WriteFile(path.Join(*oPath, "serialization.go"), formatted, 0644) - if err != nil { - glog.Exit(err) - } - } -} - -func loadOverrides(packagePath Filepath, fileName string) Overrides { - overrides := Overrides{} - if !(tPath == nil) && !(*tPath == "") { - b, err := ioutil.ReadFile(path.Join(*tPath, string(packagePath), fileName)) - if err != nil { - // ignore the error if the file just doesn't exist - if !os.IsNotExist(err) { - glog.Exit(err) - } - } else { - err = yaml.UnmarshalStrict(b, &overrides) - if err != nil { - glog.Exit(err) - } - } - } - return overrides -} - -func getParentDir(res *Resource) string { - servicePath := path.Join(*oPath, terraformResourceDirectory, "services", string(res.Package())) - if err := os.MkdirAll(servicePath, os.ModePerm); err != nil { - glog.Error(fmt.Errorf("error creating Terraform the service directory %v: %v", servicePath, err)) - } - return servicePath -} - -func generateResourceFile(res *Resource) { - // Generate resource file - tmplInput := ResourceInput{ - Resource: *res, - } - - tmpl, err := template.New("resource.go.tmpl").Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, "resource.go.tmpl"), - ) - if err != nil { - glog.Exit(err) - } - - contents := bytes.Buffer{} - if err = tmpl.ExecuteTemplate(&contents, "resource.go.tmpl", tmplInput); err != nil { - glog.Exit(err) - } - - if err != nil { - glog.Exit(err) - } - - formatted, err := formatSource(&contents) - if err != nil { - glog.Error(fmt.Errorf("error formatting %v%v: %v - resource \n ", res.ProductName(), res.Name(), err)) - } - - if oPath == nil || *oPath == "" { - fmt.Printf("%v", string(formatted)) - } else { - outname := fmt.Sprintf("resource_%s_%s.go", res.ProductName(), res.Name()) - parentDir := getParentDir(res) - err = ioutil.WriteFile(path.Join(parentDir, outname), formatted, 0644) - if err != nil { - glog.Exit(err) - } - } -} - -func generateSweeperFile(res *Resource) { - if !res.HasSweeper { - return - } - // Generate resource file - tmplInput := ResourceInput{ - Resource: *res, - } - - tmpl, err := template.New("sweeper.go.tmpl").Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, "sweeper.go.tmpl"), - ) - if err != nil { - glog.Exit(err) - } - - contents := bytes.Buffer{} - if err = tmpl.ExecuteTemplate(&contents, "sweeper.go.tmpl", tmplInput); err != nil { - glog.Exit(err) - } - - if err != nil { - glog.Exit(err) - } - - formatted, err := formatSource(&contents) - if err != nil { - glog.Error(fmt.Errorf("error formatting %v%v: %v - sweeper", res.ProductName(), res.Name(), err)) - } - - if oPath == nil || *oPath == "" { - fmt.Printf("%v", string(formatted)) - } else { - outname := fmt.Sprintf("resource_%s_%s_sweeper.go", res.ProductName(), res.Name()) - parentDir := getParentDir(res) - err := ioutil.WriteFile(path.Join(parentDir, outname), formatted, 0644) - if err != nil { - glog.Exit(err) - } - } -} - -func generateResourceTestFile(res *Resource) { - if len(res.TestSamples()) < 1 { - return - } - // Generate resource file - tmplInput := ResourceInput{ - Resource: *res, - } - - tmpl, err := template.New("test_file.go.tmpl").Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, "test_file.go.tmpl"), - ) - if err != nil { - glog.Exit(err) - } - - contents := bytes.Buffer{} - if err = tmpl.ExecuteTemplate(&contents, "test_file.go.tmpl", tmplInput); err != nil { - fmt.Println(contents.String()) - glog.Exit(err) - } - - if err != nil { - glog.Exit(err) - } - - formatted, err := formatSource(&contents) - if err != nil { - glog.Error(fmt.Errorf("error formatting %v%v: %v - test_file \n ", res.ProductName(), res.Name(), err)) - } - - if oPath == nil || *oPath == "" { - fmt.Printf("%v", string(formatted)) - } else { - outname := fmt.Sprintf("resource_%s_%s_generated_test.go", res.ProductName(), res.Name()) - parentDir := getParentDir(res) - err = ioutil.WriteFile(path.Join(parentDir, outname), formatted, 0644) - if err != nil { - glog.Exit(err) - } - } -} - -func generateProviderResourcesFile(resources []*Resource) { - tmpl, err := template.New("provider_dcl_resources.go.tmpl").Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, "provider_dcl_resources.go.tmpl"), - ) - if err != nil { - glog.Exit(err) - } - - contents := bytes.Buffer{} - if err = tmpl.ExecuteTemplate(&contents, "provider_dcl_resources.go.tmpl", resources); err != nil { - glog.Exit(err) - } - - formatted, err := formatSource(&contents) - if err != nil { - glog.Error(fmt.Errorf("error formatting package provider_dcl_resource.go.tmpl file: \n%w", err)) - } - - if oPath == nil || *oPath == "" { - fmt.Print(string(formatted)) - } else { - if err := os.MkdirAll(filepath.Join(*oPath, terraformResourceDirectory, "provider"), 0755); err != nil { - glog.Exit(err) - } - if err = ioutil.WriteFile(path.Join(*oPath, terraformResourceDirectory, "provider", "provider_dcl_resources.go"), formatted, 0644); err != nil { - glog.Exit(err) - } - } -} - -func generateProductsFile(fileName string, products []*ProductMetadata) { - if len(products) <= 0 { - return - } - templateFileName := fileName + ".go.tmpl" - // Generate endpoints file - tmpl, err := template.New(templateFileName).Funcs(TemplateFunctions).ParseFiles( - filepath.Join(*gPath, templateFileName), - ) - if err != nil { - glog.Exit(err) - } - - contents := bytes.Buffer{} - if err = tmpl.ExecuteTemplate(&contents, templateFileName, products); err != nil { - glog.Exit(err) - } - - formatted, err := formatSource(&contents) - if err != nil { - glog.Error(fmt.Errorf("error formatting package %s file: \n%w", fileName, err)) - } - - if oPath == nil || *oPath == "" { - fmt.Print(string(formatted)) - } else { - outname := fileName + ".go" - - DCLFolderPath := path.Join(*oPath, terraformResourceDirectory, "transport") - if err := os.MkdirAll(DCLFolderPath, os.ModePerm); err != nil { - glog.Error(fmt.Errorf("error creating Terraform DCL directory %v: %v", DCLFolderPath, err)) - } - - if err = ioutil.WriteFile(path.Join(DCLFolderPath, outname), formatted, 0644); err != nil { - glog.Exit(err) - } - } -} - -var TemplateFunctions = template.FuncMap{ - "title": strings.Title, - "patternToRegex": PatternToRegex, - "replace": strings.Replace, - "isLastIndex": isLastIndex, - "escapeDescription": escapeDescription, - "shouldAllowForwardSlashInFormat": shouldAllowForwardSlashInFormat, -} - -// TypeFetcher fetches reused types, as marked by the $ref field being marked on an OpenAPI schema. -type TypeFetcher struct { - doc *openapi.Document - - // Tracks if a property has already been generated. - generates map[string]string -} - -// NewTypeFetcher returns a TypeFetcher for a OpenAPI document. -func NewTypeFetcher(doc *openapi.Document) *TypeFetcher { - return &TypeFetcher{ - doc: doc, - generates: make(map[string]string), - } -} - -// ResolveSchema resolves a #/components/schemas reference from a reused type. -func (r *TypeFetcher) ResolveSchema(ref string) (*openapi.Schema, error) { - return openapi.ResolveSchema(r.doc, ref) -} - -// PackagePathForReference returns either the packageName or the shared package name. -func (r *TypeFetcher) PackagePathForReference(ref, packageName string) string { - if v, ok := r.generates[ref]; ok { - return v - } else { - r.generates[ref] = packageName - return packageName - } -} diff --git a/tpgtools/main_helpers.go b/tpgtools/main_helpers.go deleted file mode 100644 index 4f7f79e6e5e1..000000000000 --- a/tpgtools/main_helpers.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "bytes" - "fmt" - "go/format" - "strconv" - "strings" - - "github.com/kylelemons/godebug/pretty" -) - -// Sort id formats based on the order they should be matched. This is -// most specific first, so {{project}}/{{region}}/{{name}} would be applied -// before {{region}}/{{name}} -func formatComparator(formats []string) func(i, j int) bool { - return func(i, j int) bool { - l := formats[i] - r := formats[j] - - lBrace := strings.Count(l, "{{") - rBrace := strings.Count(r, "{{") - - lSlash := strings.Count(l, "/") - rSlash := strings.Count(r, "/") - - if lBrace == rBrace { - return lSlash > rSlash // > and not <, we want more to appear first - } - - return lBrace > rBrace - } -} - -func escapeDescription(in string) string { - return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(in, `\`, `\\`), `"`, `\"`), "\n", `\n`) -} - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} - -func stripExt(s string) string { - n := strings.LastIndexByte(s, '.') - if n >= 0 { - return s[:n] - } - return s -} - -func sprintResource(v interface{}) string { - prettyConfig := &pretty.Config{ - Diffable: true, - } - return prettyConfig.Sprint(v) -} - -func formatSource(source *bytes.Buffer) ([]byte, error) { - sourceByte := source.Bytes() - // Replace import path based on version (beta/alpha) - if terraformResourceDirectory != "google" { - sourceByte = bytes.Replace(sourceByte, []byte("github.com/hashicorp/terraform-provider-google/google"), []byte(terraformProviderModule+"/"+terraformResourceDirectory), -1) - } - - output, err := format.Source(sourceByte) - if err != nil { - return []byte(source.String()), err - } - - return output, nil -} - -func renderDefault(t Type, val string) (string, error) { - switch t.String() { - case SchemaTypeBool: - if b, err := strconv.ParseBool(val); err == nil { - return fmt.Sprintf("%v", b), nil - } else { - return "", fmt.Errorf("Failed to render default for boolean: %s", val) - } - case SchemaTypeFloat: - if f, err := strconv.ParseFloat(val, 64); err == nil { - return fmt.Sprintf("%f", f), nil - } else { - return "", fmt.Errorf("Failed to render default for float: %s", val) - } - case SchemaTypeInt: - if i, err := strconv.ParseInt(val, 10, 64); err == nil { - return fmt.Sprintf("%d", i), nil - } else { - return "", fmt.Errorf("Failed to render default for int: %s", val) - } - case SchemaTypeString: - return fmt.Sprintf("%q", val), nil - } - return "", fmt.Errorf("Failed to find default format for type: %v", t) -} diff --git a/tpgtools/misc_utils.go b/tpgtools/misc_utils.go deleted file mode 100644 index 19838c010b55..000000000000 --- a/tpgtools/misc_utils.go +++ /dev/null @@ -1,5 +0,0 @@ -package main - -func isLastIndex(array []string, index int) bool { - return len(array)-1 == index -} diff --git a/tpgtools/names.go b/tpgtools/names.go deleted file mode 100644 index 8a98ac017912..000000000000 --- a/tpgtools/names.go +++ /dev/null @@ -1,151 +0,0 @@ -package main - -import "strings" - -// We struggle with many types of names, and many conversions between types of names. In order to sanitize all of this, -// we have four interfaces, and many string-aliased types, which conform to at most one of the interfaces. -// This way, we can't wind up with complex, lossy, and hard-to-trace name conversions, which used to be a big problem in tpgtools. -// The functions are not really meant to be called, so much, but they are useful for converting back to regular strings where needed. -type snakeCaseName interface { - snakecase() string -} - -type titleCaseName interface { - titlecase() string -} - -type jsonCaseName interface { - jsoncase() string -} - -type lowercaseName interface { - lowercase() string -} - -// e.g. `google_compute_instance` or `google_orgpolicy_policy`. -type SnakeCaseTerraformResourceName string - -func (s SnakeCaseTerraformResourceName) snakecase() string { - return string(s) -} - -// e.g. `ComputeInstanceGroupManager`. -type TitleCaseFullName string - -func (s TitleCaseFullName) titlecase() string { - return string(s) -} - -// e.g. "compute_firewall_rule" -type SnakeCaseFullName string - -func (s SnakeCaseFullName) snakecase() string { - return string(s) -} - -// e.g. "os_policy" -type SnakeCaseProductName string - -func (s SnakeCaseProductName) snakecase() string { - return string(s) -} - -func (s SnakeCaseProductName) ToTitle() RenderedString { - return RenderedString(snakeToTitleCase(s).titlecase()) -} - -// e.g. "ForwardingRule" -type TitleCaseResourceName string - -func (t TitleCaseResourceName) titlecase() string { - return string(t) -} - -// e.g. "computeinstancegroupmanager". -type ConjoinedString string - -// snakeToLowercase converts a snake_case string to a conjoined string -func snakeToLowercase(s snakeCaseName) ConjoinedString { - return ConjoinedString(strings.Join(snakeToParts(s, false), "")) -} - -// snakeToTitleCase converts a snake_case string to TitleCase / Go struct case. -func snakeToTitleCase(s snakeCaseName) miscellaneousNameTitleCase { - return miscellaneousNameTitleCase(strings.Join(snakeToParts(s, true), "")) -} - -// A type for a string that is not meant for further conversion. Some functions return a -// RenderedString to indicate that they have been lossily converted to another format. -type RenderedString string - -func (r RenderedString) String() string { - return string(r) -} - -func renderSnakeAsTitle(s snakeCaseName) RenderedString { - return RenderedString(strings.Join(snakeToParts(s, true), "")) -} - -// e.g. "ospolicy" -type DCLPackageName string - -func (d DCLPackageName) lowercase() string { - return string(d) -} - -type BasePathOverrideNameSnakeCase string - -func (b BasePathOverrideNameSnakeCase) snakecase() string { - return string(b) -} -func (b BasePathOverrideNameSnakeCase) ToUpper() RenderedString { - return RenderedString(strings.ToUpper(string(b))) -} - -func (b BasePathOverrideNameSnakeCase) ToTitle() RenderedString { - title := snakeToTitleCase(b).titlecase() - // Got to special case the capitalization of "OS" in "OSConfig", for base paths specifically, - // because of interop with MMv1. - if strings.HasPrefix(string(b), "os") { - return RenderedString("OS" + title[2:]) - } - if strings.HasPrefix(string(b), "gkehub") { - return RenderedString("GKEHub" + title[6:]) - } - if strings.HasPrefix(string(b), "vertex_ai") { - return RenderedString("VertexAI" + title[8:]) - } - return RenderedString(title) -} - -// A path on the filesystem, usually relative to the root of the tpgtools/ directory. -type Filepath string - -// A package path, potentially including a version suffix. -// e.g. "ospolicy/beta" or "ospolicy" -type DCLPackageNameWithVersion string - -// A type for some string, not one of the things that have a specific type above, which is in -// a particular case. This is useful because we want to be able to write strings functions that take in -// a snake case string or return a snake case string, which works even if the string isn't a -// specific type. -// -// Also, having all these misc strings prevents us from winding up with a bunch of `string` types -// for things that should be explicit. -type miscellaneousNameSnakeCase string - -func (m miscellaneousNameSnakeCase) snakecase() string { - return string(m) -} - -type miscellaneousNameTitleCase string - -func (m miscellaneousNameTitleCase) titlecase() string { - return string(m) -} - -type miscellaneousNameLowercase string - -func (m miscellaneousNameLowercase) lowercase() string { - return string(m) -} diff --git a/tpgtools/override.go b/tpgtools/override.go deleted file mode 100644 index 53bd465818be..000000000000 --- a/tpgtools/override.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "fmt" - - "github.com/golang/glog" - "gopkg.in/yaml.v2" -) - -// When adding a new override, write a doc about it using go/tpgtools-new-feature and add it to go/tpgtools-overrides. - -type OverrideType string // enum - -// Product-level Overrides -const ( - ProductBasePath OverrideType = "PRODUCT_BASE_PATH" - ProductTitle OverrideType = "PRODUCT_TITLE" - ProductDocsSection OverrideType = "PRODUCT_DOCS_SECTION" -) - -// Resource-level Overrides -const ( - VirtualField OverrideType = "VIRTUAL_FIELD" - CustomID = "CUSTOM_ID" - CustomizeDiff = "CUSTOMIZE_DIFF" - ImportFormat = "IMPORT_FORMAT" - AppendToBasePath = "APPEND_TO_BASE_PATH" - ReplaceInBasePath = "REPLACE_IN_BASE_PATH" - Mutex = "MUTEX" - PreCreate = "PRE_CREATE_FUNCTION" - PostCreate = "POST_CREATE_FUNCTION" - PreDelete = "PRE_DELETE_FUNCTION" - SkipInProvider = "SKIP_IN_PROVIDER" - CustomResourceName = "CUSTOM_RESOURCE_NAME" - NoSweeper = "NO_SWEEPER" - CustomImport = "CUSTOM_IMPORT_FUNCTION" - CustomCreateDirective = "CUSTOM_CREATE_DIRECTIVE_FUNCTION" - SkipDeleteFunction = "SKIP_DELETE_FUNCTION" - SerializationOnly = "SERIALIZATION_ONLY" - CustomSerializer = "CUSTOM_SERIALIZER" - TerraformProductName = "CUSTOM_TERRAFORM_PRODUCT_NAME" - CustomTimeout = "CUSTOM_TIMEOUT" - StateUpgrade = "STATE_UPGRADE" - GenerateLongFormTests = "GENERATE_LONG_FORM_TESTS" -) - -// Field-level Overrides -const ( - CustomConfigMode OverrideType = "CUSTOM_CONFIG_MODE" - CustomDescription = "CUSTOM_DESCRIPTION" - NamePrefix = "NAME_PREFIX" - CustomName = "CUSTOM_NAME" - CustomStateGetter = "CUSTOM_STATE_GETTER" - CustomStateSetter = "CUSTOM_STATE_SETTER" - CustomValidation = "CUSTOM_VALIDATION" - Deprecated = "DEPRECATED" - DiffSuppressFunc = "DIFF_SUPPRESS_FUNC" - EnumBool = "ENUM_BOOL" - Exclude = "EXCLUDE" - CustomIdentityGetter = "CUSTOM_IDENTITY_GETTER" - Removed = "REMOVED" - SetHashFunc = "SET_HASH_FUNC" - CollapsedObject = "COLLAPSED_OBJECT" - IgnoreRead = "IGNORE_READ" - GenerateIfNotSet = "GENERATE_IF_NOT_SET" - CustomListSize = "CUSTOM_LIST_SIZE_CONSTRAINT" - CustomDefault = "CUSTOM_DEFAULT" - CustomSchemaValues = "CUSTOM_SCHEMA_VALUES" - ComplexMapKey = "COMPLEX_MAP_KEY_NAME" -) - -// Overrides represents the type a resource's override file can be marshalled -// into. -type Overrides []Override - -// Overrides handle minor quirks in behaviour for a resource (or one of its -// fields) by injecting modifications into the generated code for the resource. -// Every Override will have a Type; Overrides with a Field defined apply to that -// field in the resource and overrives without apply to the resource; Overrides -// may contain Details with structured metadata. -type Override struct { - Type OverrideType - Field *string // may be nil - Details interface{} // may be nil - Location *string // may be nil -} - -// ResourceOverride returns whether a single override with a single OverrideType -// is present on the resource. -func (o Overrides) ResourceOverride(typ OverrideType, location string) bool { - found := false - for _, v := range o { - if v.Field == nil && v.Type == typ && compareLocation(v.Location, location) { - if found { - glog.Fatalf("found duplicate override of type %v", typ) - } - - found = true - } - } - - return found -} - -// ResourceOverrideWithDetails returns whether a single OverrideType is present -// on the resource, and includes the override's Details in the i interface if so. -func (o Overrides) ResourceOverrideWithDetails(typ OverrideType, i interface{}, location string) (bool, error) { - found := false - for _, v := range o { - if v.Field == nil && v.Type == typ && compareLocation(v.Location, location) { - if found { - return false, fmt.Errorf("found duplicate override of type %v", typ) - } - - found = true - if err := convert(v.Details, i); err != nil { - return false, fmt.Errorf("error converting type: %v", err) - } - } - } - - return found, nil -} - -// ResourceOverridesWithDetails returns all OverrideTypes of a given type on the -// resource, returning their details as yaml in an array. -// TODO: make this generic when Go supports generics -// ResourceOverrideWithDetails (the singular variant) is preferred when multiple -// overrides of a given type are not expected. -func (o Overrides) ResourceOverridesWithDetails(typ OverrideType, location string) (overrides []interface{}) { - for _, v := range o { - if v.Field == nil && v.Type == typ && compareLocation(v.Location, location) { - overrides = append(overrides, v.Details) - } - } - - return overrides -} - -// PropertyOverride returns whether a single override with a single OverrideType -// is present on a given property. -func (o Overrides) PropertyOverride(typ OverrideType, p Property, location string) bool { - found := false - for _, v := range o { - if v.Field != nil && *v.Field == p.overridePath() && v.Type == typ && compareLocation(v.Location, location) { - if found { - glog.Fatalf("found duplicate override of type %v", typ) - } - - found = true - } - } - - return found -} - -// PropertyOverrideWithDetails returns whether a single OverrideType is present -// on a property, and includes the override's Details in the i interface if so. -func (o Overrides) PropertyOverrideWithDetails(typ OverrideType, p Property, i interface{}, location string) (bool, error) { - found := false - for _, v := range o { - if v.Field != nil && *v.Field == p.overridePath() && v.Type == typ && compareLocation(v.Location, location) { - if found { - return false, fmt.Errorf("found duplicate override of type %v", typ) - } - - found = true - if err := convert(v.Details, i); err != nil { - return false, fmt.Errorf("error converting type: %v", err) - } - } - } - - return found, nil -} - -// ProductWithDetails returns whether a single OverrideType is present -// on the resource, and includes the override's Details in the i interface if so. -func (o Overrides) ProductOverrideWithDetails(typ OverrideType, i interface{}) (bool, error) { - found := false - for _, v := range o { - if v.Field == nil && v.Type == typ { - if found { - return false, fmt.Errorf("found duplicate override of type %v", typ) - } - - found = true - if err := convert(v.Details, i); err != nil { - return false, fmt.Errorf("error converting type: %v", err) - } - } - } - - return found, nil -} - -func compareLocation(overrideLocation *string, objectLocation string) bool { - // Overrides without a location field are considered valid for every location - if overrideLocation == nil { - return true - } - return *overrideLocation == objectLocation -} - -func convert(item, out interface{}) error { - bytes, err := yaml.Marshal(item) - if err != nil { - return fmt.Errorf("failed to marshal: %v", err) - } - - err = yaml.Unmarshal(bytes, out) - if err != nil { - return err - } - - return nil -} diff --git a/tpgtools/override_details.go b/tpgtools/override_details.go deleted file mode 100644 index 963c23656e92..000000000000 --- a/tpgtools/override_details.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -// -----------BEFORE ADDING NEW OVERRIDES------------ -// Any new override added to tpgtools should have an associated design doc -// See go/tpgtools-new-feature for the template. -// This allows us to further document why overrides were added and -// how they should be used. -// Add these docs to go/tpgtools-overrides when the override is submitted. - -// VirtualFieldDetails are the details used to construct a virtual field, a -// Terraform-only field that represents Terraform-specific resource behaviour -// that deviates from the DCL. -type VirtualFieldDetails struct { - // Name is the name of the property in Terraform, in snake_case. - Name string - // Name of the field's type eg "string", "boolean", "integer" - Type string - // If set to true, the field is an output-only field. - Output bool -} - -type PreCreateFunctionDetails struct { - // Function is the name of the function to call. Arguments are decided by - // the generated code based on the resource's identity, with the format - // (d, config, res). - // This function is expected to return an error. - Function string -} - -type PostCreateFunctionDetails struct { - // Function is the name of the function to call. Arguments are decided by - // the generated code based on the resource's identity, with the format - // (d, config, res). - // This function is expected to return an error. - Function string -} - -type PreDeleteFunctionDetails struct { - // Function is the name of the function to call. Arguments are decided by - // the generated code based on the resource's identity, with the format - // (d, config, res). - // This function is expected to return an error. - Function string -} - -type CustomImportFunctionDetails struct { - // Function is the name of the function to call. Arguments are decided by - // the generated code based on the resource's identity, with the format - // (d, config, {{identity}}). For example: - // (d *schema.ResourceData, config *transport_tpg.Config, project, location, name string) - // This function is expected to return an error. - Function string -} - -type AppendToBasePathDetails struct { - // AppendToBasePath appends the given string onto the end of the config base path. - String string -} - -type ReplaceInBasePathDetails struct { - // ReplaceInBasePath replaces the config base path with the value returned - // by the given string. - // For example, client.Config.BasePath + "v1" would append "v1" to the current - // base path. - Present bool - Old string - New string -} - -type CustomizeDiffDetails struct { - // Functions is a list of CustomizeDiffFunc to use with - // customdiff.All(...). - Functions []string -} - -type CustomConfigModeDetails struct { - Mode string -} - -type CustomDescriptionDetails struct { - // Formatted CommonMark description for the property. - Description string -} - -type CustomDiffSuppressFuncDetails struct { - // Name of the DSF to apply to a property - DiffSuppressFunc string -} - -type CustomIDDetails struct { - // The pattern string of the Terraform resource's id - ID string -} - -type CustomNameDetails struct { - // The overriding name of the property in Terraform, in snake_case. - Name string -} - -type CustomValidationDetails struct { - // Function is the name of a ValidationFunc to apply to a property - Function string -} - -type SetHashFuncDetails struct { - // Name of the function to determine the unique ID of an item in the set - Function string -} - -type RemovedDetails struct { - // Message describing a removed field - Message string -} - -type DeprecatedDetails struct { - // Message describing a deprecated field - Message string -} - -// A CustomIdentityGetter is used to replace the default getX function for -// fields that are inferred from multiple places. -// In the future, this override could be used to attach getX functions to fields -// that don't match the standard name exactly as well. -type CustomIdentityGetterDetails struct { - // The name of the function to call to retrieve the value. An error is - // expected to be returned. - Function string -} - -type CustomDefaultDetails struct { - Default string -} - -type CustomListSizeConstraintDetails struct { - Min int64 - Max int64 -} - -type CustomSchemaValuesDetails struct { - Required bool - Optional bool - Computed bool -} - -type ImportFormatDetails struct { - // List of import format pattern strings - Formats []string -} - -type MutexDetails struct { - // The pattern string for the mutex lock name preventing concurrent calls to - // the resource - Mutex string -} - -type CustomStateGetterDetails struct { - // The function that is used as the StateGetter. - Function string -} - -type CustomStateSetterDetails struct { - // The function that is used as the StateSetter. - Function string -} - -type CustomResourceNameDetails struct { - // The name of the resource in terraform. - Title string -} - -type CustomCreateDirectiveDetails struct { - // The name of function that will return the create directive. - Function string -} - -type CustomSerializerDetails struct { - // The name of the function that will serialize this resource. - Function string -} - -type SkipDeleteFunctionDetails struct { - // The name of the function that determines if we should skip delete. - Function string -} - -type TerraformProductNameDetails struct { - // The name of the product in terraform. - Product string -} - -type ProductBasePathDetails struct { - // If set to true, generating the product base path should be skipped - // This is the case when mmv1 already generates base path support - Skip bool - // Alternative product base path name to allow for DCL-based resources to use - // different default base paths than mmv1 generated resources - BasePathIdentifier string -} - -type ProductTitleDetails struct { - // alternative name to be used for the product resources - Title string -} - -type ProductDocsSectionDetails struct { - // alternative name to be used for the product resources in docs. - DocsSection string -} - -type CustomTimeoutDetails struct { - // The overriding Timeouts in Terraform - TimeoutMinutes int -} - -type StateUpgradeDetails struct { - // The current schema version - SchemaVersion int -} - -type ComplexMapKeyDetails struct { - // The name of the key as exposed by Terraform - KeyName string -} diff --git a/tpgtools/overrides/apikeys/beta/key.yaml b/tpgtools/overrides/apikeys/beta/key.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/apikeys/beta/key.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/apikeys/beta/tpgtools_product.yaml b/tpgtools/overrides/apikeys/beta/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/apikeys/beta/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/apikeys/key.yaml b/tpgtools/overrides/apikeys/key.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/apikeys/key.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/apikeys/samples/key/meta.yaml b/tpgtools/overrides/apikeys/samples/key/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/apikeys/samples/key/service_account_key.tf.tmpl b/tpgtools/overrides/apikeys/samples/key/service_account_key.tf.tmpl deleted file mode 100644 index a0b9a45815dd..000000000000 --- a/tpgtools/overrides/apikeys/samples/key/service_account_key.tf.tmpl +++ /dev/null @@ -1,19 +0,0 @@ -resource "google_apikeys_key" "primary" { - name = "{{key}}" - display_name = "sample-key" - project = google_project.project.project_id - service_account_email = google_service_account.key_service_account.email -} - -resource "google_project" "project" { - project_id = "{{app}}" - name = "{{app}}" - org_id = "{{org_id}}" - deletion_policy = "DELETE" -} - -resource "google_service_account" "key_service_account" { - account_id = "{{app}}" - project = google_project.project.project_id - display_name = "Test Service Account" -} \ No newline at end of file diff --git a/tpgtools/overrides/apikeys/samples/key/service_account_key.yaml b/tpgtools/overrides/apikeys/samples/key/service_account_key.yaml deleted file mode 100755 index 6b60761db48e..000000000000 --- a/tpgtools/overrides/apikeys/samples/key/service_account_key.yaml +++ /dev/null @@ -1,11 +0,0 @@ -variables: - - name: "app" - type: "resource_name" - - name: "project" - type: "project" - - name: "key" - type: "resource_name" - - name: "org_id" - type: "org_id" - - name: "billing_account" - type: "billing_account" diff --git a/tpgtools/overrides/apikeys/tpgtools_product.yaml b/tpgtools/overrides/apikeys/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/apikeys/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/assuredworkloads/beta/tpgtools_product.yaml b/tpgtools/overrides/assuredworkloads/beta/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/assuredworkloads/beta/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/assuredworkloads/beta/workload.yaml b/tpgtools/overrides/assuredworkloads/beta/workload.yaml deleted file mode 100644 index b75a7c4a3f6b..000000000000 --- a/tpgtools/overrides/assuredworkloads/beta/workload.yaml +++ /dev/null @@ -1,12 +0,0 @@ -- type: CUSTOM_SCHEMA_VALUES - field: enable_sovereign_controls - details: - required: false - optional: true - computed: true -- type: CUSTOM_SCHEMA_VALUES - field: violation_notifications_enabled - details: - required: false - optional: true - computed: true \ No newline at end of file diff --git a/tpgtools/overrides/assuredworkloads/samples/workload/basic.tf.tmpl b/tpgtools/overrides/assuredworkloads/samples/workload/basic.tf.tmpl deleted file mode 100644 index 3b180aa00b11..000000000000 --- a/tpgtools/overrides/assuredworkloads/samples/workload/basic.tf.tmpl +++ /dev/null @@ -1,31 +0,0 @@ -resource "google_assured_workloads_workload" "primary" { - display_name = "{{name}}" - labels = { - a = "a" - } - billing_account = "billingAccounts/{{billing_account}}" - compliance_regime = "FEDRAMP_MODERATE" - provisioned_resources_parent = google_folder.folder1.name - organization = "{{org_id}}" - location = "us-central1" - workload_options { - kaj_enrollment_type = "KEY_ACCESS_TRANSPARENCY_OFF" - } - resource_settings { - resource_type = "CONSUMER_FOLDER" - display_name = "folder-display-name" - } - violation_notifications_enabled = true - depends_on = [time_sleep.wait_120_seconds] -} - -resource "time_sleep" "wait_120_seconds" { - create_duration = "120s" - depends_on = [google_folder.folder1] -} - -resource "google_folder" "folder1" { - display_name = "{{name}}" - parent = "organizations/{{org_id}}" - deletion_protection = false -} \ No newline at end of file diff --git a/tpgtools/overrides/assuredworkloads/samples/workload/basic.yaml b/tpgtools/overrides/assuredworkloads/samples/workload/basic.yaml deleted file mode 100755 index c94704d3895e..000000000000 --- a/tpgtools/overrides/assuredworkloads/samples/workload/basic.yaml +++ /dev/null @@ -1,14 +0,0 @@ -# optional test level config -- needed for updates basic.tf.tmpl def -updates: -- resource: ./basic_update.tf.tmpl -variables: - - name: "name" - type: "resource_name" - - name: "region" - type: "region" - - name: "org_id" - type: "org_id" - - name: "billing_account" - type: "billing_account" -external_providers: - - "time" diff --git a/tpgtools/overrides/assuredworkloads/samples/workload/basic_update.tf.tmpl b/tpgtools/overrides/assuredworkloads/samples/workload/basic_update.tf.tmpl deleted file mode 100644 index 8862249ca04d..000000000000 --- a/tpgtools/overrides/assuredworkloads/samples/workload/basic_update.tf.tmpl +++ /dev/null @@ -1,28 +0,0 @@ -resource "google_assured_workloads_workload" "primary" { - display_name = "{{name}}" - labels = { - a = "b" - } - billing_account = "billingAccounts/{{billing_account}}" - compliance_regime = "FEDRAMP_MODERATE" - provisioned_resources_parent = google_folder.folder1.name - organization = "{{org_id}}" - location = "us-central1" - resource_settings { - resource_type = "CONSUMER_FOLDER" - display_name = "folder-display-name" - } - violation_notifications_enabled = true - depends_on = [time_sleep.wait_120_seconds] -} - -resource "time_sleep" "wait_120_seconds" { - create_duration = "120s" - depends_on = [google_folder.folder1] -} - -resource "google_folder" "folder1" { - display_name = "{{name}}" - parent = "organizations/{{org_id}}" - deletion_protection = false -} \ No newline at end of file diff --git a/tpgtools/overrides/assuredworkloads/samples/workload/full.tf.tmpl b/tpgtools/overrides/assuredworkloads/samples/workload/full.tf.tmpl deleted file mode 100644 index a1c157e5cadf..000000000000 --- a/tpgtools/overrides/assuredworkloads/samples/workload/full.tf.tmpl +++ /dev/null @@ -1,25 +0,0 @@ -resource "google_assured_workloads_workload" "primary" { - display_name = "{{name}}" - billing_account = "billingAccounts/{{billing_account}}" - compliance_regime = "FEDRAMP_MODERATE" - organization = "{{org_id}}" - location = "us-central1" - kms_settings { - next_rotation_time = "2022-10-02T15:01:23Z" - rotation_period = "864000s" - } - provisioned_resources_parent = google_folder.folder1.name - depends_on = [time_sleep.wait_120_seconds] -} - -resource "time_sleep" "wait_120_seconds" { - create_duration = "120s" - depends_on = [google_folder.folder1] -} - - -resource "google_folder" "folder1" { - display_name = "{{name}}" - parent = "organizations/{{org_id}}" - deletion_protection = false -} diff --git a/tpgtools/overrides/assuredworkloads/samples/workload/full.yaml b/tpgtools/overrides/assuredworkloads/samples/workload/full.yaml deleted file mode 100644 index b5f58de37b71..000000000000 --- a/tpgtools/overrides/assuredworkloads/samples/workload/full.yaml +++ /dev/null @@ -1,11 +0,0 @@ -variables: - - name: "name" - type: "resource_name" - - name: "region" - type: "region" - - name: "org_id" - type: "org_id" - - name: "billing_account" - type: "billing_account" -external_providers: - - "time" \ No newline at end of file diff --git a/tpgtools/overrides/assuredworkloads/samples/workload/meta.yaml b/tpgtools/overrides/assuredworkloads/samples/workload/meta.yaml deleted file mode 100644 index e986c6a03e42..000000000000 --- a/tpgtools/overrides/assuredworkloads/samples/workload/meta.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# meta.yaml -# this is a shared config file that all the tests merge with -# -ignore_read: - - "billing_account" - - "kms_settings" - - "resource_settings" - - "workload_options" - - "provisioned_resources_parent" - - "partner_services_billing_account" -doc_hide: - - basic.tf.tmpl # basic_update.tf.tmpl auto hides - - full.tf.tmpl -test_hide: - - basic_workload.yaml \ No newline at end of file diff --git a/tpgtools/overrides/assuredworkloads/tpgtools_product.yaml b/tpgtools/overrides/assuredworkloads/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/assuredworkloads/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/assuredworkloads/workload.yaml b/tpgtools/overrides/assuredworkloads/workload.yaml deleted file mode 100644 index 617746f0f6a6..000000000000 --- a/tpgtools/overrides/assuredworkloads/workload.yaml +++ /dev/null @@ -1,6 +0,0 @@ -- type: CUSTOM_SCHEMA_VALUES - field: violation_notifications_enabled - details: - required: false - optional: true - computed: true \ No newline at end of file diff --git a/tpgtools/overrides/cloudbuild/beta/tpgtools_product.yaml b/tpgtools/overrides/cloudbuild/beta/tpgtools_product.yaml deleted file mode 100644 index b260c549bce5..000000000000 --- a/tpgtools/overrides/cloudbuild/beta/tpgtools_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true - basepathidentifier: cloud_build -- type: PRODUCT_TITLE # used to align with mmv1 product - details: - title: "cloudbuild" diff --git a/tpgtools/overrides/cloudbuild/beta/worker_pool.yaml b/tpgtools/overrides/cloudbuild/beta/worker_pool.yaml deleted file mode 100644 index 8c8073b08ca5..000000000000 --- a/tpgtools/overrides/cloudbuild/beta/worker_pool.yaml +++ /dev/null @@ -1,10 +0,0 @@ -- type: DIFF_SUPPRESS_FUNC - field: network_config.peered_network - details: - diffsuppressfunc: tpgresource.CompareResourceNames -- type: EXCLUDE - field: etag -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/cloudbuild/tpgtools_product.yaml b/tpgtools/overrides/cloudbuild/tpgtools_product.yaml deleted file mode 100644 index b260c549bce5..000000000000 --- a/tpgtools/overrides/cloudbuild/tpgtools_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true - basepathidentifier: cloud_build -- type: PRODUCT_TITLE # used to align with mmv1 product - details: - title: "cloudbuild" diff --git a/tpgtools/overrides/cloudbuild/worker_pool.yaml b/tpgtools/overrides/cloudbuild/worker_pool.yaml deleted file mode 100644 index 8c8073b08ca5..000000000000 --- a/tpgtools/overrides/cloudbuild/worker_pool.yaml +++ /dev/null @@ -1,10 +0,0 @@ -- type: DIFF_SUPPRESS_FUNC - field: network_config.peered_network - details: - diffsuppressfunc: tpgresource.CompareResourceNames -- type: EXCLUDE - field: etag -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/clouddeploy/beta/delivery_pipeline.yaml b/tpgtools/overrides/clouddeploy/beta/delivery_pipeline.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/clouddeploy/beta/delivery_pipeline.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/clouddeploy/beta/target.yaml b/tpgtools/overrides/clouddeploy/beta/target.yaml deleted file mode 100644 index 87b99fc0dce7..000000000000 --- a/tpgtools/overrides/clouddeploy/beta/target.yaml +++ /dev/null @@ -1,8 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: COMPLEX_MAP_KEY_NAME - field: associated_entities - details: - keyname: entity_id diff --git a/tpgtools/overrides/clouddeploy/beta/tpgtools_product.yaml b/tpgtools/overrides/clouddeploy/beta/tpgtools_product.yaml deleted file mode 100644 index e476d2d19731..000000000000 --- a/tpgtools/overrides/clouddeploy/beta/tpgtools_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -## product level overrides -- type: PRODUCT_BASE_PATH - details: - skip: true -- type: PRODUCT_DOCS_SECTION - details: - docssection: Cloud Deploy diff --git a/tpgtools/overrides/clouddeploy/delivery_pipeline.yaml b/tpgtools/overrides/clouddeploy/delivery_pipeline.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/clouddeploy/delivery_pipeline.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/clouddeploy/samples/deliverypipeline/meta.yaml b/tpgtools/overrides/clouddeploy/samples/deliverypipeline/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/clouddeploy/samples/target/meta.yaml b/tpgtools/overrides/clouddeploy/samples/target/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/clouddeploy/target.yaml b/tpgtools/overrides/clouddeploy/target.yaml deleted file mode 100644 index ca7a0b536fff..000000000000 --- a/tpgtools/overrides/clouddeploy/target.yaml +++ /dev/null @@ -1,8 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: COMPLEX_MAP_KEY_NAME - field: associated_entities - details: - keyname: entity_id \ No newline at end of file diff --git a/tpgtools/overrides/clouddeploy/tpgtools_product.yaml b/tpgtools/overrides/clouddeploy/tpgtools_product.yaml deleted file mode 100644 index e476d2d19731..000000000000 --- a/tpgtools/overrides/clouddeploy/tpgtools_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -## product level overrides -- type: PRODUCT_BASE_PATH - details: - skip: true -- type: PRODUCT_DOCS_SECTION - details: - docssection: Cloud Deploy diff --git a/tpgtools/overrides/cloudresourcemanager/beta/folder.yaml b/tpgtools/overrides/cloudresourcemanager/beta/folder.yaml deleted file mode 100644 index 20b1ae9a1d57..000000000000 --- a/tpgtools/overrides/cloudresourcemanager/beta/folder.yaml +++ /dev/null @@ -1,5 +0,0 @@ -- type: SERIALIZATION_ONLY -- type: CUSTOM_TERRAFORM_PRODUCT_NAME - details: - # Produces the correct resource name: `google_folder` - product: "" diff --git a/tpgtools/overrides/cloudresourcemanager/beta/project.yaml b/tpgtools/overrides/cloudresourcemanager/beta/project.yaml deleted file mode 100644 index 623b0ffa8244..000000000000 --- a/tpgtools/overrides/cloudresourcemanager/beta/project.yaml +++ /dev/null @@ -1,8 +0,0 @@ -- type: SERIALIZATION_ONLY -- type: CUSTOM_SERIALIZER - details: - function: "serializeBetaProjectToHCL" -- type: CUSTOM_TERRAFORM_PRODUCT_NAME - details: - # Produces the correct resource name: `google_project` - product: "" diff --git a/tpgtools/overrides/cloudresourcemanager/beta/tpgtools_product.yaml b/tpgtools/overrides/cloudresourcemanager/beta/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/cloudresourcemanager/beta/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/cloudresourcemanager/folder.yaml b/tpgtools/overrides/cloudresourcemanager/folder.yaml deleted file mode 100644 index 20b1ae9a1d57..000000000000 --- a/tpgtools/overrides/cloudresourcemanager/folder.yaml +++ /dev/null @@ -1,5 +0,0 @@ -- type: SERIALIZATION_ONLY -- type: CUSTOM_TERRAFORM_PRODUCT_NAME - details: - # Produces the correct resource name: `google_folder` - product: "" diff --git a/tpgtools/overrides/cloudresourcemanager/project.yaml b/tpgtools/overrides/cloudresourcemanager/project.yaml deleted file mode 100644 index 24d9832b70df..000000000000 --- a/tpgtools/overrides/cloudresourcemanager/project.yaml +++ /dev/null @@ -1,8 +0,0 @@ -- type: SERIALIZATION_ONLY -- type: CUSTOM_SERIALIZER - details: - function: "serializeGAProjectToHCL" -- type: CUSTOM_TERRAFORM_PRODUCT_NAME - details: - # Produces the correct resource name: `google_project` - product: "" diff --git a/tpgtools/overrides/cloudresourcemanager/tpgtools_product.yaml b/tpgtools/overrides/cloudresourcemanager/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/cloudresourcemanager/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/containeraws/beta/cluster.yaml b/tpgtools/overrides/containeraws/beta/cluster.yaml deleted file mode 100644 index de673cb35999..000000000000 --- a/tpgtools/overrides/containeraws/beta/cluster.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# GKE MultiCloud uses a different set of locations than GCE, and our default -# sweeper logic assumes that resources are in us-central1. -- type: NO_SWEEPER -- type: EXCLUDE - field: monitoring_config -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: DIFF_SUPPRESS_FUNC - field: control_plane.root_volume.volume_type - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: control_plane.main_volume.volume_type - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: logging_config.component_config.enable_components - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: control_plane.instance_placement.tenancy - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress diff --git a/tpgtools/overrides/containeraws/beta/node_pool.yaml b/tpgtools/overrides/containeraws/beta/node_pool.yaml deleted file mode 100644 index 44be04460d93..000000000000 --- a/tpgtools/overrides/containeraws/beta/node_pool.yaml +++ /dev/null @@ -1,31 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject - - tpgdclresource.ResourceContainerAwsNodePoolCustomizeDiffFunc -- type: DIFF_SUPPRESS_FUNC - field: config.root_volume.volume_type - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: config.taints.effect - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: config.instance_placement.tenancy - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: CUSTOM_STATE_SETTER - field: management - details: - function: d.Set("management", tpgresource.FlattenContainerAwsNodePoolManagement(res.Management, d, config)) -- type: CUSTOM_SCHEMA_VALUES - field: management - details: - optional: true - computed: true -- type: CUSTOM_SCHEMA_VALUES - field: management.auto_repair - details: - optional: true - computed: true diff --git a/tpgtools/overrides/containeraws/beta/tpgtools_product.yaml b/tpgtools/overrides/containeraws/beta/tpgtools_product.yaml deleted file mode 100644 index 21c439217d43..000000000000 --- a/tpgtools/overrides/containeraws/beta/tpgtools_product.yaml +++ /dev/null @@ -1,5 +0,0 @@ -## product level overrides - -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/containeraws/cluster.yaml b/tpgtools/overrides/containeraws/cluster.yaml deleted file mode 100644 index b01af18dc187..000000000000 --- a/tpgtools/overrides/containeraws/cluster.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# GKE MultiCloud uses a different set of locations than GCE, and our default -# sweeper logic assumes that resources are in us-central1. -- type: NO_SWEEPER -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: DIFF_SUPPRESS_FUNC - field: control_plane.root_volume.volume_type - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: control_plane.main_volume.volume_type - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress diff --git a/tpgtools/overrides/containeraws/node_pool.yaml b/tpgtools/overrides/containeraws/node_pool.yaml deleted file mode 100644 index 4034f6c71c6e..000000000000 --- a/tpgtools/overrides/containeraws/node_pool.yaml +++ /dev/null @@ -1,26 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: DIFF_SUPPRESS_FUNC - field: config.root_volume.volume_type - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: DIFF_SUPPRESS_FUNC - field: config.taints.effect - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress -- type: CUSTOM_STATE_SETTER - field: management - details: - function: d.Set("management", tpgresource.FlattenContainerAwsNodePoolManagement(res.Management, d, config)) -- type: CUSTOM_SCHEMA_VALUES - field: management - details: - optional: true - computed: true -- type: CUSTOM_SCHEMA_VALUES - field: management.auto_repair - details: - optional: true - computed: true diff --git a/tpgtools/overrides/containeraws/samples/cluster/basic.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/basic.tf.tmpl deleted file mode 100644 index cba4d5fefbb9..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/basic.tf.tmpl +++ /dev/null @@ -1,87 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - admin_groups { - group = "group@domain.com" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/basic.yaml b/tpgtools/overrides/containeraws/samples/cluster/basic.yaml deleted file mode 100644 index e5e4d10edf13..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/basic.yaml +++ /dev/null @@ -1,32 +0,0 @@ -description: A basic example of a containeraws cluster -name: basic_aws_cluster -type: aws_cluster -updates: -- resource: ./basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/cluster/basic_enum.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/basic_enum.tf.tmpl deleted file mode 100644 index 592be53b542a..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/basic_enum.tf.tmpl +++ /dev/null @@ -1,84 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/basic_enum.yaml b/tpgtools/overrides/containeraws/samples/cluster/basic_enum.yaml deleted file mode 100644 index 1a9a62a8dc2e..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/basic_enum.yaml +++ /dev/null @@ -1,32 +0,0 @@ -description: A basic example of a containeraws cluster with lowercase enums -name: basic_enum_aws_cluster -type: aws_cluster -updates: -- resource: ./basic_enum_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/cluster/basic_enum_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/basic_enum_update.tf.tmpl deleted file mode 100644 index 955dad66594c..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/basic_enum_update.tf.tmpl +++ /dev/null @@ -1,84 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-two = "value-two" - } - - description = "An updated sample aws cluster" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/basic_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/basic_update.tf.tmpl deleted file mode 100644 index 5273978a0121..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/basic_update.tf.tmpl +++ /dev/null @@ -1,87 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - admin_groups { - group = "group@domain.com" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-two = "value-two" - } - - description = "An updated sample aws cluster" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/beta_basic.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/beta_basic.tf.tmpl deleted file mode 100644 index ff03a07d315d..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/beta_basic.tf.tmpl +++ /dev/null @@ -1,97 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - - instance_placement { - tenancy = "DEDICATED" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["SYSTEM_COMPONENTS", "WORKLOADS"] - } - } - -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/beta_basic.yaml b/tpgtools/overrides/containeraws/samples/cluster/beta_basic.yaml deleted file mode 100644 index f0230b287764..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/beta_basic.yaml +++ /dev/null @@ -1,34 +0,0 @@ -description: A basic example of a containeraws cluster (beta) -name: beta_basic_aws_cluster -type: aws_cluster -versions: -- beta -updates: -- resource: ./beta_basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum.tf.tmpl deleted file mode 100644 index 50357cba9e04..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum.tf.tmpl +++ /dev/null @@ -1,96 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - - instance_placement { - tenancy = "dedicated" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["system_components", "workloads"] - } - } - -} diff --git a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum.yaml b/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum.yaml deleted file mode 100644 index eada3494ba75..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum.yaml +++ /dev/null @@ -1,34 +0,0 @@ -description: A basic example of a containeraws cluster with lowercase enums (beta) -name: beta_basic_enum_aws_cluster -type: aws_cluster -versions: -- beta -updates: -- resource: ./beta_basic_enum_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum_update.tf.tmpl deleted file mode 100644 index 73b33d002742..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_enum_update.tf.tmpl +++ /dev/null @@ -1,101 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - binary_authorization { - evaluation_mode = "PROJECT_SINGLETON_POLICY_ENFORCE" - } - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "updated-{{test_service_account}}" - } - - instance_placement { - tenancy = "dedicated" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-two = "value-two" - } - - description = "An updated sample aws cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["system_components", "workloads"] - } - } - -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/cluster/beta_basic_update.tf.tmpl deleted file mode 100644 index 68c78ca6ea15..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/beta_basic_update.tf.tmpl +++ /dev/null @@ -1,97 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "updated-{{test_service_account}}" - } - - instance_placement { - tenancy = "DEDICATED" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-two = "value-two" - } - - description = "An updated sample aws cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["SYSTEM_COMPONENTS", "WORKLOADS"] - } - } - -} - diff --git a/tpgtools/overrides/containeraws/samples/cluster/meta.yaml b/tpgtools/overrides/containeraws/samples/cluster/meta.yaml deleted file mode 100644 index 1f3464c256a4..000000000000 --- a/tpgtools/overrides/containeraws/samples/cluster/meta.yaml +++ /dev/null @@ -1,4 +0,0 @@ -ignore_read: - - fleet.0.project -doc_hide: - - beta_basic.tf.tmpl diff --git a/tpgtools/overrides/containeraws/samples/nodepool/basic.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/basic.tf.tmpl deleted file mode 100644 index 78e01cf015f8..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/basic.tf.tmpl +++ /dev/null @@ -1,161 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - - -resource "google_container_aws_node_pool" "primary" { - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.medium" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "PREFER_NO_SCHEDULE" - key = "taint-key" - value = "taint-value" - } - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - annotations = { - label-one = "value-one" - } - - management { - auto_repair = true - } - - kubelet_config { - cpu_manager_policy = "none" - cpu_cfs_quota = true - cpu_cfs_quota_period = "100ms" - pod_pids_limit = 1024 - } - - project = "{{project}}" -} diff --git a/tpgtools/overrides/containeraws/samples/nodepool/basic.yaml b/tpgtools/overrides/containeraws/samples/nodepool/basic.yaml deleted file mode 100644 index 1a4f78ca5f87..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/basic.yaml +++ /dev/null @@ -1,34 +0,0 @@ -description: A basic example of a containeraws node pool -name: basic_aws_cluster -type: aws_cluster -updates: -- resource: ./basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: node-pool-name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/nodepool/basic_enum.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/basic_enum.tf.tmpl deleted file mode 100644 index 9583c10d0276..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/basic_enum.tf.tmpl +++ /dev/null @@ -1,151 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - - -resource "google_container_aws_node_pool" "primary" { - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.medium" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "prefer_no_schedule" - key = "taint-key" - value = "taint-value" - } - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - annotations = { - label-one = "value-one" - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/nodepool/basic_enum.yaml b/tpgtools/overrides/containeraws/samples/nodepool/basic_enum.yaml deleted file mode 100644 index ecc96bd18420..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/basic_enum.yaml +++ /dev/null @@ -1,34 +0,0 @@ -description: A basic example of a containeraws node pool with lowercase enums -name: basic_enum_aws_cluster -type: aws_cluster -updates: -- resource: ./basic_enum_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: node-pool-name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/nodepool/basic_enum_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/basic_enum_update.tf.tmpl deleted file mode 100644 index 0c40c150ee25..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/basic_enum_update.tf.tmpl +++ /dev/null @@ -1,150 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - -resource "google_container_aws_node_pool" "primary" { - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.large" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "prefer_no_schedule" - key = "taint-key" - value = "taint-value" - } - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - annotations = { - label-two = "value-two" - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/nodepool/basic_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/basic_update.tf.tmpl deleted file mode 100644 index 22e471d3b8fa..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/basic_update.tf.tmpl +++ /dev/null @@ -1,160 +0,0 @@ -data "google_container_aws_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - -resource "google_container_aws_node_pool" "primary" { - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.large" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "PREFER_NO_SCHEDULE" - key = "taint-key" - value = "taint-value" - } - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - annotations = { - label-two = "value-two" - } - - management { - auto_repair = false - } - - kubelet_config { - cpu_manager_policy = "none" - cpu_cfs_quota = true - cpu_cfs_quota_period = "100ms" - pod_pids_limit = 1024 - } - - project = "{{project}}" -} diff --git a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/beta_basic.tf.tmpl deleted file mode 100644 index e26129139e17..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic.tf.tmpl +++ /dev/null @@ -1,177 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - - -resource "google_container_aws_node_pool" "primary" { - provider = google-beta - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.medium" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "PREFER_NO_SCHEDULE" - key = "taint-key" - value = "taint-value" - } - - instance_placement { - tenancy = "DEDICATED" - } - - image_type = "ubuntu" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - management { - auto_repair = true - } - - kubelet_config { - cpu_manager_policy = "none" - cpu_cfs_quota = true - cpu_cfs_quota_period = "100ms" - pod_pids_limit = 1024 - } - - annotations = { - label-one = "value-one" - } - - update_settings { - surge_settings { - max_surge = 1 - max_unavailable = 0 - } - } - - project = "{{project}}" -} diff --git a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic.yaml b/tpgtools/overrides/containeraws/samples/nodepool/beta_basic.yaml deleted file mode 100644 index 38641d68d0aa..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic.yaml +++ /dev/null @@ -1,36 +0,0 @@ -description: A basic example of a containeraws node pool (beta) -name: beta_basic_aws_cluster -type: aws_cluster -versions: -- beta -updates: -- resource: ./beta_basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: node-pool-name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum.tf.tmpl deleted file mode 100644 index cf5b6655457c..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum.tf.tmpl +++ /dev/null @@ -1,160 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - - -resource "google_container_aws_node_pool" "primary" { - provider = google-beta - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.medium" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "prefer_no_schedule" - key = "taint-key" - value = "taint-value" - } - - instance_placement { - tenancy = "dedicated" - } - - image_type = "ubuntu" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - annotations = { - label-one = "value-one" - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum.yaml b/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum.yaml deleted file mode 100644 index 52dad59d35ce..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum.yaml +++ /dev/null @@ -1,36 +0,0 @@ -description: A basic example of a containeraws node pool with lowercase enums (beta) -name: beta_basic_enum_aws_cluster -type: aws_cluster -versions: -- beta -updates: -- resource: ./beta_basic_enum_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: name - type: resource_name -- name: node-pool-name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: aws_account_id - type: aws_account_id -- name: aws_volume_encryption_key - type: aws_volume_encryption_key -- name: aws_vpc - type: aws_vpc -- name: aws_database_encryption_key - type: aws_database_encryption_key -- name: aws_security_group - type: aws_security_group -- name: aws_subnet - type: aws_subnet -- name: aws_security_group - type: aws_security_group -- name: aws_region - type: aws_region -- name: test_service_account - type: test_service_account diff --git a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum_update.tf.tmpl deleted file mode 100644 index a9fd2bf44df8..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_enum_update.tf.tmpl +++ /dev/null @@ -1,159 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - -resource "google_container_aws_node_pool" "primary" { - provider = google-beta - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.large" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "gp3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "prefer_no_schedule" - key = "taint-key" - value = "taint-value" - } - - instance_placement { - tenancy = "dedicated" - } - - image_type = "ubuntu" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - annotations = { - label-two = "value-two" - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_update.tf.tmpl b/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_update.tf.tmpl deleted file mode 100644 index 078c7a93e29a..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/beta_basic_update.tf.tmpl +++ /dev/null @@ -1,176 +0,0 @@ -data "google_container_aws_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_aws_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "{{test_service_account}}" - } - } - - aws_region = "{{aws_region}}" - - control_plane { - aws_services_authentication { - role_arn = "arn:aws:iam::{{aws_account_id}}:role/{{byo_multicloud_prefix}}-1p-dev-oneplatform" - role_session_name = "{{byo_multicloud_prefix}}-1p-dev-session" - } - - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - database_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-controlplane" - subnet_ids = ["{{aws_subnet}}"] - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - instance_type = "t3.medium" - - main_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - owner = "{{test_service_account}}" - } - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.2.0.0/16"] - service_address_cidr_blocks = ["10.1.0.0/16"] - vpc_id = "{{aws_vpc}}" - } - - annotations = { - label-one = "value-one" - } - - description = "A sample aws cluster" - project = "{{project}}" -} - -resource "google_container_aws_node_pool" "primary" { - provider = google-beta - autoscaling { - max_node_count = 5 - min_node_count = 1 - } - - cluster = google_container_aws_cluster.primary.name - - config { - config_encryption { - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_database_encryption_key}}" - } - - iam_instance_profile = "{{byo_multicloud_prefix}}-1p-dev-nodepool" - instance_type = "t3.large" - - labels = { - label-one = "value-one" - } - - root_volume { - iops = 3000 - kms_key_arn = "arn:aws:kms:{{aws_region}}:{{aws_account_id}}:key/{{aws_volume_encryption_key}}" - size_gib = 10 - volume_type = "GP3" - } - - security_group_ids = ["{{aws_security_group}}"] - - proxy_config { - secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" - secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" - } - - ssh_config { - ec2_key_pair = "{{byo_multicloud_prefix}}-1p-dev-ssh" - } - - tags = { - tag-one = "value-one" - } - - taints { - effect = "PREFER_NO_SCHEDULE" - key = "taint-key" - value = "taint-value" - } - - instance_placement { - tenancy = "DEDICATED" - } - - image_type = "ubuntu" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "{{aws_subnet}}" - version = "${data.google_container_aws_versions.versions.valid_versions[0]}" - - management { - auto_repair = false - } - - kubelet_config { - cpu_manager_policy = "none" - cpu_cfs_quota = true - cpu_cfs_quota_period = "100ms" - pod_pids_limit = 1024 - } - - annotations = { - label-two = "value-two" - } - - update_settings { - surge_settings { - max_surge = 1 - max_unavailable = 0 - } - } - - project = "{{project}}" -} diff --git a/tpgtools/overrides/containeraws/samples/nodepool/meta.yaml b/tpgtools/overrides/containeraws/samples/nodepool/meta.yaml deleted file mode 100644 index b14ec31e9af2..000000000000 --- a/tpgtools/overrides/containeraws/samples/nodepool/meta.yaml +++ /dev/null @@ -1,7 +0,0 @@ -ignore_read: - - fleet.0.project - - management.# - - management.0.% - - management.0.auto_repair -doc_hide: - - beta_basic.tf.tmpl diff --git a/tpgtools/overrides/containeraws/tpgtools_product.yaml b/tpgtools/overrides/containeraws/tpgtools_product.yaml deleted file mode 100644 index 21c439217d43..000000000000 --- a/tpgtools/overrides/containeraws/tpgtools_product.yaml +++ /dev/null @@ -1,5 +0,0 @@ -## product level overrides - -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/containerazure/azure_client.yaml b/tpgtools/overrides/containerazure/azure_client.yaml deleted file mode 100644 index a3c82651a742..000000000000 --- a/tpgtools/overrides/containerazure/azure_client.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# GKE MultiCloud uses a different set of locations than GCE, and our default -# sweeper logic assumes that resources are in us-central1. -- type: NO_SWEEPER -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/containerazure/beta/azure_client.yaml b/tpgtools/overrides/containerazure/beta/azure_client.yaml deleted file mode 100644 index a3c82651a742..000000000000 --- a/tpgtools/overrides/containerazure/beta/azure_client.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# GKE MultiCloud uses a different set of locations than GCE, and our default -# sweeper logic assumes that resources are in us-central1. -- type: NO_SWEEPER -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/containerazure/beta/cluster.yaml b/tpgtools/overrides/containerazure/beta/cluster.yaml deleted file mode 100644 index bf96bc008f4b..000000000000 --- a/tpgtools/overrides/containerazure/beta/cluster.yaml +++ /dev/null @@ -1,13 +0,0 @@ -# GKE MultiCloud uses a different set of locations than GCE, and our default -# sweeper logic assumes that resources are in us-central1. -- type: NO_SWEEPER -- type: EXCLUDE - field: monitoring_config -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: DIFF_SUPPRESS_FUNC - field: logging_config.component_config.enable_components - details: - diffsuppressfunc: tpgresource.CaseDiffSuppress diff --git a/tpgtools/overrides/containerazure/beta/node_pool.yaml b/tpgtools/overrides/containerazure/beta/node_pool.yaml deleted file mode 100644 index 7455aaf975dc..000000000000 --- a/tpgtools/overrides/containerazure/beta/node_pool.yaml +++ /dev/null @@ -1,18 +0,0 @@ -- type: CUSTOM_STATE_SETTER - field: management - details: - function: d.Set("management", tpgresource.FlattenContainerAzureNodePoolManagement(res.Management, d, config)) -- type: CUSTOM_SCHEMA_VALUES - field: management - details: - optional: true - computed: true -- type: CUSTOM_SCHEMA_VALUES - field: management.auto_repair - details: - optional: true - computed: true -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/containerazure/beta/tpgtools_product.yaml b/tpgtools/overrides/containerazure/beta/tpgtools_product.yaml deleted file mode 100644 index 21c439217d43..000000000000 --- a/tpgtools/overrides/containerazure/beta/tpgtools_product.yaml +++ /dev/null @@ -1,5 +0,0 @@ -## product level overrides - -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/containerazure/cluster.yaml b/tpgtools/overrides/containerazure/cluster.yaml deleted file mode 100644 index a3c82651a742..000000000000 --- a/tpgtools/overrides/containerazure/cluster.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# GKE MultiCloud uses a different set of locations than GCE, and our default -# sweeper logic assumes that resources are in us-central1. -- type: NO_SWEEPER -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/containerazure/node_pool.yaml b/tpgtools/overrides/containerazure/node_pool.yaml deleted file mode 100644 index 7455aaf975dc..000000000000 --- a/tpgtools/overrides/containerazure/node_pool.yaml +++ /dev/null @@ -1,18 +0,0 @@ -- type: CUSTOM_STATE_SETTER - field: management - details: - function: d.Set("management", tpgresource.FlattenContainerAzureNodePoolManagement(res.Management, d, config)) -- type: CUSTOM_SCHEMA_VALUES - field: management - details: - optional: true - computed: true -- type: CUSTOM_SCHEMA_VALUES - field: management.auto_repair - details: - optional: true - computed: true -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/containerazure/samples/client/basic.tf.tmpl b/tpgtools/overrides/containerazure/samples/client/basic.tf.tmpl deleted file mode 100644 index 4e009497410e..000000000000 --- a/tpgtools/overrides/containerazure/samples/client/basic.tf.tmpl +++ /dev/null @@ -1,7 +0,0 @@ -resource "google_container_azure_client" "primary" { - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} diff --git a/tpgtools/overrides/containerazure/samples/client/basic.yaml b/tpgtools/overrides/containerazure/samples/client/basic.yaml deleted file mode 100644 index a68565b78fbd..000000000000 --- a/tpgtools/overrides/containerazure/samples/client/basic.yaml +++ /dev/null @@ -1,12 +0,0 @@ -description: A basic example of a containerazure azure client -name: basic_azure_client -type: client -variables: -- name: client-name - type: resource_name -- name: project - type: project -- name: azure_app - type: azure_application -- name: azure_tenant - type: azure_ad_tenant diff --git a/tpgtools/overrides/containerazure/samples/client/meta.yaml b/tpgtools/overrides/containerazure/samples/client/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/containerazure/samples/cluster/basic.tf.tmpl b/tpgtools/overrides/containerazure/samples/cluster/basic.tf.tmpl deleted file mode 100644 index 712364a3b4b1..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/basic.tf.tmpl +++ /dev/null @@ -1,52 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_azure_cluster" "primary" { - authorization { - admin_users { - username = "mmv2@google.com" - } - admin_groups { - group = "group@domain.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" -} - -resource "google_container_azure_client" "basic" { - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/cluster/basic.yaml b/tpgtools/overrides/containerazure/samples/cluster/basic.yaml deleted file mode 100644 index 7b543e4f97a0..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/basic.yaml +++ /dev/null @@ -1,24 +0,0 @@ -description: A basic example of a containerazure azure cluster -name: basic_azure_cluster -type: azure_cluster -updates: -- resource: ./basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: azure_subscription - type: azure_subscription -- name: client-name - type: resource_name -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: azure_app - type: azure_application -- name: azure_tenant - type: azure_ad_tenant -- name: azure_config_secret - type: azure_proxy_config_secret_version diff --git a/tpgtools/overrides/containerazure/samples/cluster/basic_update.tf.tmpl b/tpgtools/overrides/containerazure/samples/cluster/basic_update.tf.tmpl deleted file mode 100644 index a010a7fa4126..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/basic_update.tf.tmpl +++ /dev/null @@ -1,87 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_azure_cluster" "primary" { - authorization { - admin_users { - username = "mmv2@google.com" - } - admin_groups { - group = "group@domain.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - database_encryption { - key_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster/providers/Microsoft.KeyVault/vaults/{{byo_multicloud_prefix}}-dev-keyvault/keys/{{byo_multicloud_prefix}}-dev-key" - } - - main_volume { - size_gib = 8 - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - replica_placements { - azure_availability_zone = "1" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - vm_size = "Standard_DS2_v2" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - - annotations = { - annotation-one = "value-one" - } - - description = "An updated sample azure cluster" - project = "{{project}}" -} - -resource "google_container_azure_client" "basic" { - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - - diff --git a/tpgtools/overrides/containerazure/samples/cluster/beta_basic.tf.tmpl b/tpgtools/overrides/containerazure/samples/cluster/beta_basic.tf.tmpl deleted file mode 100644 index 9b9b1293ca30..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/beta_basic.tf.tmpl +++ /dev/null @@ -1,59 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" - provider = google-beta -} - -resource "google_container_azure_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["SYSTEM_COMPONENTS", "WORKLOADS"] - } - } - -} - -resource "google_container_azure_client" "basic" { - provider = google-beta - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/cluster/beta_basic.yaml b/tpgtools/overrides/containerazure/samples/cluster/beta_basic.yaml deleted file mode 100644 index 79d8b7a25c0a..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/beta_basic.yaml +++ /dev/null @@ -1,26 +0,0 @@ -description: A basic example of a containerazure azure cluster (beta) -name: beta_basic_azure_cluster -type: azure_cluster -versions: -- beta -updates: -- resource: ./beta_basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: azure_subscription - type: azure_subscription -- name: client-name - type: resource_name -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: azure_app - type: azure_application -- name: azure_tenant - type: azure_ad_tenant -- name: azure_config_secret - type: azure_proxy_config_secret_version diff --git a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum.tf.tmpl b/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum.tf.tmpl deleted file mode 100644 index 3598f5a131c5..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum.tf.tmpl +++ /dev/null @@ -1,59 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" - provider = google-beta -} - -resource "google_container_azure_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["system_components", "workloads"] - } - } - -} - -resource "google_container_azure_client" "basic" { - provider = google-beta - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum.yaml b/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum.yaml deleted file mode 100644 index 2bf4e8ddaf9c..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum.yaml +++ /dev/null @@ -1,26 +0,0 @@ -description: A basic example of a containerazure azure cluster with lowercase enums (beta) -name: beta_basic_enum_azure_cluster -type: azure_cluster -versions: -- beta -updates: -- resource: ./beta_basic_enum_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: azure_subscription - type: azure_subscription -- name: client-name - type: resource_name -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: azure_app - type: azure_application -- name: azure_tenant - type: azure_ad_tenant -- name: azure_config_secret - type: azure_proxy_config_secret_version diff --git a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum_update.tf.tmpl b/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum_update.tf.tmpl deleted file mode 100644 index 7d7ee5fa36fb..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_enum_update.tf.tmpl +++ /dev/null @@ -1,94 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" - provider = google-beta -} - -resource "google_container_azure_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - database_encryption { - key_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster/providers/Microsoft.KeyVault/vaults/{{byo_multicloud_prefix}}-dev-keyvault/keys/{{byo_multicloud_prefix}}-dev-key" - } - - main_volume { - size_gib = 8 - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - replica_placements { - azure_availability_zone = "1" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - vm_size = "Standard_DS2_v2" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - - annotations = { - annotation-one = "value-one" - } - - description = "An updated sample azure cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["system_components", "workloads"] - } - } - -} - -resource "google_container_azure_client" "basic" { - provider = google-beta - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - - diff --git a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_update.tf.tmpl b/tpgtools/overrides/containerazure/samples/cluster/beta_basic_update.tf.tmpl deleted file mode 100644 index 93873553b731..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/beta_basic_update.tf.tmpl +++ /dev/null @@ -1,94 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" - provider = google-beta -} - -resource "google_container_azure_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - database_encryption { - key_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster/providers/Microsoft.KeyVault/vaults/{{byo_multicloud_prefix}}-dev-keyvault/keys/{{byo_multicloud_prefix}}-dev-key" - } - - main_volume { - size_gib = 8 - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - replica_placements { - azure_availability_zone = "1" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - vm_size = "Standard_DS2_v2" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - - annotations = { - annotation-one = "value-one" - } - - description = "An updated sample azure cluster" - project = "{{project}}" - - logging_config { - component_config { - enable_components = ["SYSTEM_COMPONENTS", "WORKLOADS"] - } - } - -} - -resource "google_container_azure_client" "basic" { - provider = google-beta - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - - diff --git a/tpgtools/overrides/containerazure/samples/cluster/meta.yaml b/tpgtools/overrides/containerazure/samples/cluster/meta.yaml deleted file mode 100644 index 1f3464c256a4..000000000000 --- a/tpgtools/overrides/containerazure/samples/cluster/meta.yaml +++ /dev/null @@ -1,4 +0,0 @@ -ignore_read: - - fleet.0.project -doc_hide: - - beta_basic.tf.tmpl diff --git a/tpgtools/overrides/containerazure/samples/nodepool/basic.tf.tmpl b/tpgtools/overrides/containerazure/samples/nodepool/basic.tf.tmpl deleted file mode 100644 index 90b33a363a31..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/basic.tf.tmpl +++ /dev/null @@ -1,103 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - -resource "google_container_azure_cluster" "primary" { - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" -} - -resource "google_container_azure_client" "basic" { - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - -resource "google_container_azure_node_pool" "primary" { - autoscaling { - max_node_count = 3 - min_node_count = 2 - } - - cluster = google_container_azure_cluster.primary.name - - config { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - labels = { - key_one = "label_one" - } - - vm_size = "Standard_DS2_v2" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - annotations = { - annotation-one = "value-one" - } - - management { - auto_repair = true - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/nodepool/basic.yaml b/tpgtools/overrides/containerazure/samples/nodepool/basic.yaml deleted file mode 100644 index fabaa90c0ded..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/basic.yaml +++ /dev/null @@ -1,26 +0,0 @@ -description: A basic example of a containerazure azure node pool -name: basic_azure_node_pool -type: azure_node_pool -updates: -- resource: ./basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: azure_subscription - type: azure_subscription -- name: node-pool-name - type: resource_name -- name: client-name - type: resource_name -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: azure_app - type: azure_application -- name: azure_tenant - type: azure_ad_tenant -- name: azure_config_secret - type: azure_proxy_config_secret_version diff --git a/tpgtools/overrides/containerazure/samples/nodepool/basic_update.tf.tmpl b/tpgtools/overrides/containerazure/samples/nodepool/basic_update.tf.tmpl deleted file mode 100644 index 267a053c5b45..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/basic_update.tf.tmpl +++ /dev/null @@ -1,104 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" -} - - -resource "google_container_azure_cluster" "primary" { - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" -} - -resource "google_container_azure_client" "basic" { - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - -resource "google_container_azure_node_pool" "primary" { - autoscaling { - max_node_count = 3 - min_node_count = 2 - } - - cluster = google_container_azure_cluster.primary.name - - config { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - labels = { - key_two = "label_two" - } - - vm_size = "Standard_DS2_v2" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - annotations = { - annotation-two = "value-two" - } - - management { - auto_repair = false - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/nodepool/beta_basic.tf.tmpl b/tpgtools/overrides/containerazure/samples/nodepool/beta_basic.tf.tmpl deleted file mode 100644 index 8dc605998b2c..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/beta_basic.tf.tmpl +++ /dev/null @@ -1,109 +0,0 @@ -data "google_container_azure_versions" "versions" { - project = "{{project}}" - location = "us-west1" - provider = google-beta -} - -resource "google_container_azure_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" -} - -resource "google_container_azure_client" "basic" { - provider = google-beta - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - -resource "google_container_azure_node_pool" "primary" { - provider = google-beta - autoscaling { - max_node_count = 3 - min_node_count = 2 - } - - cluster = google_container_azure_cluster.primary.name - - config { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - labels = { - key_one = "label_one" - } - - vm_size = "Standard_DS2_v2" - - image_type = "ubuntu" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - management { - auto_repair = true - } - - annotations = { - annotation-one = "value-one" - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/nodepool/beta_basic.yaml b/tpgtools/overrides/containerazure/samples/nodepool/beta_basic.yaml deleted file mode 100644 index e51c12993369..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/beta_basic.yaml +++ /dev/null @@ -1,28 +0,0 @@ -description: A basic example of a containerazure azure node pool (beta) -name: beta_basic_azure_node_pool -type: azure_node_pool -versions: -- beta -updates: -- resource: ./beta_basic_update.tf.tmpl -variables: -- name: byo_multicloud_prefix - type: byo_multicloud_prefix -- name: azure_subscription - type: azure_subscription -- name: node-pool-name - type: resource_name -- name: client-name - type: resource_name -- name: name - type: resource_name -- name: project - type: project -- name: project_number - type: project_number -- name: azure_app - type: azure_application -- name: azure_tenant - type: azure_ad_tenant -- name: azure_config_secret - type: azure_proxy_config_secret_version diff --git a/tpgtools/overrides/containerazure/samples/nodepool/beta_basic_update.tf.tmpl b/tpgtools/overrides/containerazure/samples/nodepool/beta_basic_update.tf.tmpl deleted file mode 100644 index bce21faa8001..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/beta_basic_update.tf.tmpl +++ /dev/null @@ -1,110 +0,0 @@ -data "google_container_azure_versions" "versions" { - provider = google-beta - project = "{{project}}" - location = "us-west1" -} - - -resource "google_container_azure_cluster" "primary" { - provider = google-beta - authorization { - admin_users { - username = "mmv2@google.com" - } - } - - azure_region = "westus2" - client = "projects/{{project_number}}/locations/us-west1/azureClients/${google_container_azure_client.basic.name}" - - control_plane { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - } - - fleet { - project = "{{project_number}}" - } - - location = "us-west1" - name = "{{name}}" - - networking { - pod_address_cidr_blocks = ["10.200.0.0/16"] - service_address_cidr_blocks = ["10.32.0.0/24"] - virtual_network_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet" - } - - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - project = "{{project}}" -} - -resource "google_container_azure_client" "basic" { - provider = google-beta - application_id = "{{azure_app}}" - location = "us-west1" - name = "{{client-name}}" - tenant_id = "{{azure_tenant}}" - project = "{{project}}" -} - -resource "google_container_azure_node_pool" "primary" { - provider = google-beta - autoscaling { - max_node_count = 3 - min_node_count = 2 - } - - cluster = google_container_azure_cluster.primary.name - - config { - ssh_config { - authorized_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers" - } - - proxy_config { - resource_group_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-cluster" - secret_id = "https://{{byo_multicloud_prefix}}-dev-keyvault.vault.azure.net/secrets/{{byo_multicloud_prefix}}-dev-secret/{{azure_config_secret}}" - } - - root_volume { - size_gib = 32 - } - - tags = { - owner = "mmv2" - } - - labels = { - key_two = "label_two" - } - - vm_size = "Standard_DS2_v2" - - image_type = "ubuntu" - } - - location = "us-west1" - - max_pods_constraint { - max_pods_per_node = 110 - } - - name = "{{node-pool-name}}" - subnet_id = "/subscriptions/{{azure_subscription}}/resourceGroups/{{byo_multicloud_prefix}}-dev-byo/providers/Microsoft.Network/virtualNetworks/{{byo_multicloud_prefix}}-dev-vnet/subnets/default" - version = "${data.google_container_azure_versions.versions.valid_versions[0]}" - - management { - auto_repair = false - } - - annotations = { - annotation-two = "value-two" - } - - project = "{{project}}" -} - diff --git a/tpgtools/overrides/containerazure/samples/nodepool/meta.yaml b/tpgtools/overrides/containerazure/samples/nodepool/meta.yaml deleted file mode 100644 index 09bdf3c9ce82..000000000000 --- a/tpgtools/overrides/containerazure/samples/nodepool/meta.yaml +++ /dev/null @@ -1,6 +0,0 @@ -ignore_read: - - management.# - - management.0.% - - management.0.auto_repair -doc_hide: - - beta_basic.tf.tmpl \ No newline at end of file diff --git a/tpgtools/overrides/containerazure/tpgtools_product.yaml b/tpgtools/overrides/containerazure/tpgtools_product.yaml deleted file mode 100644 index 21c439217d43..000000000000 --- a/tpgtools/overrides/containerazure/tpgtools_product.yaml +++ /dev/null @@ -1,5 +0,0 @@ -## product level overrides - -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/dataplex/asset.yaml b/tpgtools/overrides/dataplex/asset.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/dataplex/asset.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/dataplex/beta/asset.yaml b/tpgtools/overrides/dataplex/beta/asset.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/dataplex/beta/asset.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/dataplex/beta/lake.yaml b/tpgtools/overrides/dataplex/beta/lake.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/dataplex/beta/lake.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/dataplex/beta/tpgtools_product.yaml b/tpgtools/overrides/dataplex/beta/tpgtools_product.yaml deleted file mode 100644 index 75271c791a0c..000000000000 --- a/tpgtools/overrides/dataplex/beta/tpgtools_product.yaml +++ /dev/null @@ -1,6 +0,0 @@ -## product level overrides - -- type: PRODUCT_BASE_PATH - details: - skip: true - diff --git a/tpgtools/overrides/dataplex/beta/zone.yaml b/tpgtools/overrides/dataplex/beta/zone.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/dataplex/beta/zone.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/dataplex/lake.yaml b/tpgtools/overrides/dataplex/lake.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/dataplex/lake.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/dataplex/samples/asset/basic_asset.tf.tmpl b/tpgtools/overrides/dataplex/samples/asset/basic_asset.tf.tmpl deleted file mode 100644 index d3f18d1990dd..000000000000 --- a/tpgtools/overrides/dataplex/samples/asset/basic_asset.tf.tmpl +++ /dev/null @@ -1,66 +0,0 @@ -resource "google_storage_bucket" "basic_bucket" { - name = "{{bucket}}" - location = "{{region}}" - uniform_bucket_level_access = true - lifecycle { - ignore_changes = [ - labels - ] - } - - project = "{{project}}" -} - -resource "google_dataplex_lake" "basic_lake" { - name = "{{lake}}" - location = "{{region}}" - project = "{{project}}" -} - - -resource "google_dataplex_zone" "basic_zone" { - name = "{{zone}}" - location = "{{region}}" - lake = google_dataplex_lake.basic_lake.name - type = "RAW" - - discovery_spec { - enabled = false - } - - - resource_spec { - location_type = "SINGLE_REGION" - } - - project = "{{project}}" -} - - -resource "google_dataplex_asset" "primary" { - name = "{{asset}}" - location = "{{region}}" - - lake = google_dataplex_lake.basic_lake.name - dataplex_zone = google_dataplex_zone.basic_zone.name - - discovery_spec { - enabled = false - } - - resource_spec { - name = "projects/{{project}}/buckets/{{bucket}}" - type = "STORAGE_BUCKET" - } - - labels = { - env = "foo" - my-asset = "exists" - } - - - project = "{{project}}" - depends_on = [ - google_storage_bucket.basic_bucket - ] -} \ No newline at end of file diff --git a/tpgtools/overrides/dataplex/samples/asset/basic_asset.yaml b/tpgtools/overrides/dataplex/samples/asset/basic_asset.yaml deleted file mode 100644 index f9b228d710cb..000000000000 --- a/tpgtools/overrides/dataplex/samples/asset/basic_asset.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# optional test level config -- needed for updates basic.tf.tmpl def -updates: -- resource: ./basic_asset.tf.tmpl -variables: -- name: lake - type: resource_name -- name: zone - type: resource_name -- name: asset - type: resource_name -- name: bucket - type: resource_name -- name: project - type: project -- name: region - type: region diff --git a/tpgtools/overrides/dataplex/samples/asset/meta.yaml b/tpgtools/overrides/dataplex/samples/asset/meta.yaml deleted file mode 100644 index c6039103f498..000000000000 --- a/tpgtools/overrides/dataplex/samples/asset/meta.yaml +++ /dev/null @@ -1,2 +0,0 @@ -ignore_read: -- "resource_spec.0.name" \ No newline at end of file diff --git a/tpgtools/overrides/dataplex/samples/lake/meta.yaml b/tpgtools/overrides/dataplex/samples/lake/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/dataplex/samples/zone/meta.yaml b/tpgtools/overrides/dataplex/samples/zone/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/dataplex/tpgtools_product.yaml b/tpgtools/overrides/dataplex/tpgtools_product.yaml deleted file mode 100644 index 75271c791a0c..000000000000 --- a/tpgtools/overrides/dataplex/tpgtools_product.yaml +++ /dev/null @@ -1,6 +0,0 @@ -## product level overrides - -- type: PRODUCT_BASE_PATH - details: - skip: true - diff --git a/tpgtools/overrides/dataplex/zone.yaml b/tpgtools/overrides/dataplex/zone.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/dataplex/zone.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/dataproc/beta/tpgtools_product.yaml b/tpgtools/overrides/dataproc/beta/tpgtools_product.yaml deleted file mode 100644 index 882f1479be56..000000000000 --- a/tpgtools/overrides/dataproc/beta/tpgtools_product.yaml +++ /dev/null @@ -1,6 +0,0 @@ -## product level overrides - -## Skip base path generation... already generated by magic modules -- type: PRODUCT_BASE_PATH - details: - skip: true \ No newline at end of file diff --git a/tpgtools/overrides/dataproc/beta/workflow_template.yaml b/tpgtools/overrides/dataproc/beta/workflow_template.yaml deleted file mode 100644 index d12af4d1d2f7..000000000000 --- a/tpgtools/overrides/dataproc/beta/workflow_template.yaml +++ /dev/null @@ -1,18 +0,0 @@ -- type: CUSTOM_SCHEMA_VALUES - field: version - details: - required: false - optional: true - computed: true -- type: DEPRECATED - field: version - details: - message: >- - version is not useful as a configurable field, and will be removed in the future. -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: STATE_UPGRADE - details: - schemaversion: 1 \ No newline at end of file diff --git a/tpgtools/overrides/dataproc/tpgtools_product.yaml b/tpgtools/overrides/dataproc/tpgtools_product.yaml deleted file mode 100644 index 882f1479be56..000000000000 --- a/tpgtools/overrides/dataproc/tpgtools_product.yaml +++ /dev/null @@ -1,6 +0,0 @@ -## product level overrides - -## Skip base path generation... already generated by magic modules -- type: PRODUCT_BASE_PATH - details: - skip: true \ No newline at end of file diff --git a/tpgtools/overrides/dataproc/workflow_template.yaml b/tpgtools/overrides/dataproc/workflow_template.yaml deleted file mode 100644 index d12af4d1d2f7..000000000000 --- a/tpgtools/overrides/dataproc/workflow_template.yaml +++ /dev/null @@ -1,18 +0,0 @@ -- type: CUSTOM_SCHEMA_VALUES - field: version - details: - required: false - optional: true - computed: true -- type: DEPRECATED - field: version - details: - message: >- - version is not useful as a configurable field, and will be removed in the future. -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: STATE_UPGRADE - details: - schemaversion: 1 \ No newline at end of file diff --git a/tpgtools/overrides/firebaserules/beta/release.yaml b/tpgtools/overrides/firebaserules/beta/release.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/firebaserules/beta/release.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/firebaserules/beta/ruleset.yaml b/tpgtools/overrides/firebaserules/beta/ruleset.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/firebaserules/beta/ruleset.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/firebaserules/beta/tpgtools_product.yaml b/tpgtools/overrides/firebaserules/beta/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/firebaserules/beta/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/firebaserules/release.yaml b/tpgtools/overrides/firebaserules/release.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/firebaserules/release.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/firebaserules/ruleset.yaml b/tpgtools/overrides/firebaserules/ruleset.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/firebaserules/ruleset.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/firebaserules/samples/release/firestore_release.tf.tmpl b/tpgtools/overrides/firebaserules/samples/release/firestore_release.tf.tmpl deleted file mode 100644 index 83212f390aba..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/firestore_release.tf.tmpl +++ /dev/null @@ -1,16 +0,0 @@ -resource "google_firebaserules_release" "primary" { - name = "cloud.firestore" - project = "{{project}}" - ruleset_name = "projects/{{project}}/rulesets/${google_firebaserules_ruleset.firestore.name}" -} - -resource "google_firebaserules_ruleset" "firestore" { - project = "{{project}}" - - source { - files { - content = "service cloud.firestore {match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } }" - name = "firestore.rules" - } - } -} diff --git a/tpgtools/overrides/firebaserules/samples/release/firestore_release.yaml b/tpgtools/overrides/firebaserules/samples/release/firestore_release.yaml deleted file mode 100644 index 6e3bff6c0e67..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/firestore_release.yaml +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: firestore_release -description: Creates a Firebase Rules Release to the default Cloud Firestore instance -type: release -versions: -- ga -- beta -resource: ./firestore_release.tf.tmpl -variables: -- name: project - type: project \ No newline at end of file diff --git a/tpgtools/overrides/firebaserules/samples/release/firestore_release_additional.tf.tmpl b/tpgtools/overrides/firebaserules/samples/release/firestore_release_additional.tf.tmpl deleted file mode 100644 index 4512e0d7b956..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/firestore_release_additional.tf.tmpl +++ /dev/null @@ -1,16 +0,0 @@ -resource "google_firebaserules_release" "primary" { - name = "cloud.firestore/{{database}}" - project = "{{project}}" - ruleset_name = "projects/{{project}}/rulesets/${google_firebaserules_ruleset.firestore.name}" -} - -resource "google_firebaserules_ruleset" "firestore" { - project = "{{project}}" - - source { - files { - content = "service cloud.firestore {match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } }" - name = "firestore.rules" - } - } -} diff --git a/tpgtools/overrides/firebaserules/samples/release/firestore_release_additional.yaml b/tpgtools/overrides/firebaserules/samples/release/firestore_release_additional.yaml deleted file mode 100644 index 7668f4f15616..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/firestore_release_additional.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2024 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: firestore_release_additional -description: Creates a Firebase Rules Release to an additional Cloud Firestore instance -type: release -versions: -- ga -- beta -resource: ./firestore_release_additional.tf.tmpl -variables: -- name: project - type: project -- name: database - type: resource_name \ No newline at end of file diff --git a/tpgtools/overrides/firebaserules/samples/release/meta.yaml b/tpgtools/overrides/firebaserules/samples/release/meta.yaml deleted file mode 100644 index a397c08240d4..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/meta.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# meta.yaml -# this is a shared config file that all the tests merge with -# -# The firestore_release test uses the default Firestore instance, which can have an existing Rules deployment for whatever reason. -# However, the firestore_release_additional test was sufficient because Rules deployment doesn't care about whether it's the default Firestore instance -test_hide: - - firestore_release.tf.tmpl diff --git a/tpgtools/overrides/firebaserules/samples/release/storage_release.tf.tmpl b/tpgtools/overrides/firebaserules/samples/release/storage_release.tf.tmpl deleted file mode 100644 index dde2df5eb007..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/storage_release.tf.tmpl +++ /dev/null @@ -1,43 +0,0 @@ -resource "google_firebaserules_release" "primary" { - provider = google-beta - name = "firebase.storage/${google_storage_bucket.bucket.name}" - ruleset_name = "projects/{{project}}/rulesets/${google_firebaserules_ruleset.storage.name}" - project = "{{project}}" - - lifecycle { - replace_triggered_by = [ - google_firebaserules_ruleset.storage - ] - } -} - -# Provision a non-default Cloud Storage bucket. -resource "google_storage_bucket" "bucket" { - provider = google-beta - project = "{{project}}" - name = "{{bucket}}" - location = "{{region}}" -} - -# Make the Storage bucket accessible for Firebase SDKs, authentication, and Firebase Security Rules. -resource "google_firebase_storage_bucket" "bucket" { - provider = google-beta - project = "{{project}}" - bucket_id = google_storage_bucket.bucket.name -} - -# Create a ruleset of Firebase Security Rules from a local file. -resource "google_firebaserules_ruleset" "storage" { - provider = google-beta - project = "{{project}}" - source { - files { - name = "storage.rules" - content = "service firebase.storage {match /b/{bucket}/o {match /{allPaths=**} {allow read, write: if request.auth != null;}}}" - } - } - - depends_on = [ - google_firebase_storage_bucket.bucket - ] -} diff --git a/tpgtools/overrides/firebaserules/samples/release/storage_release.yaml b/tpgtools/overrides/firebaserules/samples/release/storage_release.yaml deleted file mode 100644 index 9d25684d8b78..000000000000 --- a/tpgtools/overrides/firebaserules/samples/release/storage_release.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2022 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -name: storage_release -description: Creates a Firebase Rules Release for a Storage bucket -type: release -versions: -- beta -resource: ./storage_release.tf.tmpl -variables: -- name: project - type: project -- name: region - type: region -- name: bucket - type: resource_name \ No newline at end of file diff --git a/tpgtools/overrides/firebaserules/samples/ruleset/meta.yaml b/tpgtools/overrides/firebaserules/samples/ruleset/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/firebaserules/tpgtools_product.yaml b/tpgtools/overrides/firebaserules/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/firebaserules/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/gkehub/beta/feature_membership.yaml b/tpgtools/overrides/gkehub/beta/feature_membership.yaml deleted file mode 100644 index 7ad339d10b73..000000000000 --- a/tpgtools/overrides/gkehub/beta/feature_membership.yaml +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -- type: CUSTOM_ID - details: - id: 'projects/{{project}}/locations/{{location}}/features/{{feature}}/membershipId/{{membership}}' -- type: MUTEX - details: - mutex: '{{project}}/{{location}}/{{feature}}' -- type: CUSTOM_TERRAFORM_PRODUCT_NAME - details: - product: gke_hub -- type: DEPRECATED - field: mesh.control_plane - details: - message: >- - Deprecated in favor of the `management` field -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject -- type: COMPLEX_MAP_KEY_NAME - field: policycontroller.policy_controller_hub_config.policy_content.bundles - details: - keyname: bundle_name -- type: COMPLEX_MAP_KEY_NAME - field: policycontroller.policy_controller_hub_config.deployment_configs - details: - keyname: component_name -- type: CUSTOM_SCHEMA_VALUES - field: policycontroller.policy_controller_hub_config.audit_interval_seconds - details: - computed: true - optional: true \ No newline at end of file diff --git a/tpgtools/overrides/gkehub/beta/tpgtools_product.yaml b/tpgtools/overrides/gkehub/beta/tpgtools_product.yaml deleted file mode 100644 index 589844700c05..000000000000 --- a/tpgtools/overrides/gkehub/beta/tpgtools_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -## product level overrides - -## Skip base path generation... needs to not share a name with GKEHub Membership -- type: PRODUCT_BASE_PATH - details: - skip: true - basepathidentifier: gkehub diff --git a/tpgtools/overrides/gkehub/feature_membership.yaml b/tpgtools/overrides/gkehub/feature_membership.yaml deleted file mode 100644 index 459cfab366ae..000000000000 --- a/tpgtools/overrides/gkehub/feature_membership.yaml +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2021 Google LLC. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -- type: CUSTOM_ID - details: - id: 'projects/{{project}}/locations/{{location}}/features/{{feature}}/membershipId/{{membership}}' -- type: MUTEX - details: - mutex: '{{project}}/{{location}}/{{feature}}' -- type: CUSTOM_TERRAFORM_PRODUCT_NAME - details: - product: gke_hub -- type: DEPRECATED - field: mesh.control_plane - details: - message: >- - Deprecated in favor of the `management` field -- type: COMPLEX_MAP_KEY_NAME - field: policycontroller.policy_controller_hub_config.policy_content.bundles - details: - keyname: bundle_name -- type: COMPLEX_MAP_KEY_NAME - field: policycontroller.policy_controller_hub_config.deployment_configs - details: - keyname: component_name -- type: CUSTOM_SCHEMA_VALUES - field: policycontroller.policy_controller_hub_config.audit_interval_seconds - details: - computed: true - optional: true \ No newline at end of file diff --git a/tpgtools/overrides/gkehub/samples/feature_membership/meta.yaml b/tpgtools/overrides/gkehub/samples/feature_membership/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/gkehub/tpgtools_product.yaml b/tpgtools/overrides/gkehub/tpgtools_product.yaml deleted file mode 100644 index 589844700c05..000000000000 --- a/tpgtools/overrides/gkehub/tpgtools_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -## product level overrides - -## Skip base path generation... needs to not share a name with GKEHub Membership -- type: PRODUCT_BASE_PATH - details: - skip: true - basepathidentifier: gkehub diff --git a/tpgtools/overrides/recaptchaenterprise/beta/key.yaml b/tpgtools/overrides/recaptchaenterprise/beta/key.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/recaptchaenterprise/beta/key.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/recaptchaenterprise/beta/tpgtools_product.yaml b/tpgtools/overrides/recaptchaenterprise/beta/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/recaptchaenterprise/beta/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/overrides/recaptchaenterprise/key.yaml b/tpgtools/overrides/recaptchaenterprise/key.yaml deleted file mode 100644 index af851d79a0c9..000000000000 --- a/tpgtools/overrides/recaptchaenterprise/key.yaml +++ /dev/null @@ -1,4 +0,0 @@ -- type: CUSTOMIZE_DIFF - details: - functions: - - tpgresource.DefaultProviderProject diff --git a/tpgtools/overrides/recaptchaenterprise/samples/key/meta.yaml b/tpgtools/overrides/recaptchaenterprise/samples/key/meta.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/overrides/recaptchaenterprise/tpgtools_product.yaml b/tpgtools/overrides/recaptchaenterprise/tpgtools_product.yaml deleted file mode 100644 index 862ff73cb130..000000000000 --- a/tpgtools/overrides/recaptchaenterprise/tpgtools_product.yaml +++ /dev/null @@ -1,3 +0,0 @@ -- type: PRODUCT_BASE_PATH - details: - skip: true diff --git a/tpgtools/product.go b/tpgtools/product.go deleted file mode 100644 index 3c68ca780a70..000000000000 --- a/tpgtools/product.go +++ /dev/null @@ -1,133 +0,0 @@ -package main - -import ( - "fmt" - "log" - "strings" - - "github.com/golang/glog" - "github.com/nasa9084/go-openapi" -) - -type ProductMetadata struct { - // PackagePath is the path to the package relative to the dcl - PackagePath Filepath - // PackageName is the namespace of the package within the dcl - // the PackageName is normally a lowercase variant of ProductName - PackageName DCLPackageName - // ProductName is the case accounted (snake case) name of the product - // that the resource belongs to. - ProductName SnakeCaseProductName -} - -var productOverrides map[Filepath]Overrides = make(map[Filepath]Overrides, 0) - -func GetProductMetadataFromDocument(document *openapi.Document, packagePath Filepath) *ProductMetadata { - // load overrides for product - if _, ok := productOverrides[packagePath]; !ok { - productOverrides[packagePath] = loadOverrides(packagePath, "tpgtools_product.yaml") - } - title := getProductTitle(document.Info.Title, packagePath) - productMetadata := NewProductMetadata(packagePath, title) - return productMetadata -} - -func NewProductMetadata(packagePath Filepath, productName string) *ProductMetadata { - packageName := strings.Split(string(packagePath), "/")[0] - return &ProductMetadata{ - PackagePath: packagePath, - PackageName: DCLPackageName(packageName), - ProductName: SnakeCaseProductName(jsonToSnakeCase(productName)), - } -} - -func (pm *ProductMetadata) ShouldWriteProductBasePath() bool { - bp := pm.ProductBasePathDetails() - if bp == nil { - return true - } - return !bp.Skip -} - -func (pm *ProductMetadata) BasePathIdentifier() BasePathOverrideNameSnakeCase { - bp := pm.ProductBasePathDetails() - if bp != nil && bp.BasePathIdentifier != "" { - return BasePathOverrideNameSnakeCase(bp.BasePathIdentifier) - } - return BasePathOverrideNameSnakeCase(pm.ProductName) -} - -func (pm *ProductMetadata) ProductBasePathDetails() *ProductBasePathDetails { - overrides, ok := productOverrides[pm.PackagePath] - if !ok { - glog.Fatalf("product overrides should be loaded already for packagePath %s", pm.PackagePath) - } - bp := ProductBasePathDetails{} - bpOk, err := overrides.ProductOverrideWithDetails(ProductBasePath, &bp) - if err != nil { - log.Fatalln("error - failed to decode base path details") - } - - if !bpOk { - return nil - } - - return &bp -} - -// getProductTitle is used internally to get the product title -// or case sensitve product name from the product definition -// we will also check if there is an override for the product title -// and utilize that if avalible and set. -func getProductTitle(documentTitle string, packagePath Filepath) string { - overrides, ok := productOverrides[packagePath] - if !ok { - glog.Fatalf("product overrides should be loaded already for packagePath %s", packagePath) - } - - pt := ProductTitleDetails{} - ptOk, err := overrides.ProductOverrideWithDetails(ProductTitle, &pt) - if err != nil { - glog.Fatalln("error - failed to decode base path details") - } - - if ptOk { - if pt.Title == "" { - glog.Fatalf("error - product title override defined but got empty value for %", packagePath) - } - title := pt.Title - return title - } - - titleParts := strings.Split(documentTitle, "/") - if len(titleParts) < 0 { - glog.Exitf("could not find product information for %s", packagePath) - } - title := titleParts[0] - return title -} - -func (pm *ProductMetadata) DocsSection() miscellaneousNameTitleCase { - overrides, ok := productOverrides[pm.PackagePath] - if !ok { - glog.Fatalf("product overrides should be loaded already for packagePath %s", pm.PackagePath) - } - pt := ProductDocsSectionDetails{} - ptOk, err := overrides.ProductOverrideWithDetails(ProductDocsSection, &pt) - if err != nil { - glog.Fatalf("could not parse override %v", err) - } - if ptOk { - return miscellaneousNameTitleCase(pt.DocsSection) - } - - return miscellaneousNameTitleCase(pm.ProductName.ToTitle()) -} - -func (pm *ProductMetadata) PackageNameWithVersion() DCLPackageNameWithVersion { - ss := strings.Split(string(pm.PackagePath), "/") - if len(ss) == 1 { - return DCLPackageNameWithVersion(pm.PackageName) - } - return DCLPackageNameWithVersion(fmt.Sprintf("%s/%s", pm.PackageName, ss[len(ss)-1])) -} diff --git a/tpgtools/property.go b/tpgtools/property.go deleted file mode 100644 index aca248781c04..000000000000 --- a/tpgtools/property.go +++ /dev/null @@ -1,1048 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "fmt" - "sort" - "strings" - "unicode" - - "github.com/golang/glog" - "github.com/nasa9084/go-openapi" -) - -// Property is the representation of a TPG resource property in tpgtools. -type Property struct { - // title is the name of a property. - title string - // PackageName is the title-cased shortname of a field as it appears as a - // property in the DCL. For example, "MachineType". - PackageName string - // Type is the type of a property. - Type - - // Settable indicates that a field is settable in desired specs provided to - // Apply. - // Settable fields may be Computed- fields are sometimes Optional + Computed - // to indicate that they have complex default values in the API. - Settable bool - - // Only applies to nested object properties. - // Indicates this property should be excluded and its - // subproperties should be brought up a level. - Collapsed bool - - // Elem is the value to insert into the Elem field. If empty, none will be - // inserted. - // In most cases, this should be a function call to a schema function. For - // TypeMaps, this will be a one-liner adding a primitive elem. - Elem *string - ElemIsBasicType bool - - // ConflictsWith is the list of fields that this field conflicts with - ConflictsWith ConflictsWith - - // ConflictsWith is the list of fields that this field conflicts with - // in JSONCase. For example, "machineType" - JSONCaseConflictsWith []string - - // Default is the default for the field. - Default *string - - // raw schema values - Required bool - Optional bool - Computed bool - Sensitive bool - WriteOnly bool - - ForceNew bool - Description string - - DiffSuppressFunc *string - ValidateFunc *string - SetHashFunc *string - MaxItems *int64 - MinItems *int64 - ConfigMode *string - - Removed *string - Deprecated *string - // end raw schema values - - // StateGetter is the line of code to retrieve a field from the `d` - // ResourceData or (TODO:) from a map[string]interface{} - StateGetter *string - - // StateSetter is the line of code to set a field in the `d` ResourceData - // or (TODO:) a map[string]interface{} - StateSetter *string - - // If this field is a three-state boolean in DCL which is represented as a - // string in terraform. This is done so that the DCL can distinguish between - // the field being unset and being set to false. - EnumBool bool - - // Whether this field is only used as a url parameter - Parameter bool - // Whether this field has long form behavior in the DCL - HasLongForm bool - - // An IdentityGetter is a function to retrieve the value of an "identity" field - // from state. Identity fields will sometimes allow retrieval from multiple - // fields or from the user's environment variables. - // In the most common case, project/region/zone will use special resource-level - // properties instead of IdentityGetters. However, if they have atypical - // behaviour, such as sourcing a region from a zone, an IdentityGetter will be - // used instead. - IdentityGetter *string - - // Sub-properties of nested objects or arrays with nested objects - Properties []Property - - // If this is a complex map type, this string represents the name of the - // field that the key to the map can be set with - ComplexMapKeyName string - - // Reference to the parent resource. - // note: "Properties" will not be available. - resource *Resource - - // Reference to the parent property of a sub-property. If the property is - // top-level, this will be unset. - parent *Property - - // customName is the Terraform-specific name that overrides title. - customName string - - // Ref is the name of the shared reference type. - ref string - - // If this property allows forward slashes in its value (only important for - // properties sent in the URL) - forwardSlashAllowed bool -} - -// An IdentityGetter is a function to retrieve the value of an "identity" field -// from state. -type IdentityGetter struct { - // If HasError is set to true, the function called by FunctionCall will - // return (v, error) - HasError bool - // Rendered function call to insert into the template. For example, - // d.Get("name").(string) - FunctionCall string -} - -// Name is the shortname of a field. For example, "machine_type". -func (p Property) Name() string { - if len(p.customName) > 0 { - return p.customName - } - return p.title -} - -// overridePath is the path of a property used in override names. For example, -// "node_config.machine_type". -func (p Property) overridePath() string { - if p.parent != nil { - return p.parent.overridePath() + "." + p.title - } - - return p.title -} - -// PackageJSONName is the camel-cased shortname of a field as it appears in the -// DCL's json serialization. For example, "machineType". -func (p Property) PackageJSONName() string { - s := p.PackageName - a := []rune(s) - - if len(a) == 0 { - return "" - } - a[0] = unicode.ToLower(a[0]) - return string(a) -} - -// PackagePath is the title-cased path of a type (relative to the resource) for -// use in naming functions. For example, "MachineType" or "NodeConfigPreemptible". -func (p Property) PackagePath() string { - if p.ref != "" { - return p.ref - } - if p.parent != nil { - return p.parent.PackagePath() + p.PackageName - } - - return p.PackageName -} - -func (p Property) ObjectType() string { - parent := p - // Look up chain to see if we are within a reference - // types within a reference should not use the parent resource's type - for { - if parent.ref != "" { - return p.PackagePath() - } - if parent.parent == nil { - break - } - parent = *parent.parent - } - return fmt.Sprintf("%s%s", p.resource.DCLTitle(), p.PackagePath()) -} - -func (p Property) IsArray() bool { - return (p.Type.String() == SchemaTypeList || p.Type.String() == SchemaTypeSet) && !p.Type.IsObject() && !p.IsComplexMap() -} - -func (t Type) IsSet() bool { - return t.String() == SchemaTypeSet -} - -// Complex map is for maps of string --> object that are supported in DCL but -// not in Terraform. We handle this by adding a field in the Terraform schema -// for the key in the map. This must be added via a COMPLEX_MAP_KEY_NAME -// override -func (t Type) IsComplexMap() bool { - if t.typ.AdditionalProperties != nil { - return t.typ.AdditionalProperties.Type != "string" - } - return false -} - -// ShouldGenerateNestedSchema returns true if an object's nested schema function should be generated. -func (p Property) ShouldGenerateNestedSchema() bool { - return len(p.Properties) > 0 && !p.Collapsed -} - -func (p Property) IsServerGeneratedName() bool { - return p.StateGetter != nil && !p.Settable -} - -// DefaultStateGetter returns the line of code to retrieve a field from the `d` -// ResourceData or (TODO:) from a map[string]interface{} -func (p Property) DefaultStateGetter() string { - rawGetter := fmt.Sprintf("d.Get(%q)", p.Name()) - return buildGetter(p, rawGetter) -} - -func (p Property) ChangeStateGetter() string { - return buildGetter(p, fmt.Sprintf("tpgdclresource.OldValue(d.GetChange(%q))", p.Name())) -} - -// Builds a Getter for constructing a shallow -// version of the object for destroy purposes -func (p Property) StateGetterForDestroyTest() string { - pullValueFromState := fmt.Sprintf(`rs.Primary.Attributes["%s"]`, p.Name()) - - switch p.Type.String() { - case SchemaTypeBool: - return fmt.Sprintf(`dcl.Bool(%s == "true")`, pullValueFromState) - case SchemaTypeString: - if p.Type.IsEnum() { - return fmt.Sprintf("%s.%sEnumRef(%s)", p.resource.Package(), p.ObjectType(), pullValueFromState) - } - if p.Computed { - return fmt.Sprintf("dcl.StringOrNil(%s)", pullValueFromState) - } - return fmt.Sprintf("dcl.String(%s)", pullValueFromState) - } - - return "" -} - -// Builds a Getter for a property with given raw value -func buildGetter(p Property, rawGetter string) string { - switch p.Type.String() { - case SchemaTypeBool: - return fmt.Sprintf("dcl.Bool(%s.(bool))", rawGetter) - case SchemaTypeString: - if p.Type.IsEnum() { - return fmt.Sprintf("%s.%sEnumRef(%s.(string))", p.resource.Package(), p.ObjectType(), rawGetter) - } - if p.EnumBool { - return fmt.Sprintf("tpgdclresource.ExpandEnumBool(%s.(string))", rawGetter) - } - if p.Computed { - return fmt.Sprintf("dcl.StringOrNil(%s.(string))", rawGetter) - } - return fmt.Sprintf("dcl.String(%s.(string))", rawGetter) - case SchemaTypeFloat: - if p.Computed { - return fmt.Sprintf("dcl.Float64OrNil(%s.(float64))", rawGetter) - } - return fmt.Sprintf("dcl.Float64(%s.(float64))", rawGetter) - case SchemaTypeInt: - if p.Computed { - return fmt.Sprintf("dcl.Int64OrNil(int64(%s.(int)))", rawGetter) - } - return fmt.Sprintf("dcl.Int64(int64(%s.(int)))", rawGetter) - case SchemaTypeMap: - return fmt.Sprintf("tpgresource.CheckStringMap(%s)", rawGetter) - case SchemaTypeList, SchemaTypeSet: - if p.Type.IsEnumArray() { - return fmt.Sprintf("expand%s%sArray(%s)", p.resource.PathType(), p.PackagePath(), rawGetter) - } - if p.Type.IsComplexMap() { - return fmt.Sprintf("expand%s%sMap(%s)", p.resource.PathType(), p.PackagePath(), rawGetter) - } - if p.Type.typ.Items != nil && p.Type.typ.Items.Type == "string" { - return fmt.Sprintf("tpgdclresource.ExpandStringArray(%s)", rawGetter) - } - - if p.Type.typ.Items != nil && p.Type.typ.Items.Type == "integer" { - return fmt.Sprintf("tpgdclresource.ExpandIntegerArray(%s)", rawGetter) - } - - if p.Type.typ.Items != nil && len(p.Properties) > 0 { - return fmt.Sprintf("expand%s%sArray(%s)", p.resource.PathType(), p.PackagePath(), rawGetter) - } - } - - if p.typ.Type == "object" { - return fmt.Sprintf("expand%s%s(%s)", p.resource.PathType(), p.PackagePath(), rawGetter) - } - - return "" -} - -// DefaultStateSetter returns the line of code to set a field in the `d` -// ResourceData or (TODO:) a map[string]interface{} -func (p Property) DefaultStateSetter() string { - switch p.Type.String() { - case SchemaTypeBool: - fallthrough - case SchemaTypeString: - fallthrough - case SchemaTypeInt: - fallthrough - case SchemaTypeFloat: - fallthrough - case SchemaTypeMap: - if p.IsResourceLabels() || p.IsResourceAnnotations() { - return fmt.Sprintf("d.Set(%q, flatten%s%s(res.%s, d))", p.Name(), p.resource.PathType(), p.PackagePath(), p.PackageName) - } - - return fmt.Sprintf("d.Set(%q, res.%s)", p.Name(), p.PackageName) - case SchemaTypeList, SchemaTypeSet: - if p.IsComplexMap() { - return fmt.Sprintf("d.Set(%q, flatten%s%sMap(res.%s))", p.Name(), p.resource.PathType(), p.PackagePath(), p.PackageName) - } - if p.typ.Items != nil && ((p.typ.Items.Type == "string" && len(p.typ.Items.Enum) == 0) || p.typ.Items.Type == "integer") { - return fmt.Sprintf("d.Set(%q, res.%s)", p.Name(), p.PackageName) - } - if p.typ.Items != nil && (len(p.Properties) > 0 || len(p.typ.Items.Enum) > 0) { - return fmt.Sprintf("d.Set(%q, flatten%s%sArray(res.%s))", p.Name(), p.resource.PathType(), p.PackagePath(), p.PackageName) - } - } - - if p.typ.Type == "object" { - return fmt.Sprintf("d.Set(%q, flatten%s%s(res.%s))", p.Name(), p.resource.PathType(), p.PackagePath(), p.PackageName) - } - - return "" -} - -// ExpandGetter needs to return a snippet of code that produces the DCL-type -// for the field from a map[string]interface{} named obj that represents the -// parent object in Terraform. -func (p Property) ExpandGetter() string { - rawGetter := fmt.Sprintf("obj[%q]", p.Name()) - return buildGetter(p, rawGetter) -} - -// FlattenGetter needs to return a snippet of code that returns an interface{} which -// can be used in the d.Set() call, given a DCL-type for the parent object named `obj`. -func (p Property) FlattenGetter() string { - return p.flattenGetterWithParent("obj") -} - -func (p Property) flattenGetterWithParent(parent string) string { - switch p.Type.String() { - case SchemaTypeBool: - fallthrough - case SchemaTypeString: - fallthrough - case SchemaTypeInt: - fallthrough - case SchemaTypeFloat: - fallthrough - case SchemaTypeMap: - if p.EnumBool { - return fmt.Sprintf("tpgdclresource.FlattenEnumBool(%s.%s)", parent, p.PackageName) - } - return fmt.Sprintf("%s.%s", parent, p.PackageName) - case SchemaTypeList, SchemaTypeSet: - if p.Type.IsEnumArray() { - return fmt.Sprintf("flatten%s%sArray(obj.%s)", p.resource.PathType(), p.PackagePath(), p.PackageName) - } - if p.Type.IsComplexMap() { - return fmt.Sprintf("flatten%s%sMap(%s.%s)", p.resource.PathType(), p.PackagePath(), parent, p.PackageName) - } - if p.Type.typ.Items != nil && p.Type.typ.Items.Type == "integer" { - return fmt.Sprintf("%s.%s", parent, p.PackageName) - } - if p.Type.typ.Items != nil && p.Type.typ.Items.Type == "string" { - return fmt.Sprintf("%s.%s", parent, p.PackageName) - } - - if p.Type.typ.Items != nil && len(p.Properties) > 0 { - return fmt.Sprintf("flatten%s%sArray(%s.%s)", p.resource.PathType(), p.PackagePath(), parent, p.PackageName) - } - } - if p.typ.Type == "object" { - return fmt.Sprintf("flatten%s%s(%s.%s)", p.resource.PathType(), p.PackagePath(), parent, p.PackageName) - } - - return "" -} - -func getSchemaExtensionMap(v interface{}) map[interface{}]interface{} { - if v != nil { - return nil - } - ls, ok := v.([]interface{}) - if ok && len(ls) > 0 { - return ls[0].(map[interface{}]interface{}) - } - return nil -} - -func (p Property) DefaultDiffSuppress() *string { - switch p.Type.String() { - case SchemaTypeString: - // Field is reference to another resource - if _, ok := p.typ.Extension["x-dcl-references"]; ok { - dsf := "tpgresource.CompareSelfLinkOrResourceName" - return &dsf - } - } - return nil -} - -func (p Property) GetRequiredFileImports() (imports []string) { - if p.ValidateFunc != nil && strings.Contains(*p.ValidateFunc, "validation.") { - imports = append(imports, GoPkgTerraformSdkValidation) - } - return imports -} - -func (p Property) DefaultSetHashFunc() *string { - switch p.Type.String() { - case SchemaTypeSet: - if p.ElemIsBasicType { - shf := "schema.HashString" - return &shf - } - shf := fmt.Sprintf("schema.HashResource(%s)", *p.Elem) - return &shf - } - glog.Fatalf("Failed to find valid hash func") - return nil -} - -// Objects returns a flatmap of the sub-properties within a Property which are -// objects (eg: have sub-properties themselves). -func (p Property) Objects() (props []Property) { - // if p.Properties is set, p is an object - for _, v := range p.Properties { - if len(v.Properties) != 0 { - if v.ref == "" { - props = append(props, v) - props = append(props, v.Objects()...) - } - } - } - - return props -} - -func (p Property) IsResourceLabels() bool { - return p.Name() == "labels" && p.parent == nil -} - -func (p Property) IsResourceAnnotations() bool { - return p.Name() == "annotations" && p.parent == nil -} - -func (p Property) IsTopLevel() bool { - return p.parent == nil -} - -func (p Property) ShouldShowUpInSamples() bool { - return (p.Settable && p.Name() != "effective_labels" && p.Name() != "effective_annotations") || p.IsResourceLabels() || p.IsResourceAnnotations() -} - -// collapsedProperties returns the input list of properties with nested objects collapsed if needed. -func collapsedProperties(props []Property) (collapsed []Property) { - for _, v := range props { - if len(v.Properties) != 0 && v.Collapsed { - collapsed = append(collapsed, collapsedProperties(v.Properties)...) - } else { - collapsed = append(collapsed, v) - } - } - return collapsed -} - -// Alias []string so that append etc. still work, but we can attach a rendering -// function to the object -type ConflictsWith []string - -func (c ConflictsWith) String() string { - var quoted []string - for _, s := range c { - quoted = append(quoted, fmt.Sprintf("%q", s)) - } - return fmt.Sprintf("[]string{%s}", strings.Join(quoted, ",")) -} - -// Builds a list of properties from an OpenAPI schema. -func createPropertiesFromSchema(schema *openapi.Schema, typeFetcher *TypeFetcher, overrides Overrides, resource *Resource, parent *Property, location string) (props []Property, err error) { - identityFields := []string{} // always empty if parent != nil - if parent == nil { - identityFields = idParts(resource.ID) - } - - // Maps PackageJSONName back to property Name - // for conflict fields - conflictsMap := make(map[string]string) - - for k, v := range schema.Properties { - ref := "" - packageName := "" - - if pName, ok := v.Extension["x-dcl-go-name"].(string); ok { - packageName = pName - } - - if v.Ref != "" { - ref = v.Ref - v, err = typeFetcher.ResolveSchema(v.Ref) - if err != nil { - return nil, err - } - ref = typeFetcher.PackagePathForReference(ref, v.Extension["x-dcl-go-type"].(string)) - } - - // Sub-properties are referenced by name, and the explicit title value - // won't be set initially. - v.Title = k - - if parent == nil && v.Title == "id" { - // If top-level field is named `id`, rename to avoid collision with Terraform id - v.Title = fmt.Sprintf("%s%s", resource.Name(), "Id") - } - - p := Property{ - title: jsonToSnakeCase(v.Title).snakecase(), - Type: Type{typ: v}, - PackageName: packageName, - Description: v.Description, - resource: resource, - parent: parent, - ref: ref, - } - - if overrides.PropertyOverride(Exclude, p, location) { - continue - } - - do := CustomDefaultDetails{} - doOk, err := overrides.PropertyOverrideWithDetails(CustomDefault, p, &do, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom list size details") - } - - if v.Default != "" || doOk { - def := v.Default - if doOk { - def = do.Default - } - d, err := renderDefault(p.Type, def) - if err != nil { - return nil, fmt.Errorf("failed to render default: %v", err) - } - p.Default = &d - } - - cn := CustomNameDetails{} - cnOk, err := overrides.PropertyOverrideWithDetails(CustomName, p, &cn, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom name details: %v", err) - } - if cnOk { - p.customName = cn.Name - } - - if p.Type.String() == SchemaTypeMap { - e := "&schema.Schema{Type: schema.TypeString}" - p.Elem = &e - p.ElemIsBasicType = true - } - - if sens, ok := v.Extension["x-dcl-sensitive"].(bool); ok { - p.Sensitive = sens - } - - if v, ok := v.Extension["x-dcl-conflicts"].([]interface{}); ok { - // NOTE: DCL not label x-dcl-conflicts for reused types - // TODO: handle nested field when b/213503595 got fixed - - if parent == nil { - for _, ci := range v { - p.JSONCaseConflictsWith = append(p.JSONCaseConflictsWith, ci.(string)) - } - - conflictsMap[p.PackageJSONName()] = p.Name() - } - } - - // Do this before handling properties so we can check if the parent is readOnly - isSGP := false - if sgp, ok := v.Extension["x-dcl-server-generated-parameter"].(bool); ok { - isSGP = sgp - } - if v.ReadOnly || isSGP || (parent != nil && parent.Computed) { - p.Computed = true - - if stringInSlice(p.Name(), identityFields) { - sg := p.DefaultStateGetter() - p.StateGetter = &sg - } - } - - p.Parameter, _ = v.Extension["x-dcl-parameter"].(bool) - p.HasLongForm, _ = v.Extension["x-dcl-has-long-form"].(bool) - - // Handle object properties - if len(v.Properties) > 0 { - props, err := createPropertiesFromSchema(v, typeFetcher, overrides, resource, &p, location) - if err != nil { - return nil, err - } - - p.Properties = props - if !p.Computed { - // Computed fields cannot specify MaxItems - mi := int64(1) - p.MaxItems = &mi - } - e := fmt.Sprintf("%s%sSchema()", resource.PathType(), p.PackagePath()) - p.Elem = &e - p.ElemIsBasicType = false - } - - // Handle array properties - if v.Items != nil { - ls := CustomListSizeConstraintDetails{} - lsOk, err := overrides.PropertyOverrideWithDetails(CustomListSize, p, &ls, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom list size details") - } - if lsOk { - if ls.Max > 0 { - p.MaxItems = &ls.Max - } - if ls.Min > 0 { - p.MinItems = &ls.Min - } - } - - // We end up handling arrays of objects very similarly to nested objects - // themselves - if len(v.Items.Properties) > 0 { - props, err := createPropertiesFromSchema(v.Items, typeFetcher, overrides, resource, &p, location) - if err != nil { - return nil, err - } - - p.Properties = props - e := fmt.Sprintf("%s%sSchema()", resource.PathType(), p.PackagePath()) - p.Elem = &e - p.ElemIsBasicType = false - } else { - i := Type{typ: v.Items} - e := fmt.Sprintf("&schema.Schema{Type: schema.%s}", i.String()) - if _, ok := v.Extension["x-dcl-references"]; ok { - e = fmt.Sprintf("&schema.Schema{Type: schema.%s, DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, }", i.String()) - } - p.Elem = &e - p.ElemIsBasicType = true - } - } - // Complex maps are represented as TypeSet but don't have v.Items set. - // Use AdditionalProperties instead, and add an additional `name` field - // that represents the key in the map - if p.Type.IsComplexMap() { - props, err := createPropertiesFromSchema(p.Type.typ.AdditionalProperties, typeFetcher, overrides, resource, &p, location) - if err != nil { - return nil, err - } - cm := ComplexMapKeyDetails{} - cmOk, err := overrides.PropertyOverrideWithDetails(ComplexMapKey, p, &cm, location) - if err != nil { - return nil, fmt.Errorf("failed to decode complex map key name details") - } - if !cmOk { - return nil, fmt.Errorf("failed to find complex map key name for map named: %s", p.Name()) - } - keyProp := Property{ - title: cm.KeyName, - Type: Type{&openapi.Schema{Type: "string"}}, - resource: resource, - parent: &p, - Required: true, - Description: "The name for the key in the map for which this object is mapped to in the API", - } - props = append([]Property{keyProp}, props...) - - p.Properties = props - e := fmt.Sprintf("%s%sSchema()", resource.PathType(), p.PackagePath()) - p.Elem = &e - p.ElemIsBasicType = false - p.ComplexMapKeyName = cm.KeyName - } - - if !p.Computed { - if stringInSlice(v.Title, schema.Required) { - p.Required = true - } else { - p.Optional = true - } - } - cr := CustomSchemaValuesDetails{} - crOk, err := overrides.PropertyOverrideWithDetails(CustomSchemaValues, p, &cr, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom required details") - } - if crOk { - p.Required = cr.Required - p.Optional = cr.Optional - p.Computed = cr.Computed - } - - // Handle settable fields. If the field is computed it's not settable but - // if it's also optional (O+C), it is. - if !p.Computed || (p.Optional) { - p.Settable = true - - // NOTE: x-kubernetes-immmutable implies that all children of a field - // are actually immutable. However, in practice, DCL specs will label - // every immutable subfield. - if isImmutable, ok := v.Extension["x-kubernetes-immutable"].(bool); ok && isImmutable { - p.ForceNew = true - } - - serverDefault, _ := v.Extension["x-dcl-server-default"].(bool) - extractIfEmpty, _ := v.Extension["x-dcl-extract-if-empty"].(bool) - - if serverDefault || extractIfEmpty { - p.Computed = true - } - - if forwardSlashAllowed, ok := v.Extension["x-dcl-forward-slash-allowed"].(bool); ok && forwardSlashAllowed { - p.forwardSlashAllowed = true - } - - // special handling for project/region/zone/other fields with - // provider defaults - if stringInSlice(p.title, []string{"project", "region", "zone"}) || stringInSlice(p.customName, []string{"region", "project", "zone"}) { - p.Optional = true - p.Required = false - p.Computed = true - - sg := fmt.Sprintf("dcl.String(%v)", p.Name()) - p.StateGetter = &sg - - cig := &CustomIdentityGetterDetails{} - cigOk, err := overrides.PropertyOverrideWithDetails(CustomIdentityGetter, p, cig, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom identity getter details") - } - - propertyName := p.title - if p.customName != "" { - propertyName = p.customName - } - ig := fmt.Sprintf("tpgresource.Get%s(d, config)", renderSnakeAsTitle(miscellaneousNameSnakeCase(propertyName))) - if cigOk { - ig = fmt.Sprintf("%s(d, config)", cig.Function) - } - - p.IdentityGetter = &ig - } else { - sg := p.DefaultStateGetter() - p.StateGetter = &sg - } - } - - ss := p.DefaultStateSetter() - p.StateSetter = &ss - - if p.Sensitive && p.Settable { - p.StateSetter = nil - } - - css := CustomStateSetterDetails{} - cssOk, err := overrides.PropertyOverrideWithDetails(CustomStateSetter, p, &css, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom stateSetter func: %v", err) - } - - if cssOk { - p.StateSetter = &css.Function - } - - irOk := overrides.PropertyOverride(IgnoreRead, p, location) - if irOk { - p.StateSetter = nil - } - - cd := CustomDescriptionDetails{} - cdOk, err := overrides.PropertyOverrideWithDetails(CustomDescription, p, &cd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom description details: %v", err) - } - - if cdOk { - p.Description = cd.Description - } - - dsf := CustomDiffSuppressFuncDetails{} - dsfOk, err := overrides.PropertyOverrideWithDetails(DiffSuppressFunc, p, &dsf, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom diff suppress func: %v", err) - } - - if dsfOk { - p.DiffSuppressFunc = &dsf.DiffSuppressFunc - } else if !(p.Computed && !p.Optional) { - p.DiffSuppressFunc = p.DefaultDiffSuppress() - } - - vf := CustomValidationDetails{} - vfOk, err := overrides.PropertyOverrideWithDetails(CustomValidation, p, &vf, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom validation func: %v", err) - } - - if vfOk { - p.ValidateFunc = &vf.Function - } - - if p.Type.IsSet() { - shf := SetHashFuncDetails{} - shfOk, err := overrides.PropertyOverrideWithDetails(SetHashFunc, p, &shf, location) - if err != nil { - return nil, fmt.Errorf("failed to decode set hash func: %v", err) - } - - if shfOk { - p.SetHashFunc = &shf.Function - } else { - p.SetHashFunc = p.DefaultSetHashFunc() - } - } - - cm := CustomConfigModeDetails{} - cmOk, err := overrides.PropertyOverrideWithDetails(CustomConfigMode, p, &cm, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom config mode func: %v", err) - } - if cmOk { - p.ConfigMode = &cm.Mode - } - - rd := &RemovedDetails{} - rdOk, err := overrides.PropertyOverrideWithDetails(Removed, p, rd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode removed details") - } - if rdOk { - p.Removed = &rd.Message - } - - dd := &DeprecatedDetails{} - ddOk, err := overrides.PropertyOverrideWithDetails(Deprecated, p, dd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode deprecated details") - } - if ddOk { - p.Deprecated = &dd.Message - } - - if overrides.PropertyOverride(CollapsedObject, p, location) { - p.Collapsed = true - if p.parent == nil { - collapseSS := fmt.Sprintf("setStateForCollapsedObject(d, %s)", p.flattenGetterWithParent("res")) - p.StateSetter = &collapseSS - } - collapseSG := fmt.Sprintf("expand%s%sCollapsed(d)", p.resource.PathType(), p.PackagePath()) - p.StateGetter = &collapseSG - } - - // Add any new imports as needed - if ls := p.GetRequiredFileImports(); len(ls) > 0 { - resource.additionalFileImportSet.Add(ls...) - } - - csgd := CustomStateGetterDetails{} - csgdOk, err := overrides.PropertyOverrideWithDetails(CustomStateGetter, p, &csgd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom state getter details with err %v", err) - } - if csgdOk { - p.StateGetter = &csgd.Function - } - - if overrides.PropertyOverride(EnumBool, p, location) { - p.EnumBool = true - p.Type.typ.Type = "string" - var parent string - if p.parent == nil { - parent = "res" - } else { - parent = "obj" - } - enumBoolSS := fmt.Sprintf("d.Set(%q, tpgdclresource.FlattenEnumBool(%s.%s))", p.Name(), parent, p.PackageName) - p.StateSetter = &enumBoolSS - enumBoolSG := fmt.Sprintf("tpgdclresource.ExpandEnumBool(d.Get(%q))", p.Name()) - p.StateGetter = &enumBoolSG - } - - if overrides.PropertyOverride(GenerateIfNotSet, p, location) { - p.Computed = true - p.Required = false - p.Optional = true - ig := fmt.Sprintf("generateIfNotSet(d, %q, %q)", p.Name(), "tfgen") - p.IdentityGetter = &ig - n := fmt.Sprintf("&%s", p.Name()) - p.StateGetter = &n - } - - if overrides.PropertyOverride(NamePrefix, p, location) { - p.Computed = true - p.Required = false - p.Optional = true - ig := fmt.Sprintf("generateIfNotSet(d, %q, d.Get(%q).(string))", p.Name(), "name_prefix") - p.IdentityGetter = &ig - n := fmt.Sprintf("&%s", p.Name()) - p.StateGetter = &n - - // plus, add the "name_prefix" property. - props = append(props, Property{ - title: "name_prefix", - Type: p.Type, - resource: resource, - parent: parent, - Optional: true, - Computed: true, - ForceNew: true, - }) - } - - if p.ref != "" { - resource.ReusedTypes = resource.RegisterReusedType(p) - } - - // Add the "effective_labels" property when the current property is top level "labels" or - // add the "effective_annotations" property when the current property is top level "annotations" - - if p.IsResourceLabels() || p.IsResourceAnnotations() { - p.Description = fmt.Sprintf("%s\n\n%s", p.Description, get_labels_field_note(p.title)) - p.Settable = false - p.StateGetter = nil - - props = append(props, build_effective_labels_field(p, resource, parent)) - - if p.IsResourceLabels() { - props = append(props, build_terraform_labels_field(p, resource, parent)) - p.ForceNew = false - } - } - - props = append(props, p) - } - - // handle conflict fields - for i, _ := range props { - p := &props[i] - if p.JSONCaseConflictsWith != nil { - for _, cf := range p.JSONCaseConflictsWith { - if val, ok := conflictsMap[cf]; ok { - p.ConflictsWith = append(p.ConflictsWith, val) - } else { - return nil, fmt.Errorf("Error generating conflict fields. %s is not labeled as a conflict field in DCL", cf) - } - - } - } - } - - // sort the properties so they're in a nice order - sort.SliceStable(props, propComparator(props)) - - return props, nil -} - -func build_effective_labels_field(p Property, resource *Resource, parent *Property) Property { - title := fmt.Sprintf("effective_%s", p.title) - description := fmt.Sprintf("All of %s (key/value pairs) present on the resource in GCP, including the %s configured through Terraform, other clients and services.", p.title, p.title) - stateSetter := fmt.Sprintf("d.Set(%q, res.%s)", title, p.PackageName) - - effectiveLabels := Property{ - title: title, - Type: p.Type, - Description: description, - resource: resource, - parent: parent, - Optional: false, - Computed: true, - ForceNew: p.ForceNew, // Add ForceNew property if labels field has it - PackageName: p.PackageName, - Settable: true, - StateSetter: &stateSetter, - } - - stateGetter := effectiveLabels.DefaultStateGetter() - effectiveLabels.StateGetter = &stateGetter - return effectiveLabels -} - -func build_terraform_labels_field(p Property, resource *Resource, parent *Property) Property { - title := fmt.Sprintf("terraform_%s", p.title) - description := fmt.Sprintf("The combination of %s configured directly on the resource and default %s configured on the provider.", p.title, p.title) - stateSetter := fmt.Sprintf("d.Set(%q, flatten%sTerraform%s(res.%s, d))", title, p.resource.PathType(), p.PackagePath(), p.PackageName) - - return Property{ - title: title, - Type: p.Type, - Description: description, - resource: resource, - parent: parent, - Computed: true, - PackageName: p.PackageName, - StateSetter: &stateSetter, - } -} - -func get_labels_field_note(title string) string { - return fmt.Sprintf("**Note**: This field is non-authoritative, and will only manage the %s present in your configuration.\nPlease refer to the field `effective_%s` for all of the %s present on the resource.", title, title, title) -} diff --git a/tpgtools/property_helpers.go b/tpgtools/property_helpers.go deleted file mode 100644 index bb81101fe0f5..000000000000 --- a/tpgtools/property_helpers.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -// Sorts properties to be in a standard order -func propComparator(props []Property) func(i, j int) bool { - return func(i, j int) bool { - l := props[i] - r := props[j] - - // required < non-required - if l.Required && !r.Required { - return true - } - - // conversely, non-required > required - if r.Required && !l.Required { - return false - } - - // same deal- settable (optional / O+C) fields > Computed fields - if l.Settable && !r.Settable { - return true - } - if r.Settable && !l.Settable { - return false - } - - // finally, sort by name - return l.Name() < r.Name() - } -} diff --git a/tpgtools/resource.go b/tpgtools/resource.go deleted file mode 100644 index ff1eb3d56ec1..000000000000 --- a/tpgtools/resource.go +++ /dev/null @@ -1,1007 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "sort" - "strings" - - "bitbucket.org/creachadair/stringset" - "github.com/golang/glog" - "github.com/nasa9084/go-openapi" - "gopkg.in/yaml.v2" -) - -const GoPkgTerraformSdkValidation = "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - -// Resource is tpgtools' model of what a information is necessary to generate a -// resource in TPG. -type Resource struct { - productMetadata *ProductMetadata - - // ID is the Terraform resource id format as a pattern string. Additionally, - // import formats can be derived from it. - ID string - - // If the Terraform ID format should be used instead of the DCL ID function. - // For example, resources with a regional/global cannot use the DCL ID formatter. - UseTerraformID bool - - // ImportFormats are pattern format strings for importing the Terraform resource. - // TODO: if none are set, the resource does not support import. - ImportFormats []string - - // AppendToBasePath is a string that will be appended to the end of the API base path. - // rarely needed in cases where the shared mm basepath does not include the version - // as in Montioring https://git.io/Jz4Wn - AppendToBasePath string - - // ReplaceInBasePath contains a string replacement for the config base path, - // replacing one substring with another. - ReplaceInBasePath BasePathReplacement - - // SkipInProvider is true when the resource shouldn't be included in the dclResources - // map for the provider. This is usually because it was already included through mmv1. - SkipInProvider bool - - // title is the name of the resource in snake_case. For example, - // "instance", "backend_service". - title SnakeCaseTerraformResourceName - - // dclTitle is the name of the resource in TitleCase, as parsed from the relevant - // DCL YAML file. For example, "Instance", "BackendService". - // This is particularly useful for acronymizations that exist in - // resource names, like OSPolicy. We store it separately from title - // because it can differ, especially in the case of split resources: - // "region_backend_service" vs "BackendService". We use this to - // create the names of DCL functions - "Apply{{dclTitle}}". - dclTitle TitleCaseResourceName - // dclStructName is the name of the resource struct in the DCL. In almost all cases - // this is == to dclTitle, but sometimes, due to (for instance) reserved words in the - // DCL conflicting with resource names, this differs. We use this to create DCL - // structs: `foo := compute.{{dclStructName}}{field1: "bar"}`. - dclStructName TitleCaseResourceName - - // Description of the Terraform resource - Description string - - // Lock name for a mutex to prevent concurrent API calls for a given resource - Mutex string - - // Properties are the fields of a resource. Properties may be nested. - Properties []Property - - // InsertTimeoutMinutes is the timeout value in minutes for the resource - // create operation - InsertTimeoutMinutes int - - // UpdateTimeoutMinutes is the timeout value in minutes for the resource - // update operation - UpdateTimeoutMinutes int - - // DeleteTimeoutMinutes is the timeout value in minutes for the resource - // delete operation - DeleteTimeoutMinutes int - - // PreCreateFunction is the name of a function that's called before the - // Creation call for a resource- specifically, before the id is recorded. - PreCreateFunction *string - - // PostCreateFunction is the name of a function that's called immediately - // after the Creation call for a resource. - PostCreateFunction *string - - // PreDeleteFunction is the name of a function that's called immediately - // prior to the Delete call for a resource. - PreDeleteFunction *string - - // CustomImportFunction is the name of a function that's called in place - // of the standard import template code - CustomImportFunction *string - - // CustomizeDiff is a list of functions to set as the Terraform schema - // CustomizeDiff field - CustomizeDiff []string - - // List of other Golang packages to import in a resources' generated Go file - additionalFileImportSet stringset.Set - - // ListFields is the list of fields required for a list call. - ListFields []string - - // location is one of "zone", "region", or "global". - location string - - // HasProject tells us if the resource has a project field. - HasProject bool - - // HasCreate tells us if the resource has a create endpoint. - HasCreate bool - - // HasSweeper says if this resource has a generated sweeper. - HasSweeper bool - - // These are all of the reused types. - ReusedTypes []Property - - // If this resource requires a state hint to update correctly - StateHint bool - - // CustomCreateDirectiveFunction is the name of a function that takes the - // object to be created and returns a list of directive to use for the apply - // call - CustomCreateDirectiveFunction *string - - // SkipDeleteFunction is the name of a function that takes the - // object and config and returns a boolean for if Terraform should make - // the delete call for the resource - SkipDeleteFunction *string - - // SerializationOnly defines if this resource should not generate provider files - // and only be used for serialization - SerializationOnly bool - - // CustomSerializer defines the function this resource should use to serialize itself. - CustomSerializer *string - - // TerraformProductName is the Product name overridden from the DCL - TerraformProductName *SnakeCaseProductName - - // The array of Samples associated with the resource - Samples []Sample - - // Versions specific information about this resource - versionMetadata Version - - // Reference points to the rest API - Reference *Link - // Guides point to non-rest useful context for the resource. - Guides []Link - - // The current schema version - SchemaVersion int - // The schema versions from 0 to the current schema version - SchemaVersions []int - - // Whether to generate long form versions of resource sample tests - GenerateLongFormTests bool -} - -type Link struct { - text string - url string -} - -type BasePathReplacement struct { - Present bool - Old string - New string -} - -func (l Link) Markdown() string { - return fmt.Sprintf("[%s](%s)", l.text, l.url) -} - -func (r *Resource) fillLinksFromExtensionsMap(m map[string]interface{}) { - ref, ok := m["x-dcl-ref"].(map[string]interface{}) - if ok { - r.Reference = &Link{url: ref["url"].(string), text: ref["text"].(string)} - } - gs, ok := m["x-dcl-guides"].([]interface{}) - if ok { - for _, g := range gs { - guide := g.(map[interface{}]interface{}) - r.Guides = append(r.Guides, Link{url: guide["url"].(string), text: guide["text"].(string)}) - } - } -} - -// Name is the shortname of a resource. For example, "instance". -func (r Resource) Name() SnakeCaseTerraformResourceName { - return r.title -} -func (r Resource) TitleCaseFullName() TitleCaseFullName { - return TitleCaseFullName(snakeToTitleCase(concatenateSnakeCase(r.ProductName(), r.Name())).titlecase()) -} - -func (r Resource) DCLTitle() TitleCaseResourceName { - return r.dclTitle -} - -func (r Resource) DCLStructName() TitleCaseResourceName { - if r.dclStructName != "" { - return r.dclStructName - } - return r.dclTitle -} - -// TerraformName is the Terraform resource type used in HCL configuration. -// For example, "google_compute_instance" -func (r Resource) TerraformName() SnakeCaseFullName { - googlePrefix := miscellaneousNameSnakeCase("google") - if r.TerraformProductName != nil { - if r.TerraformProductName.snakecase() == "" { - return SnakeCaseFullName(concatenateSnakeCase(googlePrefix, r.Name())) - } - return SnakeCaseFullName(concatenateSnakeCase(googlePrefix, *r.TerraformProductName, r.Name())) - } - return SnakeCaseFullName(concatenateSnakeCase(googlePrefix, r.ProductName(), r.Name())) -} - -// PathType is the title-cased name of a resource preceded by its package, -// often used to namespace functions. For example, "RedisInstance". -func (r Resource) PathType() TitleCaseFullName { - return r.TitleCaseFullName() -} - -// Package is the namespace of the package within the dcl -// the Package is normally a lowercase variant of ProductName -func (r Resource) Package() DCLPackageName { - return r.productMetadata.PackageName -} - -func (r Resource) TitleCasePackageName() RenderedString { - return RenderedString(snakeToTitleCase(r.ProductName()).titlecase()) -} - -func (r Resource) DocsSection() miscellaneousNameTitleCase { - return r.productMetadata.DocsSection() -} - -// ProductName is the snakecase product name of a resource. For example, -// "network_services". -func (r Resource) ProductName() SnakeCaseProductName { - return r.productMetadata.ProductName -} - -func (r Resource) ProductMetadata() *ProductMetadata { - copy := *r.productMetadata - return © -} - -// DCLPackage is the package name of the DCL client library to use for this -// resource. For example, the Package "access_context_manager" at version GA would have a -// DCLPackage of "accesscontextmanager", and at beta would be "accesscontextmanager/beta". -func (r Resource) DCLPackage() DCLPackageNameWithVersion { - return r.productMetadata.PackageNameWithVersion() -} - -// Updatable returns true if the resource should have an update method. -// This will avoid the error message: -// "All fields are ForceNew or Computed w/out Optional, Update is superfluous" -func (r Resource) Updatable() bool { - for _, p := range r.SchemaProperties() { - if !p.ForceNew && !(!p.Optional && p.Computed) { - return true - } - } - return false -} - -// The resource has other mutable fields, besides "labels" and "terraform_labels" fields -func (r Resource) HasMutableNonLabelsFields() bool { - for _, p := range r.SchemaProperties() { - if !p.IsResourceLabels() && p.Name() != "terraform_labels" && !p.ForceNew && !(!p.Optional && p.Computed) { - return true - } - } - return false -} - -// Objects are properties with sub-properties -func (r Resource) Objects() (props []Property) { - for _, v := range r.Properties { - if len(v.Properties) != 0 { - // If this property uses a reused type, add it one-time afterwards to avoid multiple creations. - if v.ref != "" { - continue - } - props = append(props, v) - props = append(props, v.Objects()...) - } - } - - for _, v := range r.ReusedTypes { - props = append(props, v) - props = append(props, v.Objects()...) - } - - return props -} - -// SchemaProperties is the list of resource properties filtered to those included in schema. -func (r Resource) SchemaProperties() (props []Property) { - return collapsedProperties(r.Properties) -} - -// Enum arrays are not arrays of strings in the DCL and require special -// conversion -func (r Resource) EnumArrays() (props []Property) { - // Top level - for _, v := range r.Properties { - if v.Type.typ.Items != nil && len(v.Type.typ.Items.Enum) > 0 { - props = append(props, v) - } - } - // Look for nested - for _, n := range r.Objects() { - for _, v := range n.Properties { - if v.Type.typ.Items != nil && len(v.Type.typ.Items.Enum) > 0 { - props = append(props, v) - } - } - } - - return props -} - -// AdditionalGoPackages returns a sorted list of additional Go packages to import. -func (r Resource) AdditionalFileImports() []string { - sl := make([]string, 0, len(r.additionalFileImportSet)) - for k := range r.additionalFileImportSet { - sl = append(sl, k) - } - sort.Strings(sl) - return sl -} - -// If this resource has a server generated field that is used to read the -// resource. This must be set during create -func (r Resource) HasServerGeneratedName() bool { - identityFields := idParts(r.ID) - for _, p := range r.Properties { - if stringInSlice(p.Name(), identityFields) { - if !p.Settable { - return true - } - } - } - return false -} - -// SweeperFunctionArgs returns a list of arguments for calling a sweeper function. -func (r Resource) SweeperFunctionArgs() string { - vals := make([]string, 0) - for _, v := range r.ListFields { - vals = append(vals, fmt.Sprintf("d[\"%s\"]", v)) - } - - if len(vals) > 0 { - return strings.Join(vals, ",") + "," - } else { - return "" - } -} - -// Returns the name of the ID function for the Terraform resource. -func (r Resource) IDFunction() string { - for _, p := range r.Properties { - if p.forwardSlashAllowed { - return "tpgresource.ReplaceVars" - } - } - return "tpgresource.ReplaceVarsForId" -} - -// Check if the resource has the lables field for the resource -func (r Resource) HasLabels() bool { - for _, p := range r.Properties { - if p.IsResourceLabels() { - return true - } - } - return false -} - -// Check if the resource has the annotations field for the resource -func (r Resource) HasAnnotations() bool { - for _, p := range r.Properties { - if p.IsResourceAnnotations() { - return true - } - } - return false -} - -// ResourceInput is a Resource along with additional generation metadata. -type ResourceInput struct { - Resource -} - -// RegisterReusedType adds a new reused type if the type does not already exist. -func (r Resource) RegisterReusedType(p Property) []Property { - found := false - for _, v := range r.ReusedTypes { - if v.ref == p.ref { - found = true - } - } - if !found { - r.ReusedTypes = append(r.ReusedTypes, p) - } - return r.ReusedTypes -} - -func createResource(schema *openapi.Schema, info *openapi.Info, typeFetcher *TypeFetcher, overrides Overrides, product *ProductMetadata, version Version, location string) (*Resource, error) { - resourceTitle := strings.Split(info.Title, "/")[1] - - res := Resource{ - title: SnakeCaseTerraformResourceName(jsonToSnakeCase(resourceTitle).snakecase()), - dclStructName: TitleCaseResourceName(schema.Title), - dclTitle: TitleCaseResourceName(resourceTitle), - productMetadata: product, - versionMetadata: version, - Description: info.Description, - location: location, - InsertTimeoutMinutes: 20, - UpdateTimeoutMinutes: 20, - DeleteTimeoutMinutes: 20, - } - - // Since the resource's "info" extension field can't be accessed, the relevant - // extensions have been copied into the schema objects. - res.fillLinksFromExtensionsMap(schema.Extension) - - // Resource Override: Custom Timeout - ctd := CustomTimeoutDetails{} - ctdOk, err := overrides.ResourceOverrideWithDetails(CustomTimeout, &ctd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom timeout details: %v", err) - } - if ctdOk { - res.InsertTimeoutMinutes = ctd.TimeoutMinutes - res.UpdateTimeoutMinutes = ctd.TimeoutMinutes - res.DeleteTimeoutMinutes = ctd.TimeoutMinutes - } - - if overrides.ResourceOverride(SkipInProvider, location) { - res.SkipInProvider = true - } - - crname := CustomResourceNameDetails{} - crnameOk, err := overrides.ResourceOverrideWithDetails(CustomResourceName, &crname, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom resource name details: %v", err) - } - - if crnameOk { - res.title = SnakeCaseTerraformResourceName(crname.Title) - } - - id, customID, err := findResourceID(schema, overrides, location) - if err != nil { - return nil, err - } - res.ID = id - res.UseTerraformID = customID - - // Resource Override: Custom Import Function - cifd := CustomImportFunctionDetails{} - cifdOk, err := overrides.ResourceOverrideWithDetails(CustomImport, &cifd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom import function details: %v", err) - } - if cifdOk { - res.CustomImportFunction = &cifd.Function - } - - // Resource Override: Append to Base Path - atbpd := AppendToBasePathDetails{} - atbpOk, err := overrides.ResourceOverrideWithDetails(AppendToBasePath, &atbpd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode append to base path details: %v", err) - } - if atbpOk { - res.AppendToBasePath = atbpd.String - } - - // Resource Override: Replace in Base Path - ribpd := ReplaceInBasePathDetails{} - ribpOk, err := overrides.ResourceOverrideWithDetails(ReplaceInBasePath, &ribpd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode replace in base path details: %v", err) - } - if ribpOk { - res.ReplaceInBasePath.Present = true - res.ReplaceInBasePath.Old = ribpd.Old - res.ReplaceInBasePath.New = ribpd.New - } - - // Resource Override: Mutex - md := MutexDetails{} - mdOk, err := overrides.ResourceOverrideWithDetails(Mutex, &md, location) - if err != nil { - return nil, fmt.Errorf("failed to decode mutex details: %v", err) - } - if mdOk { - res.Mutex = md.Mutex - } - - props, err := createPropertiesFromSchema(schema, typeFetcher, overrides, &res, nil, location) - if err != nil { - return nil, err - } - - res.Properties = props - - onlyLongFormFormat := shouldAllowForwardSlashInFormat(res.ID, res.Properties) - // Resource Override: Import formats - ifd := ImportFormatDetails{} - ifdOk, err := overrides.ResourceOverrideWithDetails(ImportFormat, &ifd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode import format details: %v", err) - } - if ifdOk { - res.ImportFormats = ifd.Formats - } else { - res.ImportFormats = defaultImportFormats(res.ID, onlyLongFormFormat) - } - - _, res.HasProject = schema.Properties["project"] - - // Resource Override: Virtual field - for _, vfd := range overrides.ResourceOverridesWithDetails(VirtualField, location) { - vf := VirtualFieldDetails{} - if err := convert(vfd, &vf); err != nil { - return nil, fmt.Errorf("error converting type: %v", err) - } - - res.Properties = append(res.Properties, readVirtualField(vf)) - } - - // Resource-level pre and post action functions - preCreate := PreCreateFunctionDetails{} - preCreOk, err := overrides.ResourceOverrideWithDetails(PreCreate, &preCreate, location) - if err != nil { - return nil, fmt.Errorf("failed to decode pre create function details: %v", err) - } - if preCreOk { - res.PreCreateFunction = &preCreate.Function - } - - postCreate := PostCreateFunctionDetails{} - postCreOk, err := overrides.ResourceOverrideWithDetails(PostCreate, &postCreate, location) - if err != nil { - return nil, fmt.Errorf("failed to decode post create function details: %v", err) - } - if postCreOk { - res.PostCreateFunction = &postCreate.Function - } - - pd := PreDeleteFunctionDetails{} - pdOk, err := overrides.ResourceOverrideWithDetails(PreDelete, &pd, location) - if err != nil { - return nil, fmt.Errorf("failed to decode pre delete function details: %v", err) - } - if pdOk { - res.PreDeleteFunction = &pd.Function - } - - // Resource Override: Customize Diff - cdiff := CustomizeDiffDetails{} - cdOk, err := overrides.ResourceOverrideWithDetails(CustomizeDiff, &cdiff, location) - if err != nil { - return nil, fmt.Errorf("failed to decode customize diff details: %v", err) - } - - if cdOk { - res.CustomizeDiff = cdiff.Functions - } - - if res.HasLabels() { - res.CustomizeDiff = append(res.CustomizeDiff, "tpgresource.SetLabelsDiff") - } - - if res.HasAnnotations() { - res.CustomizeDiff = append(res.CustomizeDiff, "tpgresource.SetAnnotationsDiff") - } - - // ListFields - if parameters, ok := typeFetcher.doc.Paths["list"]; ok { - for _, param := range parameters.Parameters { - if param.Name != "" { - res.ListFields = append(res.ListFields, param.Name) - } - } - } - - // Determine if a resource has a create method. - res.HasCreate, _ = schema.Extension["x-dcl-has-create"].(bool) - - // Determine if a resource can use a generated sweeper or not - // We only supply a certain set of parent values to sweepers, so only generate - // one if it will actually work- resources with resource parents are not - // sweepable, in particular, such as nested resources or fine-grained - // resources. Additional special cases can be handled with overrides. - res.HasSweeper = true - validSweeperParameters := []string{"project", "region", "location", "zone", "billingAccount"} - if deleteAllInfo, ok := typeFetcher.doc.Paths["deleteAll"]; ok { - for _, p := range deleteAllInfo.Parameters { - // if any field isn't a standard sweeper parameter, don't make a sweeper - if !stringInSlice(p.Name, validSweeperParameters) { - res.HasSweeper = false - } - } - } else { - // if deleteAll wasn't found, the DCL hasn't published a sweeper - res.HasSweeper = false - } - - if overrides.ResourceOverride(NoSweeper, location) { - if res.HasSweeper == false { - return nil, fmt.Errorf("superfluous NO_SWEEPER specified for %q", res.TerraformName()) - } - - res.HasSweeper = false - } - - stateHint, ok := schema.Extension["x-dcl-uses-state-hint"].(bool) - if ok { - res.StateHint = stateHint - } - - // Resource Override: CustomCreateDirectiveFunction - createDirectiveFunc := CustomCreateDirectiveDetails{} - createDirectiveFuncOk, err := overrides.ResourceOverrideWithDetails(CustomCreateDirective, &createDirectiveFunc, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom create directive function details: %v", err) - } - if createDirectiveFuncOk { - res.CustomCreateDirectiveFunction = &createDirectiveFunc.Function - } - - // Resource Override: SkipDeleteFunction - skipDeleteFunc := SkipDeleteFunctionDetails{} - skipDeleteFuncOk, err := overrides.ResourceOverrideWithDetails(SkipDeleteFunction, &skipDeleteFunc, location) - if err != nil { - return nil, fmt.Errorf("failed to decode skip delete details: %v", err) - } - if skipDeleteFuncOk { - res.SkipDeleteFunction = &skipDeleteFunc.Function - } - - // Resource Override: SerializationOnly - res.SerializationOnly = overrides.ResourceOverride(SerializationOnly, location) - - // Resource Override: CustomSerializer - customSerializerFunc := CustomSerializerDetails{} - customSerializerFuncOk, err := overrides.ResourceOverrideWithDetails(CustomSerializer, &customSerializerFunc, location) - if err != nil { - return nil, fmt.Errorf("failed to decode custom serializer function details: %v", err) - } - if customSerializerFuncOk { - res.CustomSerializer = &customSerializerFunc.Function - } - - // Resource Override: TerraformProductName - terraformProductName := TerraformProductNameDetails{} - terraformProductNameOk, err := overrides.ResourceOverrideWithDetails(TerraformProductName, &terraformProductName, location) - if err != nil { - return nil, fmt.Errorf("failed to decode terraform product name function details: %v", err) - } - if terraformProductNameOk { - scpn := SnakeCaseProductName(terraformProductName.Product) - res.TerraformProductName = &scpn - } - - // Resource Override: StateUpgrade - stateUpgrade := StateUpgradeDetails{} - stateUpgradeOk, err := overrides.ResourceOverrideWithDetails(StateUpgrade, &stateUpgrade, location) - if err != nil { - return nil, fmt.Errorf("Failed to decode state upgrade details: %v", err) - } - if stateUpgradeOk { - res.SchemaVersion = stateUpgrade.SchemaVersion - res.SchemaVersions = make([]int, res.SchemaVersion) - for i := range res.SchemaVersions { - res.SchemaVersions[i] = i - } - } - - if overrides.ResourceOverride(GenerateLongFormTests, location) { - res.GenerateLongFormTests = true - } - - res.Samples = res.loadSamples() - - return &res, nil -} - -func readVirtualField(vf VirtualFieldDetails) Property { - prop := Property{ - title: vf.Name, - Type: Type{&openapi.Schema{Type: vf.Type}}, - } - - if vf.Type == "boolean" { - def := "false" - prop.Default = &def - } - - if vf.Output { - prop.Computed = true - } else { - prop.Optional = true - prop.Settable = true - } - return prop -} - -func (r Resource) TestSamples() []Sample { - return r.getSamples(false) -} - -func (r Resource) DocSamples() []Sample { - return r.getSamples(true) -} - -func (r Resource) getSamples(docs bool) []Sample { - out := []Sample{} - if len(r.Samples) < 1 { - return out - } - var hideList []string - if docs { - hideList = r.Samples[0].DocHide - if len(r.Samples[0].DocHideConditional) > 0 { - for _, dochidec := range r.Samples[0].DocHideConditional { - if r.location == dochidec.Location { - hideList = append(hideList, dochidec.Name) - } - } - } - } else { - hideList = r.Samples[0].Testhide - if len(r.Samples[0].TestHideConditional) > 0 { - for _, testhidec := range r.Samples[0].TestHideConditional { - if r.location == testhidec.Location { - hideList = append(hideList, testhidec.Name) - } - } - } - } - for _, sample := range r.Samples { - shouldhide := false - for _, hideName := range hideList { - if sample.FileName == hideName { - shouldhide = true - } - } - if !shouldhide { - out = append(out, sample) - } - } - - return out -} - -func (r *Resource) getSampleAccessoryFolder() Filepath { - resourceType := strings.ToLower(r.DCLTitle().titlecase()) - packageName := r.productMetadata.PackageName.lowercase() - sampleAccessoryFolder := path.Join(*tPath, packageName, "samples", resourceType) - return Filepath(sampleAccessoryFolder) -} - -func (r *Resource) loadSamples() []Sample { - samples := []Sample{} - handWritten := r.loadHandWrittenSamples() - dclSamples := r.loadDCLSamples() - samples = append(samples, dclSamples...) - samples = append(samples, handWritten...) - return samples -} - -func (r *Resource) loadHandWrittenSamples() []Sample { - sampleAccessoryFolder := r.getSampleAccessoryFolder() - sampleFriendlyMetaPath := path.Join(string(sampleAccessoryFolder), "meta.yaml") - samples := []Sample{} - - if !pathExists(sampleFriendlyMetaPath) { - return samples - } - - files, err := ioutil.ReadDir(string(sampleAccessoryFolder)) - if err != nil { - glog.Exit(err) - } - - for _, file := range files { - if fileName := strings.ToLower(file.Name()); !strings.HasSuffix(fileName, ".tf.tmpl") || - strings.Contains(fileName, "_update") { - continue - } - sample := Sample{} - sampleName := strings.Split(file.Name(), ".")[0] - sampleDefinitionFile := path.Join(string(sampleAccessoryFolder), sampleName+".yaml") - var tc []byte - if pathExists(sampleDefinitionFile) { - tc, err = mergeYaml(sampleDefinitionFile, sampleFriendlyMetaPath) - } else { - tc, err = ioutil.ReadFile(sampleFriendlyMetaPath) - } - if err != nil { - glog.Exit(err) - } - err = yaml.UnmarshalStrict(tc, &sample) - if err != nil { - glog.Exit(err) - } - - versionMatch := false - - // if no versions provided assume all versions - if len(sample.Versions) <= 0 { - sample.HasGAEquivalent = true - versionMatch = true - } else { - for _, v := range sample.Versions { - if v == r.versionMetadata.V { - versionMatch = true - } - if v == "ga" { - sample.HasGAEquivalent = true - } - } - } - - if !versionMatch { - glog.Errorf("skipping %q due to no version match", file.Name()) - continue - } - - sample.SamplesPath = sampleAccessoryFolder - sample.resourceReference = r - sample.FileName = file.Name() - sample.PrimaryResource = &(sample.FileName) - if sample.Name == nil || *sample.Name == "" { - sampleName = strings.Split(sample.FileName, ".")[0] - sample.Name = &sampleName - } - sample.TestSlug = RenderedString(snakeToTitleCase(miscellaneousNameSnakeCase(sampleName)).titlecase() + "HandWritten") - - // The "labels" and "annotations" fields in the state are decided by the configuration. - // During importing, as the configuration is unavailableafter, the "labels" and "annotations" fields in the state will be empty. - // So add the "labels" and the "annotations" fields to the ImportStateVerifyIgnore list. - if r.HasLabels() { - sample.IgnoreRead = append(sample.IgnoreRead, "labels", "terraform_labels") - } - - if r.HasAnnotations() { - sample.IgnoreRead = append(sample.IgnoreRead, "annotations") - } - - samples = append(samples, sample) - } - - return samples -} - -func (r *Resource) loadDCLSamples() []Sample { - sampleAccessoryFolder := r.getSampleAccessoryFolder() - packagePath := r.productMetadata.PackagePath - version := r.versionMetadata.V - resourceType := r.DCLTitle() - sampleFriendlyMetaPath := path.Join(string(sampleAccessoryFolder), "meta.yaml") - samples := []Sample{} - - if mode != nil && *mode == "serialization" { - return samples - } - - // Samples appear in the root product folder - packagePath = Filepath(strings.Split(string(packagePath), "/")[0]) - samplesPath := Filepath(path.Join(*fPath, string(packagePath), "samples")) - files, err := ioutil.ReadDir(string(samplesPath)) - if err != nil { - // ignore the error if the file just doesn't exist - if !os.IsNotExist(err) { - glog.Exit(err) - } - } - for _, file := range files { - if !strings.HasSuffix(file.Name(), ".yaml") { - continue - } - sample := Sample{} - sampleOGFilePath := path.Join(string(samplesPath), file.Name()) - var tc []byte - if pathExists(sampleFriendlyMetaPath) { - tc, err = mergeYaml(sampleOGFilePath, sampleFriendlyMetaPath) - } else { - glog.Errorf("warning : sample meta does not exist for %v at %q", r.TerraformName(), sampleFriendlyMetaPath) - tc, err = ioutil.ReadFile(path.Join(string(samplesPath), file.Name())) - } - if err != nil { - glog.Exit(err) - } - - err = yaml.UnmarshalStrict(tc, &sample) - if err != nil { - glog.Exit(err) - } - - versionMatch := false - for _, v := range sample.Versions { - if v == version { - versionMatch = true - } - if v == "ga" { - sample.HasGAEquivalent = true - versionMatch = true - } - } - - primaryResource := *sample.PrimaryResource - var parts []miscellaneousNameSnakeCase - parts = assertSnakeArray(strings.Split(primaryResource, ".")) - primaryResourceName := snakeToTitleCase(parts[len(parts)-2]) - - if !versionMatch { - continue - } else if !strings.EqualFold(primaryResourceName.titlecase(), resourceType.titlecase()) { - // This scenario will occur for product folders with multiple resources - continue - } - - sample.SamplesPath = samplesPath - sample.resourceReference = r - sample.FileName = file.Name() - - var dependencies []Dependency - mainResource := sample.generateSampleDependencyWithName(primaryResource, "primary") - dependencies = append(dependencies, mainResource) - for _, dFileName := range sample.DependencyFileNames { - dependency := sample.generateSampleDependency(dFileName) - dependencies = append(dependencies, dependency) - } - sample.DependencyList = dependencies - sample.TestSlug = RenderedString(sampleNameToTitleCase(*sample.Name).titlecase()) - - // The "labels" and "annotations" fields in the state are decided by the configuration. - // During importing, as the configuration is unavailable, the "labels" and "annotations" fields in the state will be empty. - // So add the "labels" and the "annotations" fields to the ImportStateVerifyIgnore list. - if r.HasLabels() { - sample.IgnoreRead = append(sample.IgnoreRead, "labels", "terraform_labels") - } - - if r.HasAnnotations() { - sample.IgnoreRead = append(sample.IgnoreRead, "annotations") - } - - if r.GenerateLongFormTests { - longFormSample := sample - longFormSample.LongForm = true - var longFormDependencies []Dependency - mainResourceLongForm := longFormSample.generateSampleDependencyWithName(primaryResource, "primary") - longFormDependencies = append(longFormDependencies, mainResourceLongForm) - for _, dFileName := range longFormSample.DependencyFileNames { - longFormDependency := sample.generateSampleDependency(dFileName) - longFormDependencies = append(longFormDependencies, longFormDependency) - } - longFormSample.DependencyList = longFormDependencies - longFormSample.TestSlug += "LongForm" - samples = append(samples, longFormSample) - } - - samples = append(samples, sample) - - } - - return samples -} diff --git a/tpgtools/sample.go b/tpgtools/sample.go deleted file mode 100644 index 561963db0867..000000000000 --- a/tpgtools/sample.go +++ /dev/null @@ -1,548 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "path" - "regexp" - "strings" - - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - "github.com/golang/glog" -) - -// Sample is the object containing sample data from DCL samples -type Sample struct { - // Name of the file the sample was loaded from - FileName string - - // Name is the name of a sample - Name *string - - // Description is a short description of the sample - Description *string - - // DependencyFileNames contains the filenames of every resource in the sample - DependencyFileNames []string `yaml:"dependencies"` - - // PrimaryResource is the filename of the sample's primary resource - PrimaryResource *string `yaml:"resource"` - - IgnoreRead []string `yaml:"ignore_read"` - - // DependencyList is a list of objects containing metadata for each sample resource - DependencyList []Dependency - - // The name of the test - TestSlug RenderedString - - // The raw versions stated in the yaml - Versions []string - - // A list of updates that the resource can transition between - Updates []Update - - // HasGAEquivalent tells us if we should have `provider = google-beta` - // in the testcase. (if the test doesn't have a ga version of the test) - HasGAEquivalent bool - - // LongForm is whether this sample is a copy with long form fields expanded to include `/` - LongForm bool - - // SamplesPath is the path to the directory where the original sample data is stored - SamplesPath Filepath - - // resourceReference is the resource the sample belongs to - resourceReference *Resource - - // CustomCheck allows you to add a terraform check function to all tests - CustomCheck []string `yaml:"check"` - - // CodeInject references reletive raw files that should be injected into the sample test - CodeInject []string `yaml:"code_inject"` - - // DocHide specifies a list of samples to hide from docs - DocHide []string `yaml:"doc_hide"` - - // DocHideConditional specifies a list of samples to hide from docs when resource location matches - DocHideConditional []DocHideCondition `yaml:"doc_hide_conditional"` - - // Testhide specifies a list of samples to hide from tests - Testhide []string `yaml:"test_hide"` - - // TesthideConditional specifies a list of samples to hide from tests when resource location matches - TestHideConditional []TestHideCondition `yaml:"test_hide_conditional"` - - // ExtraDependencies are the additional golang dependencies the injected code may require - ExtraDependencies []string `yaml:"extra_dependencies"` - - // ExternalProviders are the external providers needed for tests - ExternalProviders []string `yaml:"external_providers"` - - // Type is the resource type. - Type string `yaml:"type"` - - // Variables are the various attributes of the set of resources that need to be filled in. - Variables []Variable `yaml:"variables"` -} - -// Variable contains metadata about the types of variables in a sample. -type Variable struct { - // Name is the variable name in the JSON. - Name string `yaml:"name"` - // Type is the variable type. - Type string `yaml:"type"` - // DocsValue is an optional value that should be substituted directly into - // the documentation for this variable. If not provided, tpgtools makes - // its best guess about a suitable value. Generally, this is only provided - // if the "best guess" is a poor one. - DocsValue string `yaml:"docs_value"` -} - -type DocHideCondition struct { - // Location is the location attribute to match, if matched, append Name to list of DocHide - Location string `yaml:"location"` - // Name specifies sample file name to add to DocHide if location matches. - Name string `yaml:"file_name"` -} - -type TestHideCondition struct { - // Location is the location attribute to match, if matched, append Name to list of Testhide - Location string `yaml:"location"` - // Name specifies sample file name to add to Testhide if location matches. - Name string `yaml:"file_name"` -} - -// Dependency contains data that describes a single resource in a sample -type Dependency struct { - // FileName is the name of the file as it appears in testcases.yaml - FileName string - - // HCLLocalName is the local name of the HCL block, e.g. "basic" or "default" - HCLLocalName string - - // TerraformResourceType is the type represented in Terraform, e.g. "google_compute_instance" - TerraformResourceType string - - // HCLBlock is the snippet of HCL config that declares this resource - HCLBlock string // Path to the directory where the sample data is stored -} - -type Update struct { - // The list of dependency resources to update. - Dependencies []string `yaml:"dependencies"` - - // The resource to update. - Resource string `yaml:"resource"` -} - -func packageNameFromFilepath(fp Filepath, product SnakeCaseProductName) (DCLPackageName, error) { - pm := NewProductMetadata(fp, string(product)) - return pm.PackageName, nil -} - -func findDCLReferencePackage(product SnakeCaseProductName) (DCLPackageName, error) { - // Most packages are just the product name with all the underscores removed. - // Try that first. - // We can check if a package exists by checking the "productOverrides" map from product.go, which - // will be populated by this point. That takes a "Filepath", because the reference is to the - // actual name of the directory that contains the overrides - by mandate, that's the same as the - // dcl package name, so this conversion happens to work out. - possibleFilepath := Filepath(strings.ReplaceAll(string(product), "_", "")) - if _, ok := productOverrides[possibleFilepath]; ok { - return packageNameFromFilepath(possibleFilepath, product) - } - baseFilepath := possibleFilepath - possibleFilepath = Filepath(string(baseFilepath) + "/beta") - if _, ok := productOverrides[possibleFilepath]; ok { - return packageNameFromFilepath(possibleFilepath, product) - } - possibleFilepath = Filepath(string(baseFilepath) + "/alpha") - if _, ok := productOverrides[possibleFilepath]; ok { - return packageNameFromFilepath(possibleFilepath, product) - } - - // Otherwise, just return an error. - var productOverrideKeys []Filepath - for k := range productOverrides { - productOverrideKeys = append(productOverrideKeys, k) - } - return DCLPackageName(""), fmt.Errorf("can't find %q in the overrides map, which contains %v", product, productOverrideKeys) -} - -// BuildDependency produces a Dependency using a file and filename -func BuildDependency(fileName string, product SnakeCaseProductName, localname, version string, hasGAEquivalent, makeLongForm bool, b []byte) (*Dependency, error) { - // Miscellaneous name rather than "resource name" because this is the name in the sample json file - which might not match the TF name! - // we have to account for that. - var resourceName miscellaneousNameSnakeCase - var packageName DCLPackageName - fileParts := strings.Split(fileName, ".") - if len(fileParts) == 4 { - p, rn := fileParts[1], fileParts[2] - packageName = DCLPackageName(p) - resourceName = miscellaneousNameSnakeCase(rn) - } else if len(fileParts) == 3 { - resourceName = miscellaneousNameSnakeCase(fileParts[1]) - var err error - packageName, err = findDCLReferencePackage(product) - if err != nil { - return nil, err - } - } else { - return nil, fmt.Errorf("Invalid sample dependency file name: %s", fileName) - } - - if localname == "" { - localname = fileParts[0] - } - terraformResourceType, err := DCLToTerraformReference(packageName, resourceName, version) - if err != nil { - return nil, fmt.Errorf("Error generating sample dependency reference %s: %s", fileName, err) - } - - block, err := ConvertSampleJSONToHCL(packageName, resourceName, version, hasGAEquivalent, makeLongForm, b) - if err != nil { - glog.Errorf("failed to convert %q", fileName) - return nil, fmt.Errorf("Error generating sample dependency %s: %s", fileName, err) - } - - // Find all instances of `resource "foo" "bar"` and replace `bar` with localname. - re := regexp.MustCompile(`(resource "` + terraformResourceType + `" ")(\w*)`) - block = re.ReplaceAllString(block, "${1}"+localname) - - d := &Dependency{ - FileName: fileName, - HCLLocalName: localname, - TerraformResourceType: terraformResourceType, - HCLBlock: block, - } - return d, nil -} - -func (s *Sample) generateSampleDependency(fileName string) Dependency { - return s.generateSampleDependencyWithName(fileName, "") -} - -func (s *Sample) generateSampleDependencyWithName(fileName, localname string) Dependency { - dFileNameParts := strings.Split(fileName, "samples/") - fileName = dFileNameParts[len(dFileNameParts)-1] - dependencyBytes, err := ioutil.ReadFile(path.Join(string(s.SamplesPath), fileName)) - version := s.resourceReference.versionMetadata.V - product := s.resourceReference.productMetadata.ProductName - d, err := BuildDependency(fileName, product, localname, version, s.HasGAEquivalent, s.LongForm, dependencyBytes) - if err != nil { - glog.Exit(err) - } - return *d -} - -func (s *Sample) GetCodeToInject() []string { - sampleAccessoryFolder := s.resourceReference.getSampleAccessoryFolder() - var out []string - for _, fileName := range s.CodeInject { - filePath := path.Join(string(sampleAccessoryFolder), fileName) - tc, err := ioutil.ReadFile(filePath) - if err != nil { - glog.Exit(err) - } - out = append(out, string(tc)) - } - return out -} - -// ReplaceReferences substitutes any reference tags for their HCL address -// This should only be called after every dependency for a sample is built -func (s Sample) ReplaceReferences(d *Dependency) error { - re := regexp.MustCompile(`"?{{\s*ref:([a-z_]*\.[a-z_]*\.[a-z_]*(?:\.[a-z_]*)?):([a-zA-Z0-9_\.\[\]]*)\s*}}"?`) - matches := re.FindAllStringSubmatch(d.HCLBlock, -1) - - for _, match := range matches { - referenceFileName := match[1] - idField := dcl.TitleToSnakeCase(match[2]) - var tfReference string - for _, dep := range s.DependencyList { - if dep.FileName == referenceFileName { - tfReference = dep.TerraformResourceType + "." + dep.HCLLocalName + "." + idField - break - } - } - if tfReference == "" { - return fmt.Errorf("Could not find reference file name: %s", referenceFileName) - } - startsWithQuote := strings.HasPrefix(match[0], `"`) - endsWithQuote := strings.HasSuffix(match[0], `"`) - if !(startsWithQuote && endsWithQuote) { - tfReference = fmt.Sprintf("${%s}", tfReference) - if startsWithQuote { - tfReference = `"` + tfReference - } - if endsWithQuote { - tfReference += `"` - } - } - d.HCLBlock = strings.Replace(d.HCLBlock, match[0], tfReference, 1) - } - return nil -} - -func (s Sample) generateHCLTemplate() (string, error) { - if len(s.DependencyList) == 0 { - return "", fmt.Errorf("Could not generate HCL template for %s: there are no dependencies", *s.Name) - } - - var hcl string - for index := range s.DependencyList { - err := s.ReplaceReferences(&s.DependencyList[index]) - if err != nil { - return "", fmt.Errorf("Could not generate HCL template for %s: %s", *s.Name, err) - } - hcl = fmt.Sprintf("%s%s\n", hcl, s.DependencyList[index].HCLBlock) - } - - return hcl, nil -} - -// GenerateHCL generates sample HCL using docs substitution metadata -func (s Sample) GenerateHCL(isDocs bool) string { - var hcl string - var err error - if !s.isNativeHCL() { - hcl, err = s.generateHCLTemplate() - if err != nil { - glog.Exit(err) - } - } else { - tc, err := ioutil.ReadFile(path.Join(string(s.SamplesPath), *s.PrimaryResource)) - if err != nil { - glog.Exit(err) - } - hcl = string(tc) - } - for _, sub := range s.Variables { - re := regexp.MustCompile(fmt.Sprintf(`{{%s}}`, sub.Name)) - hcl = re.ReplaceAllString(hcl, sub.translateValue(isDocs)) - } - return hcl -} - -// isNativeHCL returns whether the resource file is terraform synatax -func (s Sample) isNativeHCL() bool { - return strings.HasSuffix(*s.PrimaryResource, ".tf.tmpl") -} - -// EnumerateWithUpdateSamples returns an array of new samples expanded with -// any subsequent samples -func (s *Sample) EnumerateWithUpdateSamples() []Sample { - out := []Sample{*s} - for i, update := range s.Updates { - newSample := *s - primaryResource := update.Resource - // TODO: Consume new dependency list. - newSample.PrimaryResource = &primaryResource - if !newSample.isNativeHCL() { - var newDeps []Dependency - newDeps = append(newDeps, newSample.generateSampleDependencyWithName(*newSample.PrimaryResource, "primary")) - for _, newDepFilename := range update.Dependencies { - newDepFilename = strings.TrimPrefix(newDepFilename, "samples/") - newDeps = append(newDeps, newSample.generateSampleDependencyWithName(newDepFilename, basicResourceName(newDepFilename))) - } - newSample.DependencyList = newDeps - } - newSample.TestSlug = RenderedString(fmt.Sprintf("%sUpdate%v", newSample.TestSlug, i)) - newSample.Updates = nil - newSample.Variables = s.Variables - out = append(out, newSample) - } - return out -} - -func basicResourceName(depFilename string) string { - re := regexp.MustCompile("^update(_\\d)?\\.") - // update_1.resource.json -> basic.resource.json - basicReplaced := re.ReplaceAllString(depFilename, "basic.") - re = regexp.MustCompile("^update(_\\d)?_") - // update_1_name.resource.json -> name.resource.json - prefixTrimmed := re.ReplaceAllString(basicReplaced, "") - return dcl.SnakeToJSONCase(strings.Split(prefixTrimmed, ".")[0]) -} - -// ExpandContext expands the context model used in the generated tests -func (s Sample) ExpandContext() map[string]string { - out := map[string]string{} - for _, sub := range s.Variables { - translation, hasTranslation := translationMap[sub.Type] - if hasTranslation { - out[translation.contextKey] = translation.contextValue - } - } - return out -} - -type translationIndex struct { - docsValue string - contextKey string - contextValue string -} - -var translationMap = map[string]translationIndex{ - "org_id": { - docsValue: "123456789", - contextKey: "org_id", - contextValue: "envvar.GetTestOrgFromEnv(t)", - }, - "org_name": { - docsValue: "example.com", - contextKey: "org_domain", - contextValue: "envvar.GetTestOrgDomainFromEnv(t)", - }, - "region": { - docsValue: "us-west1", - contextKey: "region", - contextValue: "envvar.GetTestRegionFromEnv()", - }, - "zone": { - docsValue: "us-west1-a", - contextKey: "zone", - contextValue: "envvar.GetTestZoneFromEnv()", - }, - "org_target": { - docsValue: "123456789", - contextKey: "org_target", - contextValue: "envvar.GetTestOrgTargetFromEnv(t)", - }, - "billing_account": { - docsValue: "000000-0000000-0000000-000000", - contextKey: "billing_acct", - contextValue: "envvar.GetTestBillingAccountFromEnv(t)", - }, - "test_service_account": { - docsValue: "my@service-account.com", - contextKey: "service_acct", - contextValue: "envvar.GetTestServiceAccountFromEnv(t)", - }, - "project": { - docsValue: "my-project-name", - contextKey: "project_name", - contextValue: "envvar.GetTestProjectFromEnv()", - }, - "project_number": { - docsValue: "my-project-number", - contextKey: "project_number", - contextValue: "envvar.GetTestProjectNumberFromEnv()", - }, - "customer_id": { - docsValue: "A01b123xz", - contextKey: "cust_id", - contextValue: "envvar.GetTestCustIdFromEnv(t)", - }, - // Begin a long list of multicloud-only values which are not going to see reuse. - // We can hardcode fake values because we are - // always going to use the no-provisioning mode for unit testing, of these resources - // where we don't have to actually have a real AWS account. - - "aws_account_id": { - docsValue: "012345678910", - contextKey: "aws_acct_id", - contextValue: `"111111111111"`, - }, - "aws_database_encryption_key": { - docsValue: "12345678-1234-1234-1234-123456789111", - contextKey: "aws_db_key", - contextValue: `"00000000-0000-0000-0000-17aad2f0f61f"`, - }, - "aws_region": { - docsValue: "my-aws-region", - contextKey: "aws_region", - contextValue: `"us-west-2"`, - }, - "aws_security_group": { - docsValue: "sg-00000000000000000", - contextKey: "aws_sg", - contextValue: `"sg-0b3f63cb91b247628"`, - }, - "aws_volume_encryption_key": { - docsValue: "12345678-1234-1234-1234-123456789111", - contextKey: "aws_vol_key", - contextValue: `"00000000-0000-0000-0000-17aad2f0f61f"`, - }, - "aws_vpc": { - docsValue: "vpc-00000000000000000", - contextKey: "aws_vpc", - contextValue: `"vpc-0b3f63cb91b247628"`, - }, - "aws_subnet": { - docsValue: "subnet-00000000000000000", - contextKey: "aws_subnet", - contextValue: `"subnet-0b3f63cb91b247628"`, - }, - "azure_application": { - docsValue: "12345678-1234-1234-1234-123456789111", - contextKey: "azure_app", - contextValue: `"00000000-0000-0000-0000-17aad2f0f61f"`, - }, - "azure_subscription": { - docsValue: "12345678-1234-1234-1234-123456789111", - contextKey: "azure_sub", - contextValue: `"00000000-0000-0000-0000-17aad2f0f61f"`, - }, - "azure_ad_tenant": { - docsValue: "12345678-1234-1234-1234-123456789111", - contextKey: "azure_tenant", - contextValue: `"00000000-0000-0000-0000-17aad2f0f61f"`, - }, - "azure_proxy_config_secret_version": { - docsValue: "0000000000000000000000000000000000", - contextKey: "azure_config_secret", - contextValue: `"07d4b1f1a7cb4b1b91f070c30ae761a1"`, - }, - "byo_multicloud_prefix": { - docsValue: "my-", - contextKey: "byo_prefix", - contextValue: `"mmv2"`, - }, -} - -// translateValue returns the value to embed in the hcl -func (sub *Variable) translateValue(isDocs bool) string { - value := sub.Name - translation, hasTranslation := translationMap[sub.Type] - - if isDocs { - if sub.DocsValue != "" { - return sub.DocsValue - } - if hasTranslation { - return translation.docsValue - } - if sub.Type != "resource_name" { - glog.Exitf("Cannot generate docs for variable of type %q.", sub.Type) - } - return value - } - - if hasTranslation { - return fmt.Sprintf("%%{%s}", translation.contextKey) - } - - if sub.Type != "resource_name" { - glog.Exitf("Cannot generate sample test with variable of type %q - please add to sample.go's translationMap.", sub.Type) - } - - // Use '_' if already present, or '-' otherwise (some APIs require '-'). - if strings.Contains(value, "_") { - value = fmt.Sprintf("tf_test_%s", value) - } else { - value = fmt.Sprintf("tf-test-%s", value) - } - - // Random suffix is 10 characters and standard name length <= 64 - if len(value) > 54 { - value = value[:54] - } - return fmt.Sprintf("%s%%{random_suffix}", value) -} - -func (s Sample) PrimaryResourceName() string { - fileParts := strings.Split(*s.PrimaryResource, ".") - return fileParts[0] -} diff --git a/tpgtools/serializable/serializable.go b/tpgtools/serializable/serializable.go deleted file mode 100644 index 01b29133090f..000000000000 --- a/tpgtools/serializable/serializable.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package serializable contains a function that returns the list of resources that tpgtools currently supports. -package serializable - -import ( - "path/filepath" - "regexp" -) - -// Service contains the name of a GCP service and the resources it contains in tpgtools. -type Service struct { - Name string - Resources []string -} - -// ListOfResources returns a list of resources that tpgtools currently supports. -func ListOfResources(pathPrefix string) ([]*Service, error) { - pathglob := "/api/*/*.yaml" - pathregex := `/api/(?P[a-z_-]*)/(?P[a-z_-]*).yaml` - - path := pathPrefix + pathglob - matches, err := filepath.Glob(path) - if err != nil { - return nil, err - } - var services []*Service - r := regexp.MustCompile(pathPrefix + pathregex) - for _, match := range matches { - result := r.FindAllStringSubmatch(match, -1) - if len(result) > 0 && len(result[0]) > 1 { - service := findServiceInList(result[0][1], services) - if service == nil { - services = append(services, &Service{ - Name: result[0][1], - Resources: []string{result[0][2]}, - }) - } else { - service.Resources = append(service.Resources, result[0][2]) - } - } - } - return services, nil -} -func findServiceInList(name string, services []*Service) *Service { - for _, s := range services { - if s.Name == name { - return s - } - } - return nil -} diff --git a/tpgtools/serializable/test_specs/api/compute/firewall.yaml b/tpgtools/serializable/test_specs/api/compute/firewall.yaml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tpgtools/serialization.go.base b/tpgtools/serialization.go.base deleted file mode 100644 index d29fea9ab9fd..000000000000 --- a/tpgtools/serialization.go.base +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "fmt" -) - -func DCLToTerraformReference(product DCLPackageName, resource miscellaneousNameSnakeCase, version string) (string, error) { - return "", fmt.Errorf("unimplemented - did you run `make serialize`?") -} - -func ConvertSampleJSONToHCL(product DCLPackageName, resource miscellaneousNameSnakeCase, version string, hasGAEquivalent, makeLongForm bool, b []byte) (string, error) { - return "", fmt.Errorf("unimplemented - did you run `make serialize`?") -} - -func formatHCL(hcl string) (string, error) { - return "", fmt.Errorf("unimplemented - did you run `make serialize`?") -} diff --git a/tpgtools/serialization_helpers.go b/tpgtools/serialization_helpers.go deleted file mode 100644 index e362def5319d..000000000000 --- a/tpgtools/serialization_helpers.go +++ /dev/null @@ -1,104 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "regexp" - "strings" - - cloudresourcemanager "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudresourcemanager" - cloudresourcemanagerAlpha "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudresourcemanager/alpha" - cloudresourcemanagerBeta "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudresourcemanager/beta" -) - -func serializeAlphaProjectToHCL(r cloudresourcemanagerAlpha.Project, hasGAEquivalent bool) (string, error) { - b, err := json.Marshal(r) - if err != nil { - return "", err - } - var m map[string]interface{} - if err := json.Unmarshal(b, &m); err != nil { - return "", err - } - return serializeProjectToHCL(m, hasGAEquivalent) -} - -func serializeBetaProjectToHCL(r cloudresourcemanagerBeta.Project, hasGAEquivalent bool) (string, error) { - b, err := json.Marshal(r) - if err != nil { - return "", err - } - var m map[string]interface{} - if err := json.Unmarshal(b, &m); err != nil { - return "", err - } - return serializeProjectToHCL(m, hasGAEquivalent) -} - -func serializeGAProjectToHCL(r cloudresourcemanager.Project, hasGAEquivalent bool) (string, error) { - b, err := json.Marshal(r) - if err != nil { - return "", err - } - var m map[string]interface{} - if err := json.Unmarshal(b, &m); err != nil { - return "", err - } - return serializeProjectToHCL(m, hasGAEquivalent) -} - -func serializeProjectToHCL(m map[string]interface{}, hasGAEquivalent bool) (string, error) { - outputConfig := "resource \"google_project\" \"output\" {\n" - if name, ok := m["name"]; ok { - outputConfig += fmt.Sprintf("\tproject_id = %#v\n", name) - outputConfig += fmt.Sprintf("\tname = %#v\n", name) - } else { - return "", fmt.Errorf("project id was not provided") - } - if parentInterface, ok := m["parent"]; ok { - parent, ok := parentInterface.(string) - if !ok { - return "", fmt.Errorf("non-string parent %v", parentInterface) - } - if strings.HasPrefix(parent, "folders/") { - outputConfig += fmt.Sprintf("\tfolder_id = %#v\n", strings.TrimPrefix(parent, "folders/")) - } else if strings.HasPrefix(parent, "organizations/") { - outputConfig += fmt.Sprintf("\torg_id = %#v\n", strings.TrimPrefix(parent, "organizations/")) - } else { - return "", fmt.Errorf("unknown parent type %v", parent) - } - } else { - return "", fmt.Errorf("parent was not provided") - } - formatted, err := formatHCL(outputConfig + "}") - if err != nil { - // The formatter will not accept the google-beta symbol because it is injected during testing. - return "", err - } - if !hasGAEquivalent { - return withProviderLine(formatted), nil - } - return formatted, nil -} - -// Returns the terraform representation of a three-state boolean value represented by a pointer to bool in DCL. -func serializeEnumBool(v interface{}) string { - b, ok := v.(*bool) - if !ok || b == nil { - return "" - } - if *b { - return "TRUE" - } - return "FALSE" -} - -// Returns the given formatted hcl with the provider = google-beta line added at the end. -func withProviderLine(hcl string) string { - // Count the number of characters before the first = to determine how to space the provider line. - equalsPosition := len(regexp.MustCompile(".*=").FindString(hcl)) - 1 - if equalsPosition < 11 { - equalsPosition = 11 - } - return hcl[0:len(hcl)-2] + " provider" + strings.Repeat(" ", equalsPosition-10) + "= google-beta\n}" -} diff --git a/tpgtools/strings.go b/tpgtools/strings.go deleted file mode 100644 index 80e748292ca4..000000000000 --- a/tpgtools/strings.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "regexp" - "strings" - - "github.com/golang/glog" -) - -// Map from initialism -> TitleCase variant -// We can assume camelCase is the same as TitleCase except that we downcase the -// first segment -var initialisms = map[string]string{ - "ip": "IP", - "ipv4": "IPv4", - "ipv6": "IPv6", - "oauth": "OAuth", - "oauth2": "OAuth2", - "tpu": "TPU", - "vpc": "VPC", -} - -func assertSnakeArray(ss []string) []miscellaneousNameSnakeCase { - var sc []miscellaneousNameSnakeCase - for _, s := range ss { - if strings.ToLower(s) != s { - glog.Exitf("assertion failed: snake case value not in snake case. %q != %q (same string passed to ToLower).", s, strings.ToLower(s)) - } - sc = append(sc, miscellaneousNameSnakeCase(s)) - } - return sc -} - -func concatenateSnakeCase(s ...snakeCaseName) miscellaneousNameSnakeCase { - var names []string - for _, n := range s { - names = append(names, n.snakecase()) - } - return miscellaneousNameSnakeCase(strings.Join(names, "_")) -} - -// snakeToParts returns the parts of a snake_case string absent of '_' -// if titleCase is true these segents will have their first letter capitalized -func snakeToParts(s snakeCaseName, titleCase bool) []string { - parts := []string{} - segments := strings.Split(s.snakecase(), "_") - for _, seg := range segments { - if v, ok := initialisms[seg]; ok { - parts = append(parts, v) - } else { - var newPart string = seg - if titleCase && len(newPart) > 0 { - newPart = strings.ToUpper(newPart[0:1]) + newPart[1:] - } - parts = append(parts, newPart) - } - } - - return parts -} - -// jsonToSnakeCase converts a jsonCase string to snake_case. -func jsonToSnakeCase(s string) miscellaneousNameSnakeCase { - for _, v := range initialisms { - s = strings.ReplaceAll(s, v, v[0:1]+strings.ToLower(v[1:])) - } - result := regexp.MustCompile("(.)([A-Z][^A-Z]+)").ReplaceAllString(s, "${1}_${2}") - return miscellaneousNameSnakeCase(strings.ToLower(regexp.MustCompile("([a-z0-9])([A-Z])").ReplaceAllString(result, "${1}_${2}"))) -} - -func sampleNameToTitleCase(s string) miscellaneousNameTitleCase { - return miscellaneousNameTitleCase(strings.Join(sampleNameToTitleParts(s), "")) -} - -func sampleNameToTitleParts(s string) []string { - parts := []string{} - s = strings.ReplaceAll(s, "/", " ") - s = strings.ReplaceAll(s, "_", " ") - segments := strings.Split(s, " ") - for _, seg := range segments { - if v, ok := initialisms[seg]; ok { - parts = append(parts, v) - } else { - parts = append(parts, strings.ToUpper(seg[0:1])+seg[1:]) - } - } - - return parts -} diff --git a/tpgtools/templates/provider_dcl_client_creation.go.tmpl b/tpgtools/templates/provider_dcl_client_creation.go.tmpl deleted file mode 100644 index 7dc752a4955c..000000000000 --- a/tpgtools/templates/provider_dcl_client_creation.go.tmpl +++ /dev/null @@ -1,99 +0,0 @@ -{{/* Copyright 2021 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */}} -// Copyright IBM Corp. 2014, 2026 -// SPDX-License-Identifier: MPL-2.0 - -// ---------------------------------------------------------------------------- -// -// *** AUTO GENERATED CODE *** Type: DCL *** -// -// ---------------------------------------------------------------------------- -// -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. -// -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose -// -// ---------------------------------------------------------------------------- - -package transport - -import ( - "fmt" - "log" - "time" - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" -{{range $index, $pkg := .}} - {{$pkg.PackageName}} "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/{{$pkg.PackageNameWithVersion}}" -{{- end}} -) - -{{range $index, $pkg := .}} -func NewDCL{{$pkg.ProductName.ToTitle}}Client(config *Config, userAgent, billingProject string, timeout time.Duration) *{{$pkg.PackageName}}.Client { - configOptions := []dcl.ConfigOption{ - dcl.WithHTTPClient(config.Client), - dcl.WithUserAgent(userAgent), - dcl.WithLogger(dclLogger{}), - dcl.WithBasePath(config.{{$pkg.BasePathIdentifier.ToTitle}}BasePath), - } - - if (timeout != 0){ - configOptions = append(configOptions, dcl.WithTimeout(timeout)) - } - - if config.UserProjectOverride { - configOptions = append(configOptions, dcl.WithUserProjectOverride()) - if billingProject != "" { - configOptions = append(configOptions, dcl.WithBillingProject(billingProject)) - } - } - - dclConfig := dcl.NewConfig(configOptions...) - return {{$pkg.PackageName}}.NewClient(dclConfig) -} -{{end}} - -type dclLogger struct{} - -// Fatal records Fatal errors. -func (l dclLogger) Fatal(args ...interface{}) { - log.Fatal(args...) -} - -// Fatalf records Fatal errors with added arguments. -func (l dclLogger) Fatalf(format string, args ...interface{}) { - log.Fatalf(fmt.Sprintf("[DEBUG][DCL FATAL] %s", format), args...) -} - -// Info records Info errors. -func (l dclLogger) Info(args ...interface{}) { - log.Print(args...) -} - -// Infof records Info errors with added arguments. -func (l dclLogger) Infof(format string, args ...interface{}) { - log.Printf(fmt.Sprintf("[DEBUG][DCL INFO] %s", format), args...) -} - -// Warningf records Warning errors with added arguments. -func (l dclLogger) Warningf(format string, args ...interface{}) { - log.Printf(fmt.Sprintf("[DEBUG][DCL WARNING] %s", format), args...) -} - -// Warning records Warning errors. -func (l dclLogger) Warning(args ...interface{}) { - log.Print(args...) -} \ No newline at end of file diff --git a/tpgtools/templates/provider_dcl_resources.go.tmpl b/tpgtools/templates/provider_dcl_resources.go.tmpl deleted file mode 100644 index ceb790f28a38..000000000000 --- a/tpgtools/templates/provider_dcl_resources.go.tmpl +++ /dev/null @@ -1,50 +0,0 @@ -{{/* Copyright 2022 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */}} -// Copyright IBM Corp. 2014, 2026 -// SPDX-License-Identifier: MPL-2.0 - -// ---------------------------------------------------------------------------- -// -// *** AUTO GENERATED CODE *** Type: DCL *** -// -// ---------------------------------------------------------------------------- -// -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. -// -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose -// -// ---------------------------------------------------------------------------- - -package provider - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - {{- range $res := . }} - {{- if not $res.SkipInProvider }} - "github.com/hashicorp/terraform-provider-google/google/services/{{$res.Package}}" - {{- end }} - {{- end }} -) - -var dclResources = map[string]*schema.Resource{ -{{- range $res := . }} - {{- if not $res.SkipInProvider }} - "{{$res.TerraformName}}": {{$res.Package}}.Resource{{$res.PathType}}(), - {{- end }} -{{- end }} -} - diff --git a/tpgtools/templates/resource.go.tmpl b/tpgtools/templates/resource.go.tmpl deleted file mode 100644 index 0e8603906ffb..000000000000 --- a/tpgtools/templates/resource.go.tmpl +++ /dev/null @@ -1,866 +0,0 @@ -{{/* Copyright 2021 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */}} -// Copyright IBM Corp. 2014, 2026 -// SPDX-License-Identifier: MPL-2.0 - -// ---------------------------------------------------------------------------- -// -// *** AUTO GENERATED CODE *** Type: DCL *** -// -// ---------------------------------------------------------------------------- -// -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. -// -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose -// -// ---------------------------------------------------------------------------- - -package {{$.Package}} - -import( - "context" - "fmt" - "log" -{{- if $.ReplaceInBasePath.Present }} - "strings" -{{- end }} - "time" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -{{- if $.CustomizeDiff }} - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" -{{- end }} -{{- range $pkg := $.AdditionalFileImports }} - "{{ $pkg }}" -{{- end }} - - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - {{$.Package}} "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/{{$.DCLPackage}}" - - "github.com/hashicorp/terraform-provider-google/google/tpgdclresource" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func Resource{{$.PathType}}() *schema.Resource { - return &schema.Resource{ - Create: resource{{$.PathType}}Create, - Read: resource{{$.PathType}}Read, -{{- if $.Updatable }} - Update: resource{{$.PathType}}Update, -{{- end }} - Delete: resource{{$.PathType}}Delete, - - Importer: &schema.ResourceImporter{ - State: resource{{$.PathType}}Import, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout({{$.InsertTimeoutMinutes}} * time.Minute), -{{- if $.Updatable }} - Update: schema.DefaultTimeout({{$.UpdateTimeoutMinutes}} * time.Minute), -{{- end }} - Delete: schema.DefaultTimeout({{$.DeleteTimeoutMinutes}} * time.Minute), - }, - -{{- if $.CustomizeDiff }} - CustomizeDiff: customdiff.All( - {{- range $cdf := $.CustomizeDiff }} - {{$cdf }}, - {{- end }} - ), -{{- end }} - -{{- if gt $.SchemaVersion 0 }} - SchemaVersion: {{$.SchemaVersion}}, - StateUpgraders: []schema.StateUpgrader{ - {{- range $v := $.SchemaVersions }} - { - Type: resource{{$.PathType}}ResourceV{{$v}}().CoreConfigSchema().ImpliedType(), - Upgrade: Resource{{$.PathType}}UpgradeV{{$v}}, - Version: {{$v}}, - }, - {{- end }} - }, -{{- end }} - - Schema: map[string]*schema.Schema{ -{{- range $p := $.SchemaProperties }} - "{{$p.Name}}": { - Type: schema.{{$p.Type}}, - {{- if $p.Required }} - Required: true, - {{- end }} - {{- if $p.Computed }} - Computed: true, - {{- end }} - {{- if $p.Optional }} - Optional: true, - {{- end }} - {{- if $p.ForceNew }} - ForceNew: true, - {{- end }} - {{- if $p.Sensitive}} - Sensitive: true, - {{- end }} - {{- if $p.WriteOnly }} - WriteOnly: true, - {{- end }} - {{- if $p.DiffSuppressFunc }} - DiffSuppressFunc: {{$p.DiffSuppressFunc}}, - {{- end }} - Description: "{{escapeDescription $p.Description}}", - {{- if $p.MaxItems }} - MaxItems: {{$p.MaxItems}}, - {{- end }} - {{- if $p.MinItems }} - MinItems: {{$p.MinItems}}, - {{- end }} - {{- if $p.Elem }} - Elem: {{$p.Elem}}, - {{- end }} - {{- if $p.Default }} - Default: {{$p.Default}}, - {{- end }} - {{- if $p.ConflictsWith }} - ConflictsWith: {{$p.ConflictsWith}}, - {{- end }} - {{- if $p.ValidateFunc }} - ValidateFunc: {{$p.ValidateFunc}}, - {{- end }} - {{- if $p.SetHashFunc }} - Set: {{$p.SetHashFunc}}, - {{- end }} - {{- if $p.ConfigMode }} - ConfigMode: {{$p.ConfigMode}}, - {{- end }} - {{- if $p.Removed }} - Removed: "{{$p.Removed}}", - {{- end }} - {{- if $p.Deprecated }} - Deprecated: "{{$p.Deprecated}}", - {{- end }} - }, -{{ end }} - }, - } -} - -{{ range $v := .Objects }} - {{ if $v.ShouldGenerateNestedSchema }} -func {{$.PathType}}{{$v.PackagePath}}Schema() *schema.Resource { - return &schema.Resource{ - Schema: map[string]*schema.Schema{ - {{- range $p := $v.Properties }} - "{{$p.Name}}": { - Type: schema.{{$p.Type}}, - {{- if $p.Required }} - Required: true, - {{- end }} - {{- if $p.Computed }} - Computed: true, - {{- end }} - {{- if $p.Optional }} - Optional: true, - {{- end }} - {{- if $p.ForceNew }} - ForceNew: true, - {{- end }} - {{- if $p.Sensitive }} - Sensitive: true, - {{- end }} - {{- if $p.WriteOnly }} - WriteOnly: true, - {{- end }} - {{- if $p.DiffSuppressFunc }} - DiffSuppressFunc: {{$p.DiffSuppressFunc}}, - {{- end }} - Description: "{{escapeDescription $p.Description}}", - {{- if $p.MaxItems }} - MaxItems: {{$p.MaxItems}}, - {{- end }} - {{- if $p.MinItems }} - MinItems: {{$p.MinItems}}, - {{- end }} - {{- if $p.Elem }} - Elem: {{$p.Elem}}, - {{- end }} - {{- if $p.Default }} - Default: {{$p.Default}}, - {{- end }} - {{- if $p.ConflictsWith }} - ConflictsWith: {{$p.ConflictsWith}}, - {{- end }} - {{- if $p.ValidateFunc }} - ValidateFunc: {{$p.ValidateFunc}}, - {{- end }} - {{- if $p.SetHashFunc }} - Set: {{$p.SetHashFunc}}, - {{- end }} - {{- if $p.ConfigMode }} - ConfigMode: {{$p.ConfigMode}}, - {{- end }} - {{- if $p.Removed }} - Removed: "{{$p.Removed}}", - {{- end }} - {{- if $p.Deprecated }} - Deprecated: "{{$p.Deprecated}}", - {{- end }} - }, - {{ end }} - }, - } -} - {{ end -}} -{{ end }} - -func resource{{$.PathType}}Create(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) - -{{- range $v := .Properties }} - {{- if and ($v.IdentityGetter) ($v.Settable) }} - {{$v.Name}}, err := {{$v.IdentityGetter}} - if err != nil { - return err - } - {{- end -}} -{{ end }} - - obj := &{{$.Package}}.{{$.DCLStructName}}{ -{{- range $v := .Properties }} - {{- if and ($v.Settable) ($v.StateGetter) }} - {{$v.PackageName}}: {{$v.StateGetter}}, - {{- end -}} -{{ end }} - } - -{{- if $.Mutex }} - lockName, err := {{ $.IDFunction }}(d, config, "{{$.Mutex}}") - if err != nil { - return err - } - transport_tpg.MutexStore.Lock(lockName) - defer transport_tpg.MutexStore.Unlock(lockName) -{{ end }} - -{{ if $.PreCreateFunction }} - if err := {{$.PreCreateFunction}}(d, config, obj); err != nil { - return fmt.Errorf("error encountered in pre-create: %v", err) - } -{{ end }} - -{{- if $.UseTerraformID }} -{{/* TODO: When the DCL can correctly handle IDs for regional/global splits, all resources -should be converted to use the DCL's ID method, so normalization can be uniform. */}} - id, err := {{ $.IDFunction }}(d, config, "{{$.ID}}") -{{- else }} - id, err := obj.ID() -{{- end }} - if err != nil { - return fmt.Errorf("error constructing id: %s", err) - } - d.SetId(id) - -{{- if $.CustomCreateDirectiveFunction }} - directive := {{ $.CustomCreateDirectiveFunction }}(obj) -{{- else if $.HasCreate }} - directive := tpgdclresource.CreateDirective -{{- else }} - {{/* Resource has no create method, so we skip the BlockModification parameter. */}} - directive := tpgdclresource.UpdateDirective -{{- end }} - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) - if err != nil { - return err - } -{{- if $.HasProject }} - billingProject := project -{{- else }} - billingProject := "" -{{- end}} - // err == nil indicates that the billing_project value was found - if bp, err := tpgresource.GetBillingProject(d, config); err == nil { - billingProject = bp - } - client := transport_tpg.NewDCL{{$.TitleCasePackageName}}Client(config, userAgent, billingProject, d.Timeout(schema.TimeoutCreate)) - {{- if $.AppendToBasePath }} - client.Config.BasePath += "{{$.AppendToBasePath}}" - {{- end }} - {{- if $.ReplaceInBasePath.Present }} - client.Config.BasePath = strings.ReplaceAll(client.Config.BasePath, "{{$.ReplaceInBasePath.Old}}", "{{$.ReplaceInBasePath.New}}") - {{- end }} - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp - } - res, err := client.Apply{{$.DCLTitle}}(context.Background(), obj, directive...) - - if _, ok := err.(dcl.DiffAfterApplyError); ok { - log.Printf("[DEBUG] Diff after apply returned from the DCL: %s", err) - } else if err != nil { - // The resource didn't actually create - d.SetId("") - return fmt.Errorf("Error creating {{$.DCLTitle}}: %s", err) - } - -{{ if $.HasServerGeneratedName}} - {{ range $v := .Properties -}} - {{- if ($v.IsServerGeneratedName) }} - if err = {{$v.StateSetter}}; err != nil { - return fmt.Errorf("error setting {{$v.Name}} in state: %s", err) - } - {{- end -}} - {{- end }} - // ID has a server-generated value, set again after creation. - {{ if $.UseTerraformID }} - id, err = {{ $.IDFunction }}(d, config, "{{$.ID}}") - if err != nil { - return fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - {{ else }} - id, err = res.ID() - if err != nil { - return fmt.Errorf("error constructing id: %s", err) - } - d.SetId(id) - {{ end}} -{{ end }} - - log.Printf("[DEBUG] Finished creating {{$.DCLTitle}} %q: %#v", d.Id(), res) - -{{ if $.PostCreateFunction }} - if err := {{$.PostCreateFunction}}(d, config, res); err != nil { - return fmt.Errorf("error encountered in post-create: %v", err) - } -{{ end }} - - return resource{{$.PathType}}Read(d, meta) -} - -func resource{{$.PathType}}Read(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) - -{{- range $v := .Properties }} - {{- if $v.IdentityGetter }} - {{$v.Name}}, err := {{$v.IdentityGetter}} - if err != nil { - return err - } - {{- end -}} -{{ end }} - - obj := &{{$.Package}}.{{$.DCLStructName}}{ -{{- range $v := .Properties }} - {{- if ($v.StateGetter) }} - {{$v.PackageName}}: {{$v.StateGetter}}, - {{- end -}} -{{ end }} - } - - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) - if err != nil { - return err - } -{{- if $.HasProject }} - billingProject := project -{{- else }} - billingProject := "" -{{- end}} - // err == nil indicates that the billing_project value was found - if bp, err := tpgresource.GetBillingProject(d, config); err == nil { - billingProject = bp - } - client := transport_tpg.NewDCL{{$.TitleCasePackageName}}Client(config, userAgent, billingProject, d.Timeout(schema.TimeoutRead)) - {{- if $.AppendToBasePath }} - client.Config.BasePath += "{{$.AppendToBasePath}}" - {{- end }} - {{- if $.ReplaceInBasePath.Present }} - client.Config.BasePath = strings.ReplaceAll(client.Config.BasePath, "{{$.ReplaceInBasePath.Old}}", "{{$.ReplaceInBasePath.New}}") - {{- end }} - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp - } - res, err := client.Get{{$.DCLTitle}}(context.Background(), obj) - if err != nil { - resourceName := fmt.Sprintf("{{$.PathType}} %q", d.Id()) - return tpgdclresource.HandleNotFoundDCLError(err, d, resourceName) - } - -{{ range $v := .Properties -}} - {{- if ($v.StateSetter) }} - if err = {{$v.StateSetter}}; err != nil { - return fmt.Errorf("error setting {{$v.Name}} in state: %s", err) - } - {{- end -}} -{{- end }} - - return nil -} - -{{- if $.Updatable }} -func resource{{$.PathType}}Update(d *schema.ResourceData, meta interface{}) error { -{{- if $.HasMutableNonLabelsFields }} - config := meta.(*transport_tpg.Config) - -{{- range $v := .Properties }} - {{- if and ($v.IdentityGetter) ($v.Settable) }} - {{$v.Name}}, err := {{$v.IdentityGetter}} - if err != nil { - return err - } - {{- end -}} -{{ end }} - - obj := &{{$.Package}}.{{$.DCLStructName}}{ -{{- range $v := .Properties }} - {{- if ($v.StateGetter) }} - {{$v.PackageName}}: {{$v.StateGetter}}, - {{- end -}} -{{ end }} - } - -{{- if $.StateHint }} - // Construct state hint from old values - old := &{{$.Package}}.{{$.DCLStructName}}{ - {{- range $v := .Properties }} - {{- if ($v.StateGetter) }} - {{$v.PackageName}}: {{$v.ChangeStateGetter}}, - {{- end }} - {{- end }} - } -{{- end }} - -{{- if $.Mutex }} - lockName, err := {{ $.IDFunction }}(d, config, "{{$.Mutex}}") - if err != nil { - return err - } - transport_tpg.MutexStore.Lock(lockName) - defer transport_tpg.MutexStore.Unlock(lockName) - -{{ end }} - directive := tpgdclresource.UpdateDirective - {{- if $.StateHint }} - directive = append(directive, dcl.WithStateHint(old)) - {{- end }} - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) - if err != nil { - return err - } - - billingProject := "" - // err == nil indicates that the billing_project value was found - if bp, err := tpgresource.GetBillingProject(d, config); err == nil { - billingProject = bp - } - client := transport_tpg.NewDCL{{$.TitleCasePackageName}}Client(config, userAgent, billingProject, d.Timeout(schema.TimeoutUpdate)) - {{- if $.AppendToBasePath }} - client.Config.BasePath += "{{$.AppendToBasePath}}" - {{- end }} - {{- if $.ReplaceInBasePath.Present }} - client.Config.BasePath = strings.ReplaceAll(client.Config.BasePath, "{{$.ReplaceInBasePath.Old}}", "{{$.ReplaceInBasePath.New}}") - {{- end }} - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp - } - res, err := client.Apply{{$.DCLTitle}}(context.Background(), obj, directive...) - - if _, ok := err.(dcl.DiffAfterApplyError); ok { - log.Printf("[DEBUG] Diff after apply returned from the DCL: %s", err) - } else if err != nil { - // The resource didn't actually create - d.SetId("") - return fmt.Errorf("Error updating {{$.DCLTitle}}: %s", err) - } - - log.Printf("[DEBUG] Finished creating {{$.DCLTitle}} %q: %#v", d.Id(), res) - -{{- else }} - // Only the root field "labels" and "terraform_labels" are mutable -{{- end }} - - return resource{{$.PathType}}Read(d, meta) -} -{{- end }} - -func resource{{$.PathType}}Delete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) - -{{- range $v := .Properties }} - {{- if $v.IdentityGetter }} - {{$v.Name}}, err := {{$v.IdentityGetter}} - if err != nil { - return err - } - {{- end -}} -{{ end }} - - obj := &{{$.Package}}.{{$.DCLStructName}}{ -{{- range $v := .Properties }} - {{- if ($v.StateGetter) }} - {{$v.PackageName}}: {{$v.StateGetter}}, - {{- end -}} -{{ end }} - } - -{{- if $.Mutex }} - lockName, err := {{ $.IDFunction }}(d, config, "{{$.Mutex}}") - if err != nil { - return err - } - transport_tpg.MutexStore.Lock(lockName) - defer transport_tpg.MutexStore.Unlock(lockName) - -{{ end }} -{{ if $.PreDeleteFunction }} - if err := {{$.PreDeleteFunction}}(d, config, obj); err != nil { - return fmt.Errorf("error encountered in pre-delete: %v", err) - } -{{ end }} - -{{- if $.SkipDeleteFunction }} - skip, err := {{$.SkipDeleteFunction}}(config, obj) - if err != nil { - return fmt.Errorf("error encountered in skip-delete: %v", err) - } - if skip { - return nil - } -{{- end }} - - log.Printf("[DEBUG] Deleting {{$.DCLTitle}} %q", d.Id()) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) - if err != nil { - return err - } -{{- if $.HasProject }} - billingProject := project -{{- else }} - billingProject := "" -{{- end}} - // err == nil indicates that the billing_project value was found - if bp, err := tpgresource.GetBillingProject(d, config); err == nil { - billingProject = bp - } - client := transport_tpg.NewDCL{{$.TitleCasePackageName}}Client(config, userAgent, billingProject, d.Timeout(schema.TimeoutDelete)) -{{- if $.AppendToBasePath }} - client.Config.BasePath += "{{$.AppendToBasePath}}" -{{- end }} -{{- if $.ReplaceInBasePath.Present }} - client.Config.BasePath = strings.ReplaceAll(client.Config.BasePath, "{{$.ReplaceInBasePath.Old}}", "{{$.ReplaceInBasePath.New}}") -{{- end }} - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp - } - if err := client.Delete{{$.DCLTitle}}(context.Background(), obj); err != nil { - return fmt.Errorf("Error deleting {{$.DCLTitle}}: %s", err) - } - - log.Printf("[DEBUG] Finished deleting {{$.DCLTitle}} %q", d.Id()) - return nil -} - -func resource{{$.PathType}}Import(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - config := meta.(*transport_tpg.Config) -{{ if $.CustomImportFunction }} - if err := {{$.CustomImportFunction}}(d, config); err != nil { - return nil, fmt.Errorf("error encountered in import: %v", err) - } -{{ else -}} - {{$allowForwardSlash := shouldAllowForwardSlashInFormat $.ID $.Properties}} - if err := tpgresource.ParseImportId([]string{ - {{- range $format := $.ImportFormats }} - "{{patternToRegex $format $allowForwardSlash}}", - {{- end }} - }, d, config); err != nil { - return nil, err - } - - // Replace import id for the resource id - id, err := {{ $.IDFunction }}(d, config, "{{$.ID}}") - if err != nil { - return nil, fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - {{- range $v := .Properties }} - {{- if and (not $v.StateSetter) ($v.Default) }} - d.Set("{{$v.Name}}", {{$v.Default}}) - {{- end -}} - {{ end }} - -{{ end }} - return []*schema.ResourceData{d}, nil -} - -{{ range $v := .Objects -}} - {{ if $v.Settable -}} - {{ if $v.Collapsed -}} -func expand{{$.PathType}}{{$v.PackagePath}}Collapsed(d *schema.ResourceData) *{{$.Package}}.{{$v.ObjectType}} { - collapsed := {{$.Package}}.{{$v.ObjectType}}{ - {{- range $p := $v.Properties }} - {{- if and ($p.Settable) ($p.StateGetter) }} - {{$p.PackageName}}: {{$p.StateGetter}}, - {{- end -}} - {{ end }} - } - // Return nil if empty - if ({{$.Package}}.{{$v.ObjectType}}{}) == collapsed { - return nil - } - return &collapsed -} - {{ else -}} - - {{ if $v.IsArray -}} -func expand{{$.PathType}}{{$v.PackagePath}}Array(o interface{}) []{{$.Package}}.{{$v.ObjectType}} { - if o == nil { - {{- if $v.Computed }} - return nil - {{- else }} - return make([]{{$.Package}}.{{$v.ObjectType}}, 0) - {{- end }} - } - - {{ if $v.IsSet -}} - o = o.(*schema.Set).List() - {{- end }} - - objs := o.([]interface{}) - if len(objs) == 0 || objs[0] == nil { - {{- if $v.Computed }} - return nil - {{- else }} - return make([]{{$.Package}}.{{$v.ObjectType}}, 0) - {{- end }} - } - - items := make([]{{$.Package}}.{{$v.ObjectType}}, 0, len(objs)) - for _, item := range objs { - i := expand{{$.PathType}}{{$v.PackagePath}}(item) - items = append(items, *i) - } - - return items -} - {{- end }} - - {{ if $v.IsComplexMap -}} -func expand{{$.PathType}}{{$v.PackagePath}}Map(o interface{}) map[string]{{$.Package}}.{{$v.ObjectType}} { - if o == nil { - {{- if $v.Computed }} - return nil - {{- else }} - return make(map[string]{{$.Package}}.{{$v.ObjectType}}) - {{- end }} - } - - o = o.(*schema.Set).List() - - objs := o.([]interface{}) - if len(objs) == 0 || objs[0] == nil { - {{- if $v.Computed }} - return nil - {{- else }} - return make(map[string]{{$.Package}}.{{$v.ObjectType}}) - {{- end }} - } - - items := make(map[string]{{$.Package}}.{{$v.ObjectType}}) - for _, item := range objs { - i := expand{{$.PathType}}{{$v.PackagePath}}(item) - if item != nil { - items[item.(map[string]interface{})["{{$v.ComplexMapKeyName}}"].(string)] = *i - } - } - - return items -} - {{- end }} - -func expand{{$.PathType}}{{$v.PackagePath}}(o interface{}) *{{$.Package}}.{{$v.ObjectType}} { - if o == nil { - {{- if $v.Computed }} - return nil - {{- else }} - return {{$.Package}}.Empty{{$v.ObjectType}} - {{- end }} - } - {{ if $v.IsObject -}} - objArr := o.([]interface{}) - if len(objArr) == 0 || objArr[0] == nil { - {{- if $v.Computed }} - return nil - {{- else }} - return {{$.Package}}.Empty{{$v.ObjectType}} - {{- end }} - } - obj := objArr[0].(map[string]interface{}) - {{- else }} - obj := o.(map[string]interface{}) - {{- end }} - return &{{$.Package}}.{{$v.ObjectType}}{ - {{- range $p := $v.Properties }} - {{- if and ($p.Settable) ($p.ExpandGetter) (or (not $v.IsComplexMap) (ne $p.Name $v.ComplexMapKeyName)) }} - {{$p.PackageName}}: {{$p.ExpandGetter}}, - {{- end -}} - {{ end }} - } -} - {{- end }} -{{- end }} - - {{ if $v.IsArray -}} -func flatten{{$.PathType}}{{$v.PackagePath}}Array(objs []{{$.Package}}.{{$v.ObjectType}}) []interface{} { - if objs == nil { - return nil - } - - items := []interface{}{} - for _, item := range objs { - i := flatten{{$.PathType}}{{$v.PackagePath}}(&item) - items = append(items, i) - } - - return items -} - {{- end }} - - {{ if $v.IsComplexMap -}} -func flatten{{$.PathType}}{{$v.PackagePath}}Map(objs map[string]{{$.Package}}.{{$v.ObjectType}}) []interface{} { - if objs == nil { - return nil - } - - items := []interface{}{} - for name, item := range objs { - i := flatten{{$.PathType}}{{$v.PackagePath}}(&item, name) - items = append(items, i) - } - - return items -} - {{- end }} - -func flatten{{$.PathType}}{{$v.PackagePath}}(obj *{{$.Package}}.{{$v.ObjectType}}{{- if $v.IsComplexMap -}}, name string{{- end -}}) interface{} { - if obj == nil {{- if not $v.IsComplexMap -}}|| obj.Empty(){{- end -}}{ - return nil - } - transformed := map[string]interface{}{ -{{- range $p := $v.Properties }} - {{- if or (not $v.IsComplexMap) (ne $p.Name $v.ComplexMapKeyName) }} - "{{$p.Name}}": {{$p.FlattenGetter}}, - {{- end -}} -{{ end }} - } -{{ if $v.IsComplexMap }} - transformed["{{$v.ComplexMapKeyName}}"] = name -{{ end }} -{{ if $v.IsObject }} - return []interface{}{transformed} -{{ else }} - return transformed -{{ end }} -} -{{ end -}} - -{{ if $.HasLabels }} -func flatten{{$.PathType}}Labels(v map[string]string, d *schema.ResourceData) interface{} { - if v == nil { - return nil - } - - transformed := make(map[string]interface{}) - if l, ok := d.Get("labels").(map[string]interface{}); ok { - for k := range l { - transformed[k] = v[k] - } - } - - return transformed -} - -func flatten{{$.PathType}}TerraformLabels(v map[string]string, d *schema.ResourceData) interface{} { - if v == nil { - return nil - } - - transformed := make(map[string]interface{}) - if l, ok := d.Get("terraform_labels").(map[string]interface{}); ok { - for k := range l { - transformed[k] = v[k] - } - } - - return transformed -} -{{ end }} - -{{ if $.HasAnnotations }} -func flatten{{$.PathType}}Annotations(v map[string]string, d *schema.ResourceData) interface{} { - if v == nil { - return nil - } - - transformed := make(map[string]interface{}) - if l, ok := d.Get("annotations").(map[string]interface{}); ok { - for k := range l { - transformed[k] = v[k] - } - } - - return transformed -} -{{ end }} - -{{ range $v := .EnumArrays -}} -func flatten{{$.PathType}}{{$v.PackagePath}}Array(obj []{{$.Package}}.{{$v.ObjectType}}Enum) interface{} { - if obj == nil { - return nil - } - items := []string{} - for _, item := range obj { - items = append(items, string(item)) - } - return items -} - - {{- if $v.Settable }} -func expand{{$.PathType}}{{$v.PackagePath}}Array(o interface{}) []{{$.Package}}.{{$v.ObjectType}}Enum { - objs := o.([]interface{}) - items := make([]{{$.Package}}.{{$v.ObjectType}}Enum, 0, len(objs)) - for _, item := range objs { - i := {{$.Package}}.{{$v.ObjectType}}EnumRef(item.(string)) - items = append(items, *i) - } - return items -} - {{- end }} -{{ end }} - diff --git a/tpgtools/templates/resource.html.markdown.tmpl b/tpgtools/templates/resource.html.markdown.tmpl deleted file mode 100644 index 7e3b8a4e1d06..000000000000 --- a/tpgtools/templates/resource.html.markdown.tmpl +++ /dev/null @@ -1,176 +0,0 @@ -{{- /* Copyright 2021 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */ -}} ---- -# ---------------------------------------------------------------------------- -# -# *** AUTO GENERATED CODE *** Type: DCL *** -# -# ---------------------------------------------------------------------------- -# -# This file is managed by Magic Modules (https:#github.com/GoogleCloudPlatform/magic-modules) -# and is based on the DCL (https:#github.com/GoogleCloudPlatform/declarative-resource-client-library). -# Changes will need to be made to the DCL or Magic Modules instead of here. -# -# We are not currently able to accept contributions to this file. If changes -# are required, please file an issue at https:#github.com/hashicorp/terraform-provider-google/issues/new/choose -# -# ---------------------------------------------------------------------------- -subcategory: "{{$.DocsSection}}" -description: |- - {{$.Description}} ---- - -# {{ $.TerraformName }} - -{{$.Description}} -{{if or $.Reference $.Guides}} -For more information, see: -{{- if $.Reference }} -* {{$.Reference.Markdown}} -{{- end }} -{{- range $g := $.Guides }} -* {{$g.Markdown}} -{{- end }} -{{- end }} - -{{- /* TODO warning */}} -{{- range $s := $.DocSamples}} -## Example Usage - {{$s.Name}} -{{- if $s.Description}} -{{$s.Description}} -{{- end }} -```hcl -{{ $s.GenerateHCL true }} -``` -{{- end }} - -## Argument Reference - -The following arguments are supported: -{{ range $p := $.SchemaProperties }} - {{- if $p.Required }} -* `{{$p.Name}}` - - (Required) - {{$p.Description}} - {{- if ($p.Default) }} - Default value is {{$p.Default}}. - {{- end }} - {{ end }} -{{- end }} - -{{ range $v := $.Objects }} - {{- if and ($v.Required) ($v.IsTopLevel) ($v.ShouldGenerateNestedSchema) }} -The `{{$v.Name}}` block supports: - {{ range $p := $v.Properties }} -* `{{$p.Name}}` - - {{- if $p.Required }} - (Required) - {{- end }} - {{- if $p.Optional }} - (Optional) - {{- end }} - {{$p.Description}} - {{- if $p.Default }} - Default value is {{$p.Default}}. - {{- end }} - {{ end }} - {{- end }} -{{- end }} -- - - -{{ range $p := $.SchemaProperties }} - {{- if $p.Optional }} -* `{{$p.Name}}` - - (Optional) - {{$p.Description}} - {{- if ($p.Default) }} - Default value is {{$p.Default}}. - {{- end }} - {{ end }} -{{- end }} - -{{ range $v := $.Objects }} - {{- if and (or ($v.Optional) (and ($v.Required) (not $v.IsTopLevel))) ($v.ShouldGenerateNestedSchema) }} -The `{{$v.Name}}` block supports: - {{ range $p := $v.Properties }} -* `{{$p.Name}}` - - {{- if $p.Required }} - (Required) - {{- end }} - {{- if $p.Optional }} - (Optional) - {{- end }} - {{$p.Description}} - {{- if $p.Default }} - Default value is {{$p.Default}}. - {{- end }} - {{ end }} - {{- end }} -{{- end }} -## Attributes Reference - -In addition to the arguments listed above, the following computed attributes are exported: - -* `id` - an identifier for the resource with format `{{$.ID}}` -{{ range $p := $.SchemaProperties }} - {{- if and ($p.Computed) (and (not $p.Required) (not $p.Optional)) }} -* `{{$p.Name}}` - - {{$p.Description}} - {{ end }} -{{- end }} -## Timeouts - -This resource provides the following -[Timeouts](https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/retries-and-customizable-timeouts) configuration options: - -- `create` - Default is {{$.InsertTimeoutMinutes}} minutes. -{{- if $.Updatable }} -- `update` - Default is {{$.UpdateTimeoutMinutes}} minutes. -{{- end }} -- `delete` - Default is {{$.DeleteTimeoutMinutes}} minutes. - -## Import -{{/* TODO excluded imports */}} -{{$.DCLTitle}} can be imported using any of these accepted formats: - -{{- $id := "" }} -{{- range $format := $.ImportFormats }} -{{- $id = $format }} -* `{{$format}}` -{{- end }} - -In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import {{$.DCLTitle}} using one of the formats above. For example: - -{{- range $format := $.ImportFormats }} -{{/* Get the first import format for templating */}} -{{- $id = $format }} -{{- break }} -{{- end }} - -```tf -import { - id = "{{$id}}" - to = {{$.TerraformName}}.default -} -``` - -When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), {{$.DCLTitle}} can be imported using one of the formats above. For example: - -``` -{{- range $format := $.ImportFormats }} -$ terraform import {{$.TerraformName}}.default {{$format}} -{{- end }} -``` - -{{/* TODO project overrides */}} - diff --git a/tpgtools/templates/serialization.go.tmpl b/tpgtools/templates/serialization.go.tmpl deleted file mode 100644 index 46044ce9582d..000000000000 --- a/tpgtools/templates/serialization.go.tmpl +++ /dev/null @@ -1,306 +0,0 @@ -{{/* Copyright 2021 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */}} -// Copyright IBM Corp. 2014, 2026 -// SPDX-License-Identifier: MPL-2.0 - -// ---------------------------------------------------------------------------- -// -// *** AUTO GENERATED CODE *** Type: DCL *** -// -// ---------------------------------------------------------------------------- -// -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. -// -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose -// -// ---------------------------------------------------------------------------- - -package main - -import ( - "bytes" - "encoding/json" - "fmt" - "sort" - "strings" - - fmtcmd "github.com/hashicorp/hcl/hcl/fmtcmd" -{{- range $name, $path := $.Packages }} - {{$name}} "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/{{$path}}" -{{- end }} -) - -// DCLToTerraformReference converts a DCL resource name to the final tpgtools name -// after overrides are applied -func DCLToTerraformReference(product DCLPackageName, resource miscellaneousNameSnakeCase, version string) (string, error) { - {{- range $version, $resList := $.Resources }} - {{- if not (eq $version.V "ga") }} - if version == "{{$version.V}}" { - switch fmt.Sprintf("%s/%s", product, resource) { - {{- range $res := $resList }} - case "{{$res.Package}}/{{$res.Name}}": - return "{{$res.TerraformName}}", nil - {{- end }} - } - } - {{- else }} - // If not found in sample version, fallthrough to GA - switch fmt.Sprintf("%s/%s", product, resource) { - {{- range $res := $resList }} - case "{{$res.Package}}/{{$res.Name}}": - return "{{$res.TerraformName}}", nil - {{- end }} - default: - return "", fmt.Errorf("Error retrieving Terraform name from DCL resource type: %s/%s not found", product, resource) - } - {{ end }} - {{- end }} -} - -// ConvertSampleJSONToHCL unmarshals json to an HCL string. -func ConvertSampleJSONToHCL(product DCLPackageName, resource miscellaneousNameSnakeCase, version string, hasGAEquivalent, makeLongForm bool, b []byte) (string, error) { - {{- range $version, $resList := $.Resources }} - {{- if not (eq $version.V "ga") }} - if version == "{{$version.V}}" { - switch fmt.Sprintf("%s/%s", product, resource) { - {{- range $res := $resList }} - case "{{$res.Package}}/{{$res.Name}}": - r := &{{$res.Package}}{{$version.SerializationSuffix}}.{{$res.DCLStructName}}{} - if err := json.Unmarshal(b, r); err != nil { - return "", err - } - {{- if $res.CustomSerializer }} - return {{$res.CustomSerializer}}(*r, hasGAEquivalent) - {{- else }} - return {{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}AsHCL(*r, hasGAEquivalent, makeLongForm) - {{- end }} - {{- end }} - } - } - {{- else }} - // If not found in sample version, fallthrough to GA - switch fmt.Sprintf("%s/%s", product, resource) { - {{- range $res := $resList }} - case "{{$res.Package}}/{{$res.Name}}": - r := &{{$res.Package}}{{$version.SerializationSuffix}}.{{$res.DCLStructName}}{} - if err := json.Unmarshal(b, r); err != nil { - return "", err - } - {{- if $res.CustomSerializer }} - return {{$res.CustomSerializer}}(*r, hasGAEquivalent) - {{- else }} - return {{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}AsHCL(*r, hasGAEquivalent, makeLongForm) - {{- end }} - {{- end }} - default: - return "", fmt.Errorf("Error converting sample JSON to HCL: %s not found", product, resource) - } - {{ end }} - {{- end }} - -} - - -{{- range $version, $resList := $.Resources }} - {{- range $res := $resList }} -// {{ $res.TitleCaseFullName }}{{$version.SerializationSuffix}}AsHCL returns a string representation of the specified resource in HCL. -// The generated HCL will include every settable field as a literal - that is, no -// variables, no references. This may not be the best possible representation, but -// the crucial point is that `terraform import; terraform apply` will not produce -// any changes. We do not validate that the resource specified will pass terraform -// validation unless is an object returned from the API after an Apply. -func {{ $res.TitleCaseFullName }}{{$version.SerializationSuffix}}AsHCL(r {{$res.Package}}{{$version.SerializationSuffix}}.{{$res.DCLStructName}}, hasGAEquivalent, makeLongForm bool) (string, error) { - outputConfig := "resource \"{{$res.TerraformName}}\" \"output\" {\n" - {{- range $field := $res.Properties}} - {{- if $field.ShouldShowUpInSamples }} - {{- if eq $field.Type.String "TypeString" "TypeInt" "TypeBool" "TypeFloat" }} - {{- if $field.Type.IsDateTime }} - if !r.{{$field.PackageName}}.IsZero() { - outputConfig += fmt.Sprintf("\t{{$field.Name}} = %v\n", r.{{$field.PackageName}}) - } - {{- else if $field.EnumBool }} - if r.{{$field.PackageName}} != nil { - outputConfig += fmt.Sprintf("\t{{$field.Name}} = %q\n", serializeEnumBool(r.{{$field.PackageName}})) - } - {{- else }} - if r.{{$field.PackageName}} != nil { - {{- if or $field.Parameter $field.HasLongForm }} - if makeLongForm { - outputConfig += fmt.Sprintf("\t{{$field.Name}} = %#v\n", "long/form/" + *r.{{$field.PackageName}}) - } else { - outputConfig += fmt.Sprintf("\t{{$field.Name}} = %#v\n", *r.{{$field.PackageName}}) - } - {{- else }} - outputConfig += fmt.Sprintf("\t{{$field.Name}} = %#v\n", *r.{{$field.PackageName}}) - {{- end }} - } - {{- end}} - {{- else if $field.Type.IsObject }} - if v := convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$field.PackagePath}}ToHCL(r.{{$field.PackageName}}); v != "" { - {{- if $field.Collapsed }} - outputConfig += v - {{- else }} - outputConfig += fmt.Sprintf("\t{{$field.Name}} %s\n", v) - {{- end }} - } - {{- else if eq $field.Type.String "TypeList" "TypeSet" }} - if r.{{$field.PackageName}} != nil { - {{- if $field.ElemIsBasicType }} - outputConfig += "\t{{$field.Name}} = [" - for _, v := range r.{{$field.PackageName}} { - outputConfig += fmt.Sprintf("%#v, ", v) - } - outputConfig += "]\n" - {{- else }} - for _, v := range r.{{$field.PackageName}} { - outputConfig += fmt.Sprintf("\t{{$field.Name}} %s\n", convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$field.PackagePath}}ToHCL(&v)) - } - {{- end }} - } - {{- else if eq $field.Type.String "TypeMap" }} - {{- /* TODO: Implement maps with non-string values */}} - outputConfig += "{{ if not $field.Collapsed }}\t{{end}}{{$field.Name}} = {" - keys{{$field.PackageName}} := []string{} - // golang range goes over maps in an arbitrary order- we've gotta order the - // keys ourselves to make the output deterministic - for k, _ := range r.{{$field.PackageName}} { - keys{{$field.PackageName}} = append(keys{{$field.PackageName}}, k) - } - - sort.Strings(keys{{$field.PackageName}}) - - for _, k := range keys{{$field.PackageName}} { - outputConfig += fmt.Sprintf("%v = %q, ", k, r.{{$field.PackageName}}[k]) - } - outputConfig += "}\n" - {{- end}} - {{- end}} - {{- end}} - formatted, err := formatHCL(outputConfig + "}") - if err != nil { - return "", err - } - if !hasGAEquivalent { - // The formatter will not accept the google-beta symbol because it is injected during testing. - return withProviderLine(formatted), nil - } - return formatted, nil -} - - {{ range $v := $res.Objects}} -func convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$v.PackagePath}}ToHCL(r *{{$res.Package}}{{$version.SerializationSuffix}}.{{$v.ObjectType}}) string { - if r == nil { - return "" - } - outputConfig := "{{ if not $v.Collapsed }}{\n{{end}}" - {{- range $field := $v.Properties}} - {{- if $field.Settable }} - {{- if eq $field.Type.String "TypeString" "TypeInt" "TypeBool" "TypeFloat" }} - {{- if $field.EnumBool }} - if r.{{$field.PackageName}} != nil { - outputConfig += fmt.Sprintf("{{ if not $v.Collapsed }}\t{{end}}{{$field.Name}} = %q\n", serializeEnumBool(r.{{$field.PackageName}})) - } - {{- else }} - if r.{{$field.PackageName}} != nil { - outputConfig += fmt.Sprintf("{{ if not $v.Collapsed }}\t{{end}}{{$field.Name}} = %#v\n", *r.{{$field.PackageName}}) - } - {{- end }} - {{- else if $field.Type.IsObject }} - if v := convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$field.PackagePath}}ToHCL(r.{{$field.PackageName}}); v != "" { - outputConfig += fmt.Sprintf("{{ if not $v.Collapsed }}\t{{end}}{{$field.Name}} %s\n", v) - } - {{- else if eq $field.Type.String "TypeList" "TypeSet" }} - if r.{{$field.PackageName}} != nil { - {{- if $field.ElemIsBasicType }} - outputConfig += "{{ if not $v.Collapsed }}\t{{end}}{{$field.Name}} = [" - for _, v := range r.{{$field.PackageName}} { - outputConfig += fmt.Sprintf("%#v, ", v) - } - outputConfig += "]\n" - {{- else }} - for _, v := range r.{{$field.PackageName}} { - outputConfig += fmt.Sprintf("{{ if not $v.Collapsed }}\t{{end}}{{$field.Name}} %s\n", convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$field.PackagePath}}ToHCL(&v)) - } - {{- end }} - } - {{- else if eq $field.Type.String "TypeMap" }} - {{- /* TODO: Implement maps with non-string values */}} - outputConfig += "{{ if not $field.Collapsed }}\t{{end}}{{$field.Name}} = {" - keys{{$field.PackageName}} := []string{} - // golang range goes over maps in an arbitrary order- we've gotta order the - // keys ourselves to make the output deterministic - for k, _ := range r.{{$field.PackageName}} { - keys{{$field.PackageName}} = append(keys{{$field.PackageName}}, k) - } - - sort.Strings(keys{{$field.PackageName}}) - - for _, k := range keys{{$field.PackageName}} { - outputConfig += fmt.Sprintf("%v = %q, ", k, r.{{$field.PackageName}}[k]) - } - outputConfig += "}\n" - {{- end}} - {{- end}} - {{- end}} - return outputConfig{{ if not $v.Collapsed }} + "}"{{end}} -} - - {{ end }} - {{- end }} -{{- end }} -{{- range $version, $resList := $.Resources }} - {{- range $res := $resList }} - {{- range $v := $res.Objects }} -func convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$v.PackagePath}}(i interface{}) (map[string]interface{}) { - if i == nil { - return nil - } - in := i.(map[string]interface{}) - return map[string]interface{}{ - {{- range $prop := $v.Properties }} - {{- if $prop.IsObject }} - "{{$prop.PackageJSONName}}": convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$prop.PackagePath}}(in["{{$prop.Name}}"]), - {{- else }} - "{{$prop.PackageJSONName}}": in["{{$prop.Name}}"], - {{- end }} - {{- end }} - } -} - - -func convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$v.PackagePath}}List(i interface{}) (out []map[string]interface{}) { - if i == nil { - return nil - } - - for _, v := range i.([]interface{}) { - out = append(out, convert{{$res.TitleCaseFullName}}{{$version.SerializationSuffix}}{{$v.PackagePath}}(v)) - } - return out -} - {{ end }} - {{- end }} -{{- end }} - -func formatHCL(hcl string) (string, error) { - b := bytes.Buffer{} - r := strings.NewReader(hcl) - if err := fmtcmd.Run(nil, nil, r, &b, fmtcmd.Options{}); err != nil { - return "", err - } - return b.String(), nil -} diff --git a/tpgtools/templates/sweeper.go.tmpl b/tpgtools/templates/sweeper.go.tmpl deleted file mode 100644 index d5351e559726..000000000000 --- a/tpgtools/templates/sweeper.go.tmpl +++ /dev/null @@ -1,86 +0,0 @@ -{{/* Copyright 2021 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */}} -// Copyright IBM Corp. 2014, 2026 -// SPDX-License-Identifier: MPL-2.0 - -// ---------------------------------------------------------------------------- -// -// *** AUTO GENERATED CODE *** Type: DCL *** -// -// ---------------------------------------------------------------------------- -// -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. -// -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose -// -// ---------------------------------------------------------------------------- - -package {{$.Package}} - -import( - "context" - "log" - "testing" - - {{$.Package}} "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/{{$.DCLPackage}}" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" - "github.com/hashicorp/terraform-provider-google/google/envvar" - "github.com/hashicorp/terraform-provider-google/google/sweeper" -) - -func init() { - sweeper.AddTestSweepersLegacy("{{$.TitleCaseFullName}}", testSweep{{$.TitleCaseFullName}}) -} - -func testSweep{{$.TitleCaseFullName}}(region string) error { - log.Print("[INFO][SWEEPER_LOG] Starting sweeper for {{$.TitleCaseFullName}}") - - config, err := sweeper.SharedConfigForRegion(region) - if err != nil { - log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) - return err - } - - err = config.LoadAndValidate(context.Background()) - if err != nil { - log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) - return err - } - - t := &testing.T{} - billingId := envvar.GetTestBillingAccountFromEnv(t) - - // Setup variables to be used for Delete arguments. - d := map[string]string{ - "project":config.Project, - "region":region, - "location":region, - "zone":"-", - "billing_account":billingId, - } - - client := transport_tpg.NewDCL{{$.TitleCasePackageName}}Client(config, config.UserAgent, "", 0) - err = client.DeleteAll{{$.DCLTitle}}(context.Background(), {{$.SweeperFunctionArgs}} isDeletable{{$.TitleCaseFullName}}) - if err != nil { - return err - } - return nil -} - -func isDeletable{{$.TitleCaseFullName}}(r *{{$.Package}}.{{$.DCLStructName}}) bool { - return sweeper.IsSweepableTestResource(*r.Name) -} diff --git a/tpgtools/templates/test_file.go.tmpl b/tpgtools/templates/test_file.go.tmpl deleted file mode 100644 index a3e4aabc77ec..000000000000 --- a/tpgtools/templates/test_file.go.tmpl +++ /dev/null @@ -1,155 +0,0 @@ -{{/* Copyright 2021 Google LLC. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. */}} -// Copyright IBM Corp. 2014, 2026 -// SPDX-License-Identifier: MPL-2.0 - -// ---------------------------------------------------------------------------- -// -// *** AUTO GENERATED CODE *** Type: DCL *** -// -// ---------------------------------------------------------------------------- -// -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. -// -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose -// -// ---------------------------------------------------------------------------- - -package {{$.Package}}_test - -import ( - "context" - "fmt" - "strings" - "testing" -{{$s := index ($.TestSamples) 0 -}} -{{- range $extra_d := $s.ExtraDependencies -}} - "{{ $extra_d}}" -{{ end -}} - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - {{$.Package}} "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/{{$.DCLPackage}}" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/terraform" - - "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/envvar" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -{{- range $s := $.TestSamples }} -func TestAcc{{$.PathType}}_{{$s.TestSlug}}(t *testing.T) { - t.Parallel() - - context := map[string]interface{} { - {{- range $contextkey, $contextvalue := $s.ExpandContext }} - "{{$contextkey}}" : {{$contextvalue}}, - {{- end }} - "random_suffix": acctest.RandString(t, 10), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - {{ if $s.HasGAEquivalent -}} - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - {{- else }} - ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), - {{- end }} - {{- range $external_p := $s.ExternalProviders }} - ExternalProviders: map[string]resource.ExternalProvider{ - "{{ $external_p }}": {}, - }, - {{- end }} - {{ if true -}} - CheckDestroy: testAccCheck{{$.PathType}}DestroyProducer(t), - {{- end }} - Steps: []resource.TestStep{ - {{- range $se := $s.EnumerateWithUpdateSamples }} - { - Config: testAcc{{$.PathType}}_{{$se.TestSlug}}(context), - {{- if $se.CustomCheck }} - Check: resource.ComposeTestCheckFunc( - {{- range $index, $check := $se.CustomCheck -}} - {{ $check }} {{- if isLastIndex $se.CustomCheck $index }}, {{end -}} - {{- end }} - ), - {{- end }} - }, - { - ResourceName: "{{$.TerraformName}}.primary", - ImportState: true, - ImportStateVerify: true, - {{ if $se.IgnoreRead -}} - ImportStateVerifyIgnore: []string{ {{- range $ignoreReadValue := $se.IgnoreRead -}}"{{$ignoreReadValue}}", {{- end -}} }, - {{- end }} - }, - {{- end }} - }, - }) -} -{{- end }} - -{{$s := index ($.TestSamples) 0 -}} -{{- range $cti := $s.GetCodeToInject }} -{{ $cti }} -{{ end }} - -{{- range $s := $.TestSamples -}} -{{ range $se := $s.EnumerateWithUpdateSamples }} -func testAcc{{$.PathType}}_{{$se.TestSlug}}(context map[string]interface{}) string { - return acctest.Nprintf(` -{{ $se.GenerateHCL false }} -`, context) -} -{{ end }} -{{- end }} - -func testAccCheck{{$.PathType}}DestroyProducer(t *testing.T) func(s *terraform.State) error { - return func(s *terraform.State) error { - for name, rs := range s.RootModule().Resources { - if rs.Type != "rs.{{$.TerraformName}}" { - continue - } - if strings.HasPrefix(name, "data.") { - continue - } - - config := acctest.GoogleProviderConfig(t) - - billingProject := "" - if config.BillingProject != "" { - billingProject = config.BillingProject - } - - obj := &{{$.Package}}.{{$.DCLStructName}}{ - {{- range $v := .Properties }} - {{- if $v.StateGetterForDestroyTest }} - {{$v.PackageName}}: {{ $v.StateGetterForDestroyTest }}, - {{- end }} - {{- end }} - } - - client := transport_tpg.NewDCL{{$.TitleCasePackageName}}Client(config, config.UserAgent, billingProject, 0) - _, err := client.Get{{$.DCLTitle}}(context.Background(), obj) - if err == nil { - return fmt.Errorf("{{$.TerraformName}} still exists %v", obj) - } - } - return nil - } -} - - diff --git a/tpgtools/type.go b/tpgtools/type.go deleted file mode 100644 index 0e1a43a4342c..000000000000 --- a/tpgtools/type.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "fmt" - - "github.com/nasa9084/go-openapi" -) - -const ( - SchemaTypeBool = "TypeBool" - SchemaTypeInt = "TypeInt" - SchemaTypeList = "TypeList" - SchemaTypeMap = "TypeMap" - SchemaTypeString = "TypeString" - SchemaTypeFloat = "TypeFloat" - SchemaTypeSet = "TypeSet" -) - -// Type is the type of a TPG property. -type Type struct { - // The raw string value of the type. - typ *openapi.Schema -} - -// IsObject returns whether a Type represents an object type. This is useful to -// disambiguate arrays from nested objects, both of which map to SchemaTypeList -// in terms of Terraform typing. -func (t Type) IsObject() bool { - return t.String() == SchemaTypeList && t.typ.Type == "object" -} - -func (t Type) IsEnum() bool { - return len(t.typ.Enum) > 0 -} - -// Enum arrays are different from string arrays, and must be parsed differently -func (t Type) IsEnumArray() bool { - return t.typ.Items != nil && len(t.typ.Items.Enum) > 0 -} - -// String returns the Terraform type of the Type. -func (t Type) String() string { - switch t.typ.Type { - case "boolean": - return SchemaTypeBool - case "string": - return SchemaTypeString - case "integer": - return SchemaTypeInt - case "number": - if t.typ.Format == "double" { - return SchemaTypeFloat - } - return "unknown number type" - case "object": - if t.typ.AdditionalProperties != nil { - if v := t.typ.AdditionalProperties.Type; v == "string" { - return SchemaTypeMap - } else { - // Complex maps are handled as sets with an extra value for the - // name of the object - return SchemaTypeSet - } - } - return SchemaTypeList - case "array": - if t.typ.Extension["x-dcl-list-type"] == "set" { - return SchemaTypeSet - } - return SchemaTypeList - case "": - return "" - default: - return fmt.Sprintf("undefined type: %s", t.typ) - } -} - -// IsDateTime returns true if the field in question is an openapi "date-time". -func (t Type) IsDateTime() bool { - return t.typ.Format == "date-time" -} diff --git a/tpgtools/versions.go b/tpgtools/versions.go deleted file mode 100644 index e8f3f9809922..000000000000 --- a/tpgtools/versions.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2021 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import "github.com/golang/glog" - -type Version struct { - V string - Order int - SerializationSuffix string -} - -func fromString(v string) *Version { - for _, version := range allVersions() { - if v == version.V { - return &version - } - } - switch v { - case "nightly": - return &BETA_VERSION - case "private", "internal": - return &ALPHA_VERSION - } - glog.Infof("Failed finding version: %s", v) - return nil -} - -type VersionOrder int - -const ( - GA = iota - BETA - ALPHA -) - -var GA_VERSION = Version{V: "ga", Order: GA, SerializationSuffix: ""} -var BETA_VERSION = Version{V: "beta", Order: BETA, SerializationSuffix: "Beta"} -var ALPHA_VERSION = Version{V: "alpha", Order: ALPHA, SerializationSuffix: "Alpha"} - -func allVersions() []Version { - return []Version{GA_VERSION, BETA_VERSION, ALPHA_VERSION} -}