Skip to content

Commit ea8f123

Browse files
workspace variables functions updates
1 parent c0d78e8 commit ea8f123

5 files changed

Lines changed: 483 additions & 0 deletions

File tree

examples/variables.py

Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Comprehensive example testing all variable functions in TFE workspace.
4+
Tests: list, list_all, create, read, update, and delete operations.
5+
"""
6+
7+
import sys
8+
import os
9+
import time
10+
11+
# Add the src directory to the path
12+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
13+
14+
from tfe import TFEClient, TFEConfig
15+
from tfe.types import VariableCreateOptions, VariableUpdateOptions, CategoryType
16+
17+
18+
def main():
19+
"""Test all variable operations in a workspace."""
20+
21+
# Initialize the TFE client
22+
client = TFEClient(TFEConfig.from_env())
23+
24+
# Replace this with your actual workspace ID
25+
workspace_id = "ws-example123456789" # Get this from your TFE workspace
26+
27+
print(f"Testing all variable operations in workspace: {workspace_id}")
28+
print("=" * 60)
29+
30+
# Track created variables for cleanup
31+
created_variables = []
32+
33+
try:
34+
# 1. Test CREATE function - COMMENTED OUT (already have variables from previous run)
35+
print("\n1. Testing CREATE operation:")
36+
print("-" * 30)
37+
38+
# Create a Terraform variable
39+
terraform_var = VariableCreateOptions(
40+
key="test_terraform_var",
41+
value="production",
42+
description="Test Terraform variable",
43+
category=CategoryType.TERRAFORM,
44+
hcl=False,
45+
sensitive=False
46+
)
47+
48+
try:
49+
variable = client.variables.create(workspace_id, terraform_var)
50+
created_variables.append(variable.id)
51+
print(f"✓ Created Terraform variable: {variable.key} = {variable.value}")
52+
print(f" ID: {variable.id}, Category: {variable.category}")
53+
except Exception as e:
54+
print(f"✗ Error creating Terraform variable: {e}")
55+
56+
# Create an environment variable
57+
env_var = VariableCreateOptions(
58+
key="TEST_LOG_LEVEL",
59+
value="DEBUG",
60+
description="Test environment variable",
61+
category=CategoryType.ENV,
62+
hcl=False,
63+
sensitive=False
64+
)
65+
66+
try:
67+
variable = client.variables.create(workspace_id, env_var)
68+
created_variables.append(variable.id)
69+
print(f"✓ Created environment variable: {variable.key} = {variable.value}")
70+
print(f" ID: {variable.id}, Category: {variable.category}")
71+
except Exception as e:
72+
print(f"✗ Error creating environment variable: {e}")
73+
74+
# Create a sensitive variable
75+
secret_var = VariableCreateOptions(
76+
key="TEST_API_KEY",
77+
value="super-secret-key-12345",
78+
description="Test sensitive variable",
79+
category=CategoryType.ENV,
80+
hcl=False,
81+
sensitive=True
82+
)
83+
84+
try:
85+
variable = client.variables.create(workspace_id, secret_var)
86+
created_variables.append(variable.id)
87+
print(f"✓ Created sensitive variable: {variable.key} = ***HIDDEN***")
88+
print(f" ID: {variable.id}, Category: {variable.category}")
89+
except Exception as e:
90+
print(f"✗ Error creating sensitive variable: {e}")
91+
92+
# Small delay to ensure variables are created
93+
time.sleep(1)
94+
95+
# 2. Test LIST function (workspace-only variables) - COMMENTED OUT
96+
print("\n2. Testing LIST operation (workspace variables only):")
97+
print("-" * 50)
98+
99+
try:
100+
variables = list(client.variables.list(workspace_id))
101+
print(f"Found {len(variables)} workspace variables:")
102+
for var in variables:
103+
value_display = "***SENSITIVE***" if var.sensitive else var.value
104+
print(f" • {var.key} = {value_display} ({var.category}) [ID: {var.id}]")
105+
except Exception as e:
106+
print(f"✗ Error listing variables: {e}")
107+
108+
# 3. Test LIST_ALL function (includes inherited variables from variable sets)
109+
print("\n3. Testing LIST_ALL operation (includes variable sets):")
110+
print("-" * 55)
111+
112+
try:
113+
all_variables = list(client.variables.list_all(workspace_id))
114+
print(f"Found {len(all_variables)} total variables (including inherited):")
115+
for var in all_variables:
116+
value_display = "***SENSITIVE***" if var.sensitive else var.value
117+
print(f" • {var.key} = {value_display} ({var.category}) [ID: {var.id}]")
118+
except Exception as e:
119+
print(f"✗ Error listing all variables: {e}")
120+
121+
# Test READ function with specific variable ID - COMMENTED OUT
122+
print("\n4. Testing READ operation with specific variable ID:")
123+
print("-" * 50)
124+
125+
# Replace this with actual variable ID to test reading
126+
test_variable_id = "var-example123456789"
127+
print(f"Testing READ with variable ID: {test_variable_id}")
128+
129+
try:
130+
variable = client.variables.read(workspace_id, test_variable_id)
131+
# For testing, show actual values even for sensitive variables
132+
if variable.sensitive:
133+
print(f"✓ Read variable: {variable.key} = {variable.value} (SENSITIVE)")
134+
else:
135+
print(f"✓ Read variable: {variable.key} = {variable.value}")
136+
print(f" ID: {variable.id}")
137+
print(f" Description: {variable.description}")
138+
print(f" Category: {variable.category}")
139+
print(f" HCL: {variable.hcl}")
140+
print(f" Sensitive: {variable.sensitive}")
141+
if hasattr(variable, 'version_id'):
142+
print(f" Version ID: {variable.version_id}")
143+
except Exception as e:
144+
print(f"✗ Error reading variable {test_variable_id}: {e}")
145+
146+
# Test UPDATE function with specific variable ID - COMMENTED OUT
147+
print("\n5. Testing UPDATE operation with specific variable ID:")
148+
print("-" * 55)
149+
150+
# Replace this with actual variable ID to test updating
151+
test_variable_id = "var-example123456789"
152+
print(f"Testing UPDATE with variable ID: {test_variable_id}")
153+
print(f"Setting value to: 'npe'")
154+
155+
try:
156+
# First read the current variable to get its details
157+
current_var = client.variables.read(workspace_id, test_variable_id)
158+
print(f"Current value: {current_var.value}")
159+
print(f"Current key: {current_var.key}")
160+
161+
# Update the variable value to "npe"
162+
update_options = VariableUpdateOptions(
163+
key=current_var.key,
164+
value="npe",
165+
description=current_var.description,
166+
hcl=current_var.hcl,
167+
sensitive=current_var.sensitive
168+
)
169+
170+
updated_variable = client.variables.update(workspace_id, test_variable_id, update_options)
171+
print(f"✓ Updated variable: {updated_variable.key} = {updated_variable.value}")
172+
print(f" Description: {updated_variable.description}")
173+
print(f" Category: {updated_variable.category}")
174+
print(f" HCL: {updated_variable.hcl}")
175+
print(f" Sensitive: {updated_variable.sensitive}")
176+
print(f" ID: {updated_variable.id}")
177+
except Exception as e:
178+
print(f"✗ Error updating variable {test_variable_id}: {e}")
179+
180+
# Test DELETE function with specific variable ID
181+
print("\n6. Testing DELETE operation with specific variable ID:")
182+
print("-" * 55)
183+
184+
# Replace this with actual variable ID to test deletion
185+
test_variable_id = "var-example123456789"
186+
print(f"Testing DELETE with variable ID: {test_variable_id}")
187+
188+
try:
189+
# First read the variable to confirm it exists before deletion
190+
variable = client.variables.read(workspace_id, test_variable_id)
191+
print(f"Variable to delete: {variable.key} = {variable.value}")
192+
print(f" ID: {variable.id}")
193+
194+
# Delete the variable
195+
client.variables.delete(workspace_id, test_variable_id)
196+
print(f"✓ Successfully deleted variable with ID: {test_variable_id}")
197+
198+
# Try to read it again to verify deletion
199+
print("Verifying deletion...")
200+
try:
201+
client.variables.read(workspace_id, test_variable_id)
202+
print("✗ Warning: Variable still exists after deletion!")
203+
except Exception as read_error:
204+
if "not found" in str(read_error).lower() or "404" in str(read_error):
205+
print("✓ Confirmed: Variable no longer exists")
206+
else:
207+
print(f"✗ Unexpected error verifying deletion: {read_error}")
208+
209+
except Exception as e:
210+
print(f"✗ Error deleting variable {test_variable_id}: {e}")
211+
212+
213+
# 4. Test READ function
214+
print("\n4. Testing READ operation:")
215+
print("-" * 25)
216+
217+
if created_variables:
218+
test_var_id = created_variables[0] # Use the first created variable
219+
try:
220+
variable = client.variables.read(workspace_id, test_var_id)
221+
value_display = "***SENSITIVE***" if variable.sensitive else variable.value
222+
print(f"✓ Read variable: {variable.key} = {value_display}")
223+
print(f" ID: {variable.id}")
224+
print(f" Description: {variable.description}")
225+
print(f" Category: {variable.category}")
226+
print(f" HCL: {variable.hcl}")
227+
print(f" Sensitive: {variable.sensitive}")
228+
except Exception as e:
229+
print(f"✗ Error reading variable {test_var_id}: {e}")
230+
else:
231+
print("No variables available to read")
232+
233+
# 5. Test UPDATE function
234+
print("\n5. Testing UPDATE operation:")
235+
print("-" * 27)
236+
237+
if created_variables:
238+
test_var_id = created_variables[0] # Use the first created variable
239+
try:
240+
# First read the current variable to get its details
241+
current_var = client.variables.read(workspace_id, test_var_id)
242+
243+
# Update the variable
244+
update_options = VariableUpdateOptions(
245+
key=current_var.key,
246+
value="updated_value_123",
247+
description="Updated test variable description",
248+
hcl=False,
249+
sensitive=False
250+
)
251+
252+
updated_variable = client.variables.update(workspace_id, test_var_id, update_options)
253+
print(f"✓ Updated variable: {updated_variable.key} = {updated_variable.value}")
254+
print(f" New description: {updated_variable.description}")
255+
print(f" ID: {updated_variable.id}")
256+
except Exception as e:
257+
print(f"✗ Error updating variable {test_var_id}: {e}")
258+
else:
259+
print("No variables available to update")
260+
261+
# 6. Test DELETE function
262+
print("\n6. Testing DELETE operation:")
263+
print("-" * 27)
264+
265+
# Delete all created variables
266+
for var_id in created_variables:
267+
try:
268+
client.variables.delete(workspace_id, var_id)
269+
print(f"✓ Deleted variable with ID: {var_id}")
270+
except Exception as e:
271+
print(f"✗ Error deleting variable {var_id}: {e}")
272+
273+
# Verify deletion by listing variables again
274+
print("\nVerifying deletion - listing variables after cleanup:")
275+
try:
276+
remaining_variables = list(client.variables.list(workspace_id))
277+
# Filter out the variables we just deleted
278+
remaining_test_vars = [v for v in remaining_variables if v.key.startswith("test_") or v.key.startswith("TEST_")]
279+
if remaining_test_vars:
280+
print(f"Warning: {len(remaining_test_vars)} test variables still exist:")
281+
for var in remaining_test_vars:
282+
print(f" • {var.key} [ID: {var.id}]")
283+
else:
284+
print("✓ All test variables successfully deleted")
285+
except Exception as e:
286+
print(f"✗ Error verifying deletion: {e}")
287+
288+
except Exception as e:
289+
print(f"✗ Unexpected error during testing: {e}")
290+
291+
print("\n" + "=" * 60)
292+
print("Variable testing complete!")
293+
294+
295+
if __name__ == "__main__":
296+
main()

src/tfe/client.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from .config import TFEConfig
55
from .resources.organizations import Organizations
66
from .resources.projects import Projects
7+
from .resources.variable import Variables
78
from .resources.workspaces import Workspaces
89

910

@@ -26,6 +27,7 @@ def __init__(self, config: TFEConfig | None = None):
2627
)
2728
self.organizations = Organizations(self._transport)
2829
self.projects = Projects(self._transport)
30+
self.variables = Variables(self._transport)
2931
self.workspaces = Workspaces(self._transport)
3032

3133
def close(self) -> None:

src/tfe/errors.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,7 @@ class RequiredFieldMissing(TFEError): ...
5757
ERR_REQUIRED_NAME = "name is required"
5858
ERR_INVALID_ORG = "invalid organization name"
5959
ERR_REQUIRED_EMAIL = "email is required"
60+
ERR_INVALID_WORKSPACE_ID = "invalid workspace ID"
61+
ERR_INVALID_VARIABLE_ID = "invalid variable ID"
62+
ERR_REQUIRED_KEY = "key is required"
63+
ERR_REQUIRED_CATEGORY = "category is required"

0 commit comments

Comments
 (0)