Skip to content

Commit 98054a6

Browse files
chore: Defines new schema scaffolding command using terraform code generation tools (#1827)
* chore: New schema scaffolding command using terraform code generation tools * shell linting fixes * addressing reviews related to contributing file * addressing reviews: remove redundant comments and improvements in script * adding validation when input name is not provided * shell linting fix * add new line at end of file Co-authored-by: Andrea Angiolillo <[email protected]> * refactor: moving schema-scaffold script over to scripts folder * rename input param of scaffold command from name to resource_name for alignment with docs command * include example for running command in makefile --------- Co-authored-by: Andrea Angiolillo <[email protected]>
1 parent d8eee33 commit 98054a6

File tree

3 files changed

+103
-5
lines changed

3 files changed

+103
-5
lines changed

CONTRIBUTING.md

+39-3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Thanks for your interest in contributing to MongoDB Atlas Terraform Provider, th
1212
- [Running Acceptance Tests](#running-acceptance-tests)
1313
- [Code and Test Best Practices](#code-and-test-best-practices)
1414
- [Creating New Resource and Data Sources](#creating-new-resources-and-data-sources)
15+
- [Scaffolding Initial Code and File Structure](#scaffolding-initial-code-and-file-structure)
16+
- [Scaffolding Schema and Model Definitions](#scaffolding-schema-and-model-definitions)
1517
- [Documentation Best Practices](#documentation-best-practices)
1618
- [Discovering New API features](#discovering-new-api-features)
1719

@@ -309,17 +311,51 @@ To do this you can:
309311

310312
### Creating New Resource and Data Sources
311313

312-
A scaffolding command was defined with the intention of speeding up development process, while also preserving common conventions throughout our codebase.
314+
A set of commands have been defined with the intention of speeding up development process, while also preserving common conventions throughout our codebase.
315+
316+
#### Scaffolding Initial Code and File Structure
313317

314318
This command can be used the following way:
315319
```bash
316-
make scaffold name=streamInstance type=resource
320+
make scaffold resource_name=streamInstance type=resource
317321
```
318-
- **name**: The name of the resource, which must be defined in camel case.
322+
- **resource_name**: The name of the resource, which must be defined in camel case.
319323
- **type**: Describes the type of resource being created. There are 3 different types: `resource`, `data-source`, `plural-data-source`.
320324

321325
This will generate resource/data source files and accompanying test files needed for starting the development, and will contain multiple comments with `TODO:` statements which give guidance for the development.
322326

327+
#### Scaffolding Schema and Model Definitions
328+
329+
Complementary to the `scaffold` command, there is a command which generates the initial Terraform schema definition and associated Go types for a resource or data source. This processes leverages [Code Generation Tools](https://developer.hashicorp.com/terraform/plugin/code-generation) developed by HashiCorp, which in turn make use of the [Atlas Admin API](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/) OpenAPI Specification.
330+
331+
##### Running the command
332+
333+
Both `tfplugingen-openapi` and `tfplugingen-framework` must be installed. This can be done by running `make tools`.
334+
335+
The command takes a single argument which specifies the resource or data source where the code generation is run, defined in camel case, e.g.:
336+
```bash
337+
make scaffold-schemas resource_name=streamInstance
338+
```
339+
340+
As a pre-requiste, the relevant resource/data source directory must define a configuration file in the path `./internal/service/<resource_name>/tfplugingen/generator_config.yml`. The content of this file will define which resource and/or data source schemas will be generated by providing the API endpoints they are mapped to. See the [Generator Config](https://developer.hashicorp.com/terraform/plugin/code-generation/openapi-generator#generator-config) documentation for more information on configuration options. An example defined in our repository can be found in [searchdeployment/tfplugingen/generator_config.yml](https://github.com/mongodb/terraform-provider-mongodbatlas/blob/master/internal/service/searchdeployment/tfplugingen/generator_config.yml).
341+
342+
As a result of the execution, the schema definitions and associated model types will be defined in separate files depending on the resources and data sources that were configured in the generator_config.yml file:
343+
- `data_source_<resource_name>_schema.go`
344+
- `resource_<resource_name>_schema.go`
345+
346+
Note: if the resulting file paths already exist the content will be stored in files with a `_gen.go` postfix, and in this case any content will be overwritten. This can be useful for comparing the latest autogenerated schema against the existing implementation.
347+
348+
##### Considerations over generated schema and types
349+
350+
- Generated Go type should include a TF prefix to follow the convention in our codebase, this will not be present in generated code.
351+
- Some attribute names may need to be adjusted if there is a difference in how they are named in Terraform vs the API. An examples of this is `group_id``project_id`.
352+
- Inferred characteristics of an attribute (computed, optional, required) may not always be an accurate representation and should be revised. Details of inference logic can be found in [OAS Types to Provider Attributes](https://github.com/hashicorp/terraform-plugin-codegen-openapi/blob/main/DESIGN.md#oas-types-to-provider-attributes).
353+
- Missing [sensitive](https://developer.hashicorp.com/terraform/plugin/framework/handling-data/attributes/string#sensitive) field in attributes.
354+
- Missing plan modifiers such as `RequiresReplace()` in attributes.
355+
- Terraform specific attributes such as [timeouts](https://developer.hashicorp.com/terraform/plugin/framework/resources/timeouts#specifying-timeouts-in-configuration) need to be included manually.
356+
- If nested attributes are defined a set of helper functions are generated for using the model. The usage of the generated functions can be considered optional as the current documentation is not very clear on the usage (More details in [terraform-plugin-codegen-framework/issues/80](https://github.com/hashicorp/terraform-plugin-codegen-framework/issues/80)).
357+
358+
323359
## Documentation Best Practices
324360

325361
- In our documentation, when a resource field allows a maximum of only one item, we do not format that field as an array. Instead, we create a subsection specifically for this field. Within this new subsection, we enumerate all the attributes of the field. Let's illustrate this with an example: [cloud_backup_schedule.html.markdown](https://github.com/mongodb/terraform-provider-mongodbatlas/blob/master/website/docs/r/cloud_backup_schedule.html.markdown?plain=1#L207)

GNUmakefile

+10-2
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,20 @@ link-git-hooks: ## Install git hooks
115115
update-atlas-sdk: ## Update the atlas-sdk dependency
116116
./scripts/update-sdk.sh
117117

118-
# details on usage can be found in CONTRIBUTING.md under "Creating New Resource and Data Sources"
118+
# e.g. run: make scaffold resource_name=streamInstance type=resource
119+
# - type argument can have the values: `resource`, `data-source`, `plural-data-source`.
120+
# details on usage can be found in CONTRIBUTING.md under "Scaffolding initial Code and File Structure"
119121
.PHONY: scaffold
120122
scaffold:
121-
@go run ./tools/scaffold/*.go $(name) $(type)
123+
@go run ./tools/scaffold/*.go $(resource_name) $(type)
122124
@echo "Reminder: configure the new $(type) in provider.go"
123125

126+
# e.g. run: make scaffold-schemas resource_name=streamInstance
127+
# details on usage can be found in CONTRIBUTING.md under "Scaffolding Schema and Model Definitions"
128+
.PHONY: scaffold-schemas
129+
scaffold-schemas:
130+
@scripts/schema-scaffold.sh $(resource_name)
131+
124132

125133
.PHONY: generate-doc
126134
generate-doc: ## Generate the resource documentation via tfplugindocs

scripts/schema-scaffold.sh

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
: "${1?"Name of resource or data source must be provided."}"
5+
6+
# URL to download Atlas Admin API Spec
7+
atlas_admin_api_spec="https://raw.githubusercontent.com/mongodb/atlas-sdk-go/main/openapi/atlas-api-transformed.yaml"
8+
9+
echo "Downloading api spec"
10+
curl -L "$atlas_admin_api_spec" -o "./api-spec.yml"
11+
12+
resource_name=$1
13+
resource_name_lower_case="$(echo "$resource_name" | awk '{print tolower($0)}')"
14+
resource_name_snake_case="$(echo "$resource_name" | perl -pe 's/([a-z0-9])([A-Z])/$1_\L$2/g')"
15+
16+
pushd "./internal/service/$resource_name_lower_case" || exit
17+
18+
# Running HashiCorp code generation tools
19+
20+
echo "Generating provider code specification"
21+
# Generate provider code specification using api spec and generator config
22+
tfplugingen-openapi generate --config ./tfplugingen/generator_config.yml --output provider-code-spec.json ../../../api-spec.yml
23+
24+
echo "Generating resource and data source schemas and models"
25+
# Generate resource and data sources schemas using provider code specification
26+
tfplugingen-framework generate data-sources --input provider-code-spec.json --output ./ --package "$resource_name_lower_case"
27+
tfplugingen-framework generate resources --input provider-code-spec.json --output ./ --package "$resource_name_lower_case"
28+
29+
30+
rm ../../../api-spec.yml
31+
rm provider-code-spec.json
32+
33+
34+
rename_file() {
35+
local old_name=$1
36+
local new_name=$2
37+
38+
# Check if the original file exists
39+
if [ -e "$old_name" ]; then
40+
# If the target new name exists, use the alternative name with _gen
41+
if [ -e "$new_name" ]; then
42+
echo "File $new_name already exists, writing content in ${new_name%.*}_gen.go"
43+
new_name="${new_name%.*}_gen.go"
44+
fi
45+
46+
echo "Created file in $new_name"
47+
# Rename the file
48+
mv "$old_name" "$new_name"
49+
fi
50+
}
51+
52+
rename_file "${resource_name_snake_case}_data_source_gen.go" "data_source_${resource_name_snake_case}_schema.go"
53+
rename_file "${resource_name_snake_case}s_data_source_gen.go" "data_source_${resource_name_snake_case}s_schema.go"
54+
rename_file "${resource_name_snake_case}_resource_gen.go" "resource_${resource_name_snake_case}_schema.go"

0 commit comments

Comments
 (0)