or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-interface.mdcore-operations.mdindex.mdstate-management.mdworkspace-management.md

workspace-management.mddocs/

0

# Workspace Management

1

2

Terraform workspace operations for managing multiple environments and configurations within the same terraform project. Workspaces allow you to manage different states for the same configuration (e.g., dev, staging, prod environments).

3

4

## Capabilities

5

6

### Switch to Workspace

7

8

Switches the current terraform workspace to an existing workspace.

9

10

```python { .api }

11

def set_workspace(self, workspace: str, *args, **kwargs) -> CommandOutput:

12

"""

13

Switch to an existing Terraform workspace.

14

15

Args:

16

workspace: Name of the workspace to switch to

17

*args: Additional positional arguments

18

**kwargs: Additional terraform options

19

20

Returns:

21

Tuple of (return_code, stdout, stderr)

22

23

Raises:

24

TerraformCommandError: If workspace doesn't exist or switch fails

25

"""

26

```

27

28

Usage example:

29

30

```python

31

# Switch to production workspace

32

return_code, stdout, stderr = tf.set_workspace('production')

33

34

# Switch to staging workspace

35

return_code, stdout, stderr = tf.set_workspace('staging')

36

```

37

38

### Create New Workspace

39

40

Creates a new terraform workspace and optionally switches to it.

41

42

```python { .api }

43

def create_workspace(self, workspace: str, *args, **kwargs) -> CommandOutput:

44

"""

45

Create a new Terraform workspace.

46

47

Args:

48

workspace: Name of the workspace to create

49

*args: Additional positional arguments

50

**kwargs: Additional terraform options

51

52

Returns:

53

Tuple of (return_code, stdout, stderr)

54

55

Raises:

56

TerraformCommandError: If workspace already exists or creation fails

57

"""

58

```

59

60

Usage examples:

61

62

```python

63

# Create a new workspace for development

64

return_code, stdout, stderr = tf.create_workspace('development')

65

66

# Create a new workspace for a feature branch

67

return_code, stdout, stderr = tf.create_workspace('feature-auth-system')

68

```

69

70

### Delete Workspace

71

72

Deletes an existing terraform workspace. Cannot delete the current workspace - you must switch to another workspace first.

73

74

```python { .api }

75

def delete_workspace(self, workspace: str, *args, **kwargs) -> CommandOutput:

76

"""

77

Delete a Terraform workspace.

78

79

Args:

80

workspace: Name of the workspace to delete

81

*args: Additional positional arguments

82

**kwargs: Additional terraform options

83

84

Returns:

85

Tuple of (return_code, stdout, stderr)

86

87

Raises:

88

TerraformCommandError: If workspace is current workspace, doesn't exist, or deletion fails

89

"""

90

```

91

92

Usage examples:

93

94

```python

95

# Delete an old feature workspace

96

return_code, stdout, stderr = tf.delete_workspace('feature-old-system')

97

98

# Delete a temporary testing workspace

99

return_code, stdout, stderr = tf.delete_workspace('temp-testing')

100

```

101

102

### Show Current Workspace

103

104

Shows the name of the currently active terraform workspace.

105

106

```python { .api }

107

def show_workspace(self, **kwargs) -> CommandOutput:

108

"""

109

Show the current Terraform workspace name.

110

111

Args:

112

**kwargs: Additional terraform options

113

114

Returns:

115

Tuple of (return_code, stdout, stderr)

116

stdout contains the workspace name

117

"""

118

```

119

120

Usage example:

121

122

```python

123

# Get current workspace name

124

return_code, stdout, stderr = tf.show_workspace()

125

if return_code == 0:

126

current_workspace = stdout.strip()

127

print(f"Current workspace: {current_workspace}")

128

```

129

130

## Workspace Workflow Examples

131

132

### Environment Management

133

134

```python

135

from python_terraform import Terraform

136

137

tf = Terraform(working_dir='/path/to/terraform/project')

138

139

# Initialize the project

140

tf.init()

141

142

# Create environments if they don't exist

143

environments = ['development', 'staging', 'production']

144

for env in environments:

145

try:

146

tf.create_workspace(env)

147

print(f"Created workspace: {env}")

148

except TerraformCommandError:

149

print(f"Workspace {env} already exists")

150

151

# Deploy to each environment

152

for env in environments:

153

print(f"Deploying to {env}")

154

155

# Switch to environment workspace

156

tf.set_workspace(env)

157

158

# Apply with environment-specific variables

159

tf.apply(var_file=f'{env}.tfvars')

160

```

161

162

### Feature Branch Workflow

163

164

```python

165

import subprocess

166

167

# Get current git branch

168

git_branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode().strip()

169

workspace_name = f'feature-{git_branch}'

170

171

# Create workspace for feature branch

172

try:

173

tf.create_workspace(workspace_name)

174

print(f"Created workspace for branch: {workspace_name}")

175

except TerraformCommandError:

176

tf.set_workspace(workspace_name)

177

print(f"Using existing workspace: {workspace_name}")

178

179

# Deploy feature branch infrastructure

180

tf.apply(var={'environment': 'feature', 'branch': git_branch})

181

```

182

183

### Workspace Cleanup

184

185

```python

186

# List and clean up old workspaces

187

# Note: This uses the generic cmd method since there's no built-in list method

188

189

# Get list of workspaces

190

return_code, stdout, stderr = tf.cmd('workspace', 'list')

191

workspaces = [ws.strip().lstrip('* ') for ws in stdout.splitlines() if ws.strip()]

192

193

# Delete old feature workspaces

194

for workspace in workspaces:

195

if workspace.startswith('feature-') and workspace != current_workspace:

196

print(f"Cleaning up old workspace: {workspace}")

197

tf.delete_workspace(workspace)

198

```

199

200

## Error Handling

201

202

Workspace operations can fail for several reasons:

203

204

- **Workspace already exists** (create)

205

- **Workspace doesn't exist** (set, delete)

206

- **Attempting to delete current workspace** (delete)

207

208

```python

209

try:

210

tf.create_workspace('my-environment')

211

except TerraformCommandError as e:

212

if 'already exists' in e.err:

213

print("Workspace already exists, switching to it")

214

tf.set_workspace('my-environment')

215

else:

216

raise

217

```