|
| 1 | +""" |
| 2 | +Terraform Cloud/Enterprise Run Tasks Integration Example |
| 3 | +
|
| 4 | +This example demonstrates how to use the python-tfe SDK to build a run task server |
| 5 | +that receives task requests from TFC/TFE and sends results back via the callback API. |
| 6 | +
|
| 7 | +IMPORTANT: This example uses Flask as a simple HTTP server for demonstration purposes. |
| 8 | +You can use any web framework (FastAPI, Django, etc.) or even the built-in http.server. |
| 9 | +The key components are: |
| 10 | +1. Receiving POST requests with run task payloads |
| 11 | +2. Using TFEClient.run_tasks_integration.callback() to send results back |
| 12 | +
|
| 13 | +Prerequisites: |
| 14 | + - Install Flask (for this example only): pip install flask |
| 15 | + - Expose your server publicly using ngrok, cloudflare tunnel, or similar |
| 16 | + - Create a run task in TFC/TFE pointing to your public URL endpoint |
| 17 | + - Attach the run task to a workspace |
| 18 | +
|
| 19 | +Usage: |
| 20 | + python examples/run_tasks_integration.py |
| 21 | +
|
| 22 | +Then expose with ngrok: |
| 23 | + ngrok http 5000 |
| 24 | +
|
| 25 | +API Documentation: |
| 26 | + https://developer.hashicorp.com/terraform/enterprise/api-docs/run-tasks/run-tasks-integration |
| 27 | +""" |
| 28 | + |
| 29 | +from __future__ import annotations |
| 30 | + |
| 31 | +import os |
| 32 | + |
| 33 | +try: |
| 34 | + from flask import Flask, request, jsonify |
| 35 | +except ImportError: |
| 36 | + print("Error: Flask is required for this example") |
| 37 | + print("Install it with: pip install flask") |
| 38 | + exit(1) |
| 39 | + |
| 40 | +from pytfe import TFEClient, TFEConfig |
| 41 | +from pytfe.models import RunTaskRequest, RunTaskRequestCapabilities |
| 42 | +from pytfe.resources.run_tasks_integration import ( |
| 43 | + RunTasksIntegration, |
| 44 | + TaskResultCallbackOptions, |
| 45 | + TaskResultOutcome, |
| 46 | + TaskResultStatus, |
| 47 | + TaskResultTag, |
| 48 | +) |
| 49 | + |
| 50 | +app = Flask(__name__) |
| 51 | + |
| 52 | +# Initialize TFE client for callback functionality |
| 53 | +# Note: The callback uses the access_token from the run task request, |
| 54 | +# NOT your regular TFE API token |
| 55 | +config = TFEConfig() |
| 56 | +client = TFEClient(config) |
| 57 | + |
| 58 | + |
| 59 | +@app.route('/run-task', methods=['POST']) |
| 60 | +def handle_run_task(): |
| 61 | + """Handle incoming run task request from TFC/TFE.""" |
| 62 | + try: |
| 63 | + # Parse the incoming request |
| 64 | + run_task_request = RunTaskRequest(**request.json) |
| 65 | + |
| 66 | + print(f"Received run task request:") |
| 67 | + print(f" Organization: {run_task_request.organization_name}") |
| 68 | + print(f" Workspace: {run_task_request.workspace_name}") |
| 69 | + print(f" Run ID: {run_task_request.run_id}") |
| 70 | + print(f" Stage: {run_task_request.stage}") |
| 71 | + print(f" Enforcement Level: {run_task_request.task_result_enforcement_level}") |
| 72 | + |
| 73 | + # Extract the callback information |
| 74 | + callback_url = run_task_request.task_result_callback_url |
| 75 | + access_token = run_task_request.access_token |
| 76 | + |
| 77 | + # YOUR CUSTOM LOGIC HERE |
| 78 | + # This is where you would perform your actual run task checks |
| 79 | + # For example: |
| 80 | + # - Download and analyze the plan JSON |
| 81 | + # - Check for policy violations |
| 82 | + # - Validate resource configurations |
| 83 | + # - Run security scans |
| 84 | + # - Check cost estimates |
| 85 | + |
| 86 | + # Example: Simple check based on workspace name |
| 87 | + if "prod" in run_task_request.workspace_name.lower(): |
| 88 | + # Production workspace - run strict checks |
| 89 | + result = perform_strict_checks(run_task_request) |
| 90 | + else: |
| 91 | + # Non-production - run basic checks |
| 92 | + result = perform_basic_checks(run_task_request) |
| 93 | + |
| 94 | + # Send the callback to TFC/TFE |
| 95 | + callback_options = TaskResultCallbackOptions( |
| 96 | + status=result["status"], |
| 97 | + message=result["message"], |
| 98 | + url=result.get("url"), |
| 99 | + outcomes=result.get("outcomes", []), |
| 100 | + ) |
| 101 | + |
| 102 | + client.run_tasks_integration.callback( |
| 103 | + callback_url=callback_url, |
| 104 | + access_token=access_token, |
| 105 | + options=callback_options, |
| 106 | + ) |
| 107 | + |
| 108 | + print(f"Successfully sent callback with status: {result['status']}") |
| 109 | + |
| 110 | + # Return 200 OK to TFC/TFE |
| 111 | + return jsonify({"status": "accepted"}), 200 |
| 112 | + |
| 113 | + except Exception as e: |
| 114 | + print(f"Error processing run task: {e}") |
| 115 | + |
| 116 | + # Even if processing fails, try to send a failure callback |
| 117 | + try: |
| 118 | + if 'callback_url' in locals() and 'access_token' in locals(): |
| 119 | + error_options = TaskResultCallbackOptions( |
| 120 | + status=TaskResultStatus.FAILED, |
| 121 | + message=f"Run task processing error: {str(e)}", |
| 122 | + ) |
| 123 | + client.run_tasks_integration.callback( |
| 124 | + callback_url=callback_url, |
| 125 | + access_token=access_token, |
| 126 | + options=error_options, |
| 127 | + ) |
| 128 | + except Exception as callback_error: |
| 129 | + print(f"Failed to send error callback: {callback_error}") |
| 130 | + |
| 131 | + return jsonify({"error": str(e)}), 500 |
| 132 | + |
| 133 | + |
| 134 | +def perform_strict_checks(run_task_request: RunTaskRequest) -> dict: |
| 135 | + """Perform strict checks for production workspaces. |
| 136 | + |
| 137 | + This is a placeholder for your actual check logic. |
| 138 | + """ |
| 139 | + # Example: Always pass for demo purposes |
| 140 | + # In real implementation, you would: |
| 141 | + # - Download the configuration or plan |
| 142 | + # - Analyze it for compliance/security |
| 143 | + # - Generate detailed outcomes |
| 144 | + |
| 145 | + outcomes = [ |
| 146 | + TaskResultOutcome( |
| 147 | + outcome_id="SECURITY-001", |
| 148 | + description="Security check passed", |
| 149 | + body="All security requirements met for production deployment.", |
| 150 | + tags={ |
| 151 | + "Category": [TaskResultTag(label="Security")], |
| 152 | + "Severity": [TaskResultTag(label="Info", level="info")], |
| 153 | + }, |
| 154 | + ), |
| 155 | + TaskResultOutcome( |
| 156 | + outcome_id="COMPLIANCE-001", |
| 157 | + description="Compliance check passed", |
| 158 | + body="Configuration meets all compliance requirements.", |
| 159 | + tags={ |
| 160 | + "Category": [TaskResultTag(label="Compliance")], |
| 161 | + "Severity": [TaskResultTag(label="Info", level="info")], |
| 162 | + }, |
| 163 | + ), |
| 164 | + ] |
| 165 | + |
| 166 | + return { |
| 167 | + "status": TaskResultStatus.PASSED, |
| 168 | + "message": "All production checks passed", |
| 169 | + "url": "https://your-dashboard.example.com/results/123", |
| 170 | + "outcomes": outcomes, |
| 171 | + } |
| 172 | + |
| 173 | + |
| 174 | +def perform_basic_checks(run_task_request: RunTaskRequest) -> dict: |
| 175 | + """Perform basic checks for non-production workspaces. |
| 176 | + |
| 177 | + This is a placeholder for your actual check logic. |
| 178 | + """ |
| 179 | + # Example: Simple validation |
| 180 | + outcomes = [ |
| 181 | + TaskResultOutcome( |
| 182 | + outcome_id="BASIC-001", |
| 183 | + description="Basic validation passed", |
| 184 | + body="Configuration syntax is valid.", |
| 185 | + tags={ |
| 186 | + "Category": [TaskResultTag(label="Validation")], |
| 187 | + }, |
| 188 | + ), |
| 189 | + ] |
| 190 | + |
| 191 | + return { |
| 192 | + "status": TaskResultStatus.PASSED, |
| 193 | + "message": "Basic checks completed successfully", |
| 194 | + "outcomes": outcomes, |
| 195 | + } |
| 196 | + |
| 197 | + |
| 198 | +@app.route('/health', methods=['GET']) |
| 199 | +def health_check(): |
| 200 | + """Health check endpoint.""" |
| 201 | + return jsonify({"status": "healthy"}), 200 |
| 202 | + |
| 203 | + |
| 204 | +if __name__ == '__main__': |
| 205 | + print("Starting Run Task server on http://localhost:5000") |
| 206 | + print("Make sure to expose this with ngrok or similar for TFC/TFE to reach it") |
| 207 | + print("Example: ngrok http 5000") |
| 208 | + app.run(host='0.0.0.0', port=5000, debug=True) |
0 commit comments