Advanced Usage
This guide covers more complex scenarios and tips for getting the most out of the Terraform Editor API. We'll look at larger, multi-step edits, dynamic selectors, mixed data sources, and ways to integrate the API into bigger automation workflows.
1. Combining Multiple Operations in One Request
Scenario
You need to:
- Add a new resource.
- Update an existing one.
- Delete an attribute from yet another.
Instead of making three separate calls, you can combine all these operations in one request. This approach ensures you keep related changes together, making them easier to manage and reason about.
{
"code": "resource \"aws_instance\" \"old\" {\n ami = \"ami-1234abcd\"\n}\n",
"edits": {
"add": {
"resource": {
"aws_instance": {
"new_server": [
{
"attributes": {
"ami": "ami-9876wxyz"
}
}
]
}
}
},
"update": {
"resource": {
"aws_instance": {
"old": [
{
"attributes": {
"ami": "ami-updatedabcd"
}
}
]
}
}
},
"delete": {
"resource": {
"aws_security_group": {
"deprecated_sg": []
}
}
}
}
}
- Single Transaction: The API adds
"aws_instance.new_server"
, updates"aws_instance.old"
, and deletes"aws_security_group.deprecated_sg"
. - Why Useful: Keeps your pipeline simpler by reducing the number of separate API calls.
2. Dynamic Selectors Using Attribute Maps
When your configuration is generated from dynamic data, you may not know in advance which selectors you need. You can build a selector map on the fly—like a where
clause—based on external inputs.
Example: Suppose you have an environment variable specifying which region to target:
export TARGET_REGION="us-west1"
Then in your script that calls the Terraform Editor API, you might do something like:
WHERE_CLAUSE="{\"region\": \"${TARGET_REGION}\"}"
curl -X POST -H "Content-Type: application/json" \
-d "{
\"code\": \"provider \\\"google\\\" {...}\",
\"edits\": {
\"update\": {
\"provider\": {
\"google\": [
{
\"where\": $WHERE_CLAUSE,
\"attributes\": {
\"region\": \"${TARGET_REGION}-updated\"
}
}
]
}
}
}
}" \
https://app-terraform-editor-api-use-dx-dev.azurewebsites.net/edit
- Benefit: Your pipeline or script can adapt selectors at runtime, ensuring your request always targets the right block(s).
3. Merging Partial Files
Sometimes your Terraform code is split across multiple files, or you only need to modify a subset of your overall configuration. Because the API works on one code
string at a time, you have a few options:
- Concatenate relevant
.tf
files into one string before sending. - Apply changes iteratively to each file's content.
- Maintain a single aggregated string in memory, repeatedly calling the API after each change (like a patch series).
Example (concatenating two .tf
files into one request):
cat resources.tf providers.tf > combined.tf
curl -X POST -H "Content-Type: application/json" \
-d "{
\"code\": \"$(cat combined.tf)\",
\"edits\": {
\"delete\": {
\"variable\": {
\"unused_var\": []
}
}
}
}" \
https://app-terraform-editor-api-use-dx-dev.azurewebsites.net/edit
- Result:
unused_var
is removed from the combined code, which you can then split back or keep aggregated as needed.
4. Handling Large or Complex Configurations
For very large Terraform codebases, your requests might become unwieldy. Consider:
- Splitting your edits into logical chunks (e.g., one request focusing on providers, another on resources).
- Using a Git workflow: Commit partial changes after each edit, giving you a clear revision history.
- Applying incremental merges: If your config changes frequently, store the intermediate merged result and feed it into subsequent requests.
5. Staged Editing with Intermediate Checks
If you're unsure about a complex change, try staging the transformation in parts:
- Step 1: Update providers.
- Step 2: Validate new provider blocks (e.g., run
terraform validate
). - Step 3: Update resources.
- Step 4: Validate again, possibly run
terraform plan
.
This approach keeps each change smaller and easier to debug. You can script this with a series of Terraform Editor API calls, applying the updated edited_code
from each step as the code
input for the next step.
6. Mixed Data Sources: JSON vs. String for edits
The API supports passing edits
as either a JSON object or a JSON string. In advanced workflows, you might generate the edits
JSON in one language or environment, then embed it as a string in another.
Example: Generating edits
in Python, then passing it to a Bash script:
edits = {
"update": {
"provider": {
"google": [
{
"where": {"alias": "asia"},
"attributes": {
"region": "asia-south1"
}
}
]
}
}
}
print(json.dumps(edits))
Then in your Bash script:
PYTHON_OUTPUT=$(python generate_edits.py)
curl -X POST -H "Content-Type: application/json" \
-d "{
\"code\": \"provider \\\"google\\\" {...}\",
\"edits\": \"$PYTHON_OUTPUT\"
}" \
https://app-terraform-editor-api-use-dx-dev.azurewebsites.net/edit
- Why Bother?: Sometimes your main automation tool only works with string parameters. Or you need to store the edits JSON in a place where only strings are allowed (like certain CI/CD config variables).
7. Rollback & Error Recovery
The Terraform Editor API only returns the final merged code. If an error occurs (like an ambiguous match), it won't partially apply your edits. You'll see an error response, and your code remains unchanged.
For a rollback strategy:
- Keep the Original Code: If the API fails, just reuse your unmodified
code
. - Create Git Commits: If you're storing code in source control, commit after each successful transformation so you can revert if something goes wrong downstream.
8. Putting It All Together
Advanced usage often involves chaining multiple operations, integrating with external data, and carefully structuring requests so they're maintainable. Here are some final suggestions:
- Organize Large Edits into multiple smaller ones, each with a clear purpose.
- Use Dynamic Selectors when your environment is in flux (e.g., ephemeral test environments).
- Validate or Plan after each significant edit if you're unsure about the resulting configuration.
For more detailed, real-world examples, check out the Examples guide. If you want broader guidance on best practices—like how to name or structure resources—head to Best Practices.