terraform: refactor tasks into provider-specific modules
PATCH 1/1 terraform: refactor tasks into provider-specific modules
The terraform role's main.yml had grown to nearly 800 lines with Lambda Labs and DataCrunch provider-specific logic interleaved throughout the file. This made maintenance difficult and required understanding the entire file to make changes for a single provider.
This refactoring creates a plugin-like architecture where each cloud provider's unique requirements are isolated in dedicated task files. The new structure separates concerns by operation (bringup, destroy) and by provider (lambdalabs, datacrunch, generic), making it straightforward to add support for new providers or modify existing ones without risk of breaking other providers.
Common functionality shared across all providers, such as SSH configuration and status reporting, is now cleanly separated in a common directory. This follows patterns already established in other roles like bootlinux and guestfs.
--- .../terraform/tasks/bringup/datacrunch.yml | 441 ++++++++++ .../roles/terraform/tasks/bringup/generic.yml | 12 + .../terraform/tasks/bringup/lambdalabs.yml | 222 +++++ .../roles/terraform/tasks/bringup/main.yml | 27 + .../terraform/tasks/common/ssh-config.yml | 37 + .../roles/terraform/tasks/common/status.yml | 35 + .../terraform/tasks/destroy/datacrunch.yml | 67 ++ .../roles/terraform/tasks/destroy/generic.yml | 12 + .../roles/terraform/tasks/destroy/main.yml | 26 + playbooks/roles/terraform/tasks/main.yml | 779 +----------------- 10 files changed, 893 insertions(+), 765 deletions(-) create mode 100644 playbooks/roles/terraform/tasks/bringup/datacrunch.yml create mode 100644 playbooks/roles/terraform/tasks/bringup/generic.yml create mode 100644 playbooks/roles/terraform/tasks/bringup/lambdalabs.yml create mode 100644 playbooks/roles/terraform/tasks/bringup/main.yml create mode 100644 playbooks/roles/terraform/tasks/common/ssh-config.yml create mode 100644 playbooks/roles/terraform/tasks/common/status.yml create mode 100644 playbooks/roles/terraform/tasks/destroy/datacrunch.yml create mode 100644 playbooks/roles/terraform/tasks/destroy/generic.yml create mode 100644 playbooks/roles/terraform/tasks/destroy/main.yml
playbooks/roles/terraform/tasks/bringup/datacrunch.yml new file +441 -0
@@ -0,0 +1,441 @@ +--- +# DataCrunch provider bringup tasks +# Provider installation, tier-based instance selection, capacity checking, terraform apply + +- name: Set DataCrunch provider architecture + ansible.builtin.set_fact: + datacrunch_provider_arch: "{{ 'amd64' if ansible_architecture == 'x86_64' else ansible_architecture }}" + tags: + - bringup + - destroy + - status + +- name: Check if DataCrunch terraform provider is already installed + ansible.builtin.stat: + path: >- + ~/.terraform.d/plugins/registry.terraform.io/linux-kdevops/datacrunch/0.0.3/{{ + ansible_system | lower }}_{{ datacrunch_provider_arch }}/terraform-provider-datacrunch_v0.0.3 + register: datacrunch_provider_installed + tags: + - bringup + - destroy + - status + +- name: Download and install DataCrunch terraform provider from GitHub releases + ansible.builtin.shell: + cmd: | + PROVIDER_VERSION="0.0.3" + PROVIDER_OS="{{ ansible_system | lower }}" + PROVIDER_ARCH="{{ datacrunch_provider_arch }}" + PROVIDER_DIR="$HOME/.terraform.d/plugins/registry.terraform.io/linux-kdevops/datacrunch" + PROVIDER_DIR="${PROVIDER_DIR}/${PROVIDER_VERSION}/${PROVIDER_OS}_${PROVIDER_ARCH}" + PROVIDER_FILE="terraform-provider-datacrunch_${PROVIDER_VERSION}_${PROVIDER_OS}_${PROVIDER_ARCH}" + GITHUB_URL="https://github.com/linux-kdevops/terraform-provider-datacrunch/releases" + + mkdir -p "${PROVIDER_DIR}" + cd "${PROVIDER_DIR}" + + # Download the provider binary + wget -q "${GITHUB_URL}/download/v${PROVIDER_VERSION}/${PROVIDER_FILE}.zip" + + # Extract the binary + unzip -o "${PROVIDER_FILE}.zip" + + # Clean up zip file + rm "${PROVIDER_FILE}.zip" + + # Make it executable + chmod +x terraform-provider-datacrunch_v${PROVIDER_VERSION} + + echo "DataCrunch provider v${PROVIDER_VERSION} installed to ${PROVIDER_DIR}" + changed_when: true + when: + - not datacrunch_provider_installed.stat.exists + tags: + - bringup + - destroy + - status + +- name: Auto-select instance type for tier-based wildcards + ansible.builtin.shell: + cmd: | + set -o pipefail + case "{{ terraform_datacrunch_instance_type }}" in + B300_OR_LESS|B200_OR_LESS|H100_OR_LESS|A100_80_OR_LESS|A100_40_OR_LESS) + # Use tier-based selection script + tier_group=$(echo "{{ terraform_datacrunch_instance_type }}" | \ + tr '[:upper:]' '[:lower:]' | tr '_' '-') + {{ topdir_path }}/scripts/datacrunch_select_tier.py "$tier_group" --verbose + ;; + ANY_1H100) + # Legacy H100 variant selection - check all regions + for variant in 1H100.80S.30V 1H100.80S.32V; do + result=$({{ topdir_path }}/scripts/datacrunch_check_capacity.py \ + --instance-type "$variant" --json 2>/dev/null || echo "[]") + location=$(echo "$result" | python3 -c " + import sys, json + data=json.load(sys.stdin) + print(data[0]['location']) if data and len(data) > 0 else '' + " 2>/dev/null) + if [ -n "$location" ]; then + echo "$variant $location" + exit 0 + fi + done + echo "No single H100 variants available" >&2 + exit 1 + ;; + *) + echo "Unknown wildcard type: {{ terraform_datacrunch_instance_type }}" + exit 1 + ;; + esac + register: datacrunch_auto_instance_type + failed_when: false + changed_when: false + when: + - terraform_datacrunch_instance_type in ["B300_OR_LESS", "B200_OR_LESS", "H100_OR_LESS", + "A100_80_OR_LESS", "A100_40_OR_LESS", "ANY_1H100"] + tags: + - bringup + +- name: Fail if no instances available for wildcard selection + ansible.builtin.fail: + msg: | + No GPU instances available for {{ terraform_datacrunch_instance_type }} + + {{ datacrunch_auto_instance_type.stderr }} + + Try: + - Wait and retry (capacity changes frequently) + - Check DataCrunch dashboard: https://cloud.datacrunch.io + - Use a different tier group via menuconfig + - Check capacity manually: scripts/datacrunch_check_capacity.py --instance-type <type> + when: + - terraform_datacrunch_instance_type in ["B300_OR_LESS", "B200_OR_LESS", "H100_OR_LESS", + "A100_80_OR_LESS", "A100_40_OR_LESS", "ANY_1H100"] + - datacrunch_auto_instance_type.rc != 0 + tags: + - bringup + +- name: Parse auto-selected instance type and location + ansible.builtin.set_fact: + auto_selected_instance: "{{ datacrunch_auto_instance_type.stdout.split()[0] }}" + auto_selected_location: "{{ datacrunch_auto_instance_type.stdout.split()[1] }}" + when: + - terraform_datacrunch_instance_type in ["B300_OR_LESS", "B200_OR_LESS", "H100_OR_LESS", + "A100_80_OR_LESS", "A100_40_OR_LESS", "ANY_1H100"] + - datacrunch_auto_instance_type.rc == 0 + tags: + - bringup + +- name: Report auto-selected instance type for wildcards + ansible.builtin.debug: + msg: >- + Auto-selected instance type: {{ auto_selected_instance }} + in region: {{ auto_selected_location }} + when: + - terraform_datacrunch_instance_type in ["B300_OR_LESS", "B200_OR_LESS", "H100_OR_LESS", + "A100_80_OR_LESS", "A100_40_OR_LESS", "ANY_1H100"] + - datacrunch_auto_instance_type.rc == 0 + tags: + - bringup + +- name: Update terraform vars with auto-selected instance type + ansible.builtin.lineinfile: + path: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}/terraform.tfvars" + regexp: '^datacrunch_instance_type\s*=' + line: 'datacrunch_instance_type = "{{ auto_selected_instance }}"' + when: + - terraform_datacrunch_instance_type in ["B300_OR_LESS", "B200_OR_LESS", "H100_OR_LESS", + "A100_80_OR_LESS", "A100_40_OR_LESS", "ANY_1H100"] + - datacrunch_auto_instance_type.rc == 0 + tags: + - bringup + +- name: Define DataCrunch tier wildcards list + ansible.builtin.set_fact: + datacrunch_tier_wildcards: + - B300_OR_LESS + - B200_OR_LESS + - H100_OR_LESS + - A100_80_OR_LESS + - A100_40_OR_LESS + - ANY_1H100 + tags: + - bringup + +- name: Set resolved instance type for subsequent tasks + ansible.builtin.set_fact: + resolved_instance_type: >- + {{ auto_selected_instance + if (terraform_datacrunch_instance_type in datacrunch_tier_wildcards + and datacrunch_auto_instance_type.rc == 0) + else terraform_datacrunch_instance_type }} + tags: + - bringup + +- name: Check DataCrunch capacity before provisioning + ansible.builtin.shell: + cmd: | + set -o pipefail + {{ topdir_path }}/scripts/datacrunch_check_capacity.py \ + --instance-type {{ resolved_instance_type }} \ + --json | \ + python3 -c " + import sys, json + data = json.load(sys.stdin) + if data and len(data) > 0: + locations = [item['location'] for item in data] + print(f'Instance {{ resolved_instance_type }} is available in: ' + ', '.join(locations)) + sys.exit(0) + else: + print('Error: Instance {{ resolved_instance_type }} is not available in any location') + print('Check available instances with: scripts/datacrunch_check_capacity.py') + sys.exit(1) + " + register: datacrunch_capacity_check + failed_when: false + changed_when: false + when: + - terraform_datacrunch_instance_type not in datacrunch_tier_wildcards + tags: + - bringup + +- name: Report DataCrunch capacity check result + ansible.builtin.fail: + msg: "{{ datacrunch_capacity_check.stdout }}" + when: + - datacrunch_capacity_check is defined + - datacrunch_capacity_check.rc is defined + - datacrunch_capacity_check.rc != 0 + tags: + - bringup + +- name: Auto-select DataCrunch location for explicit instance types + ansible.builtin.shell: + cmd: | + {{ topdir_path }}/scripts/datacrunch_check_capacity.py \ + --instance-type {{ resolved_instance_type }} \ + --pick-first + register: datacrunch_auto_location + changed_when: false + when: + - terraform_datacrunch_instance_type not in datacrunch_tier_wildcards + tags: + - bringup + +- name: Use tier-selected location for wildcard instance types + ansible.builtin.set_fact: + datacrunch_final_location: "{{ auto_selected_location }}" + when: + - terraform_datacrunch_instance_type in datacrunch_tier_wildcards + - datacrunch_auto_instance_type.rc == 0 + tags: + - bringup + +- name: Use auto-selected location for explicit instance types + ansible.builtin.set_fact: + datacrunch_final_location: "{{ datacrunch_auto_location.stdout }}" + when: + - terraform_datacrunch_instance_type not in datacrunch_tier_wildcards + - datacrunch_auto_location.rc == 0 + tags: + - bringup + +- name: Update terraform vars with final location + ansible.builtin.lineinfile: + path: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}/terraform.tfvars" + regexp: '^datacrunch_location\s*=' + line: 'datacrunch_location = "{{ datacrunch_final_location }}"' + when: + - datacrunch_final_location is defined + tags: + - bringup + +- name: Display final location + ansible.builtin.debug: + msg: "Selected DataCrunch location: {{ datacrunch_final_location }}" + when: + - datacrunch_final_location is defined + tags: + - bringup + +- name: Check if terraform state already has resources + ansible.builtin.command: + cmd: terraform state list + chdir: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + register: terraform_state_check + failed_when: false + changed_when: false + tags: + - bringup + +- name: Set flag for existing terraform resources + ansible.builtin.set_fact: + terraform_resources_exist: "{{ terraform_state_check.stdout_lines | default([]) | length > 0 }}" + tags: + - bringup + +- name: Report that infrastructure is already provisioned + ansible.builtin.debug: + msg: "Infrastructure already provisioned ({{ terraform_state_check.stdout_lines | default([]) | length }} resources in state). Skipping terraform apply." + when: + - terraform_resources_exist | default(false) + tags: + - bringup + +- name: Initialize external provider for DataCrunch (workaround for dev_overrides) + ansible.builtin.shell: + cmd: | + # Hide all terraform files that reference datacrunch resources + # so that terraform init only sees the external provider requirement + for file in provider.tf main.tf output.tf vars.tf nodes.tf; do + if [ -f "$file" ]; then + mv "$file" "$file.bak" + fi + done + + # Create minimal terraform config with only external provider + cat > provider_init.tf << 'EOF' + terraform { + required_version = ">= 1.0" + required_providers { + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } + } + EOF + + # Initialize to get external provider and generate lock file + # Suppress color output to avoid ANSI codes in logs + terraform init -no-color > /dev/null 2>&1 || terraform init -no-color + + # Preserve the generated lock file for the external provider + # This is needed because dev_overrides prevents normal init of datacrunch provider + # but we still need the lock file for other providers + if [ -f .terraform.lock.hcl ]; then + cp .terraform.lock.hcl .terraform.lock.hcl.generated + fi + + # Clean up temporary file and restore original terraform files + rm provider_init.tf + for file in provider.tf main.tf output.tf vars.tf nodes.tf; do + if [ -f "$file.bak" ]; then + mv "$file.bak" "$file" + fi + done + + # Restore the lock file after putting all files back + if [ -f .terraform.lock.hcl.generated ]; then + mv .terraform.lock.hcl.generated .terraform.lock.hcl + fi + chdir: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + when: + - not (terraform_resources_exist | default(false)) + changed_when: false + tags: + - bringup + +- name: Bring up terraform resources (DataCrunch with tier fallback on failure) + ansible.builtin.shell: + cmd: | + set -o pipefail + MAX_RETRIES=5 + EXCLUDED_INSTANCES="" + TIER_GROUP="{{ terraform_datacrunch_instance_type | lower | replace('_', '-') }}" + + # Check if using tier-based selection + is_tier_based() { + case "{{ terraform_datacrunch_instance_type }}" in + B300_OR_LESS|B200_OR_LESS|H100_OR_LESS|A100_80_OR_LESS|A100_40_OR_LESS) + return 0 + ;; + *) + return 1 + ;; + esac + } + + for attempt in $(seq 1 $MAX_RETRIES); do + echo "=== Attempt $attempt of $MAX_RETRIES ===" + + # Get current instance type from tfvars + CURRENT_INSTANCE=$(grep '^datacrunch_instance_type' terraform.tfvars | \ + sed 's/.*= *"\([^"]*\)".*/\1/') + echo "Trying instance type: $CURRENT_INSTANCE" + + # Attempt terraform apply and capture output + APPLY_OUTPUT=$(terraform apply -auto-approve -no-color 2>&1) && { + echo "$APPLY_OUTPUT" + echo "Terraform apply succeeded!" + exit 0 + } + + # Apply failed - check what kind of error + echo "$APPLY_OUTPUT" + + # Check if this is a 503 or deployment error that we can retry with fallback + if echo "$APPLY_OUTPUT" | grep -q "API returned status 503\|Error deploying instance"; then + echo "" + echo "Deployment failed for $CURRENT_INSTANCE - checking if tier fallback is available..." + + if ! is_tier_based; then + echo "Not using tier-based selection, cannot fall back to different instance type." + exit 1 + fi + + # Add current instance to exclusion list + if [ -n "$EXCLUDED_INSTANCES" ]; then + EXCLUDED_INSTANCES="$EXCLUDED_INSTANCES --exclude $CURRENT_INSTANCE" + else + EXCLUDED_INSTANCES="--exclude $CURRENT_INSTANCE" + fi + + echo "Excluded instances so far: $EXCLUDED_INSTANCES" + + # Try to select next available instance + echo "Selecting next available instance from tier group: $TIER_GROUP" + NEXT_SELECTION=$({{ topdir_path }}/scripts/datacrunch_select_tier.py \ + "$TIER_GROUP" --verbose $EXCLUDED_INSTANCES 2>&1) || { + echo "No more instances available in tier group $TIER_GROUP" + echo "$NEXT_SELECTION" + exit 1 + } + + # Parse new instance and location + NEW_INSTANCE=$(echo "$NEXT_SELECTION" | tail -1 | awk '{print $1}') + NEW_LOCATION=$(echo "$NEXT_SELECTION" | tail -1 | awk '{print $2}') + + if [ -z "$NEW_INSTANCE" ] || [ -z "$NEW_LOCATION" ]; then + echo "Failed to parse new instance selection" + exit 1 + fi + + echo "" + echo "Falling back to: $NEW_INSTANCE in $NEW_LOCATION" + + # Update terraform.tfvars with new instance type and location + sed -i "s/^datacrunch_instance_type.*/datacrunch_instance_type = \"$NEW_INSTANCE\"/" \ + terraform.tfvars + sed -i "s/^datacrunch_location.*/datacrunch_location = \"$NEW_LOCATION\"/" \ + terraform.tfvars + + echo "Updated terraform.tfvars, retrying..." + echo "" + else + echo "Terraform failed with non-recoverable error" + exit 1 + fi + done + + echo "Exhausted all $MAX_RETRIES retry attempts" + exit 1 + chdir: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + changed_when: true + when: + - not (terraform_resources_exist | default(false)) + tags: + - bringup
playbooks/roles/terraform/tasks/bringup/generic.yml new file +12 -0
@@ -0,0 +1,12 @@ +--- +# Generic terraform bringup for providers without special handling +# Used for: AWS, Azure, GCE, OCI, and other standard providers + +- name: Bring up terraform resources + cloud.terraform.terraform: + binary_path: "{{ terraform_binary_path }}" + force_init: true + project_path: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + state: present + tags: + - bringup
playbooks/roles/terraform/tasks/bringup/lambdalabs.yml new file +222 -0
222 lines not on this page · raw message
playbooks/roles/terraform/tasks/bringup/main.yml new file +27 -0
@@ -0,0 +1,27 @@ +--- +# Terraform bringup orchestration +# Includes provider-specific tasks based on kdevops_terraform_provider + +- name: Include Lambda Labs bringup tasks + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/bringup/lambdalabs.yml" + when: + - kdevops_terraform_provider == "lambdalabs" + tags: + - bringup + +- name: Include DataCrunch bringup tasks + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/bringup/datacrunch.yml" + when: + - kdevops_terraform_provider == "datacrunch" + tags: + - bringup + +- name: Include generic bringup tasks + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/bringup/generic.yml" + when: + - kdevops_terraform_provider not in ["lambdalabs", "datacrunch"] + tags: + - bringup
playbooks/roles/terraform/tasks/common/ssh-config.yml new file +37 -0
@@ -0,0 +1,37 @@ +--- +# SSH configuration generation for terraform-provisioned nodes +# This is common to all terraform providers + +- name: Retrieve the controller_ip_map from terraform + cloud.terraform.terraform_output: + binary_path: "{{ terraform_binary_path }}" + format: json + name: controller_ip_map + project_path: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + register: terraform_output + tags: + - ssh + +- name: Add each target node's ssh Host entry on the control host + ansible.builtin.blockinfile: + block: "{{ lookup('template', 'ssh_config.j2') }}" + create: true + dest: "{{ kdevops_ssh_config }}" + insertafter: "EOF" + marker: "# {mark} host configuration for {{ item.key }}" + mode: "u=rw,g=r,o=r" + loop: "{{ terraform_output.value | dict2items }}" + tags: + - ssh + +- name: Ensure the Include directive is present on the controller + ansible.builtin.blockinfile: + path: "{{ sshconfig }}" + insertbefore: BOF + append_newline: true + create: true + marker: "# {mark} Managed by kdevops" + mode: "u=rw,g=r,o=r" + block: "Include {{ kdevops_ssh_config_prefix }}*" + tags: + - ssh
playbooks/roles/terraform/tasks/common/status.yml new file +35 -0
@@ -0,0 +1,35 @@ +--- +# Terraform status reporting +# Common to all terraform providers + +- name: Report terraform status + tags: + - status + block: + - name: Retrieve the controller_ip_map from terraform + cloud.terraform.terraform_output: + binary_path: "{{ terraform_binary_path }}" + format: json + name: controller_ip_map + project_path: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + register: terraform_output + + - name: End play -- terraform state file is empty or missing + ansible.builtin.meta: end_play + when: + - terraform_output.warnings is defined + + - name: Count active resources + ansible.builtin.command: + cmd: "terraform state list" + chdir: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + register: terraform_state + changed_when: false + + - name: Show status + ansible.builtin.debug: + msg: "Active resources: {{ terraform_state.stdout_lines | length }}" + + - name: Show controller IP map + ansible.builtin.debug: + var: terraform_output.value
playbooks/roles/terraform/tasks/destroy/datacrunch.yml new file +67 -0
67 lines not on this page · raw message
playbooks/roles/terraform/tasks/destroy/generic.yml new file +12 -0
@@ -0,0 +1,12 @@ +--- +# Generic terraform destroy for providers without special handling +# Used for: AWS, Azure, GCE, OCI, Lambda Labs, and other standard providers + +- name: Destroy terraform resources + cloud.terraform.terraform: + binary_path: "{{ terraform_binary_path }}" + force_init: true + project_path: "{{ topdir_path }}/terraform/{{ kdevops_terraform_provider }}" + state: absent + tags: + - destroy
playbooks/roles/terraform/tasks/destroy/main.yml new file +26 -0
@@ -0,0 +1,26 @@ +--- +# Terraform destroy orchestration +# Includes provider-specific tasks based on kdevops_terraform_provider + +- name: Remove the ephemeral ssh config file on the control host + ansible.builtin.file: + path: "{{ kdevops_ssh_config }}" + state: absent + tags: + - destroy + +- name: Include DataCrunch destroy tasks + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/destroy/datacrunch.yml" + when: + - kdevops_terraform_provider == "datacrunch" + tags: + - destroy + +- name: Include generic destroy tasks + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/destroy/generic.yml" + when: + - kdevops_terraform_provider != "datacrunch" + tags: + - destroy
playbooks/roles/terraform/tasks/main.yml +14 -765
792 lines not on this page · raw message
Signature · 1 line
2.52.0
Chuck Lever
AppliedQuoted 12 lines · Chuck Lever
The terraform role's main.yml had grown to nearly 800 lines with Lambda Labs and DataCrunch provider-specific logic interleaved throughout the file. This made maintenance difficult and required understanding the entire file to make changes for a single provider.
This refactoring creates a plugin-like architecture where each cloud provider's unique requirements are isolated in dedicated task files. The new structure separates concerns by operation (bringup, destroy) and by provider (lambdalabs, datacrunch, generic), making it straightforward to add support for new providers or modify existing ones without risk of breaking other providers.
Quoted 7 lines
Common functionality shared across all providers, such as SSH configuration and status reporting, is now cleanly separated in a common directory. This follows patterns already established in other roles like bootlinux and guestfs.
Generated-by Claude AISigned-off-by Chuck Lever <[email protected]>
Merged into origin/main.
Chuck Lever