Package: pulumiverse-matchbox
Terraform Bridge Provider BoilerplateThis repository contains boilerplate code for building a new Pulumi provider which wraps an existing Terraform provider.BackgroundThis repository is part of theguide for authoring and publishing a Pulumi Package.Learn about the concepts behindPulumi Packages.Creating a Pulumi Terraform Bridge ProviderThe following instructions cover:providers maintained by Pulumi (denoted with a "Pulumi Official" checkmark on the Pulumi registry)providers published and maintained by the Pulumi community, referred to as "third-party" providersWe showcase a Pulumi-owned provider based on an upstream provider namedterraform-provider-foo.  Substitute appropriate values below for your use case.Note: If the name of the desired Pulumi provider differs from the name of the Terraform provider, you will need to carefully distinguish between the references - seehttps://github.com/pulumi/pulumi-azurefor an example.PrerequisitesEnsure the following tools are installed and present in your$PATH:pulumictlGo 1.17or 1.latestNodeJS14.x.  We recommend usingnvmto manage NodeJS installations.YarnTypeScriptPython(called aspython3).  For recent versions of MacOS, the system-installed version is fine..NETCreating and Initializing the RepositoryPulumi offers this repository as aGitHub template repositoryfor convenience.  From this repository:Click "Use this template".Set the following options:Owner: pulumi (third-party: your GitHub organization/username)Repository name: pulumi-foo (third-party: preface your repo name with "pulumi" as standard practice)Description: Pulumi provider for FooRepository type: PublicClone the generated repository.From the templated repository:Run the following command to update files to use the name of your provider (third-party: use your GitHub organization/username):makeprepareNAME=fooREPOSITORY=github.com/pulumi/pulumi-fooThis will do the following:rename folders inprovider/cmdtopulumi-resource-fooandpulumi-tfgen-fooreplace dependencies inprovider/go.modto reflect your repository namefind and replace all instances of the boilerplatematchboxwith theNAMEof your provider.Note for third-party providers:Make sure to set the correct GitHub organization/username in all files referencing your provider as a dependency:examples/go.modprovider/resources.gosdk/go.modprovider/cmd/pulumi-resource-foo/main.goprovider/cmd/pulumi-tfgen-foo/main.goModifyREADME-PROVIDER.mdto include the following (we'll rename it toREADME.mdtoward the end of this guide):Any desired build status badges.An introductory paragraph describing the type of resources the provider manages, e.g. "The Foo provider for Pulumi manages resources forFoo.In the "Installing" section, correct package names for the various SDK libraries in the languages Pulumi supports.In the "Configuration" section, any configurable options for the provider.  These may include, but are not limited to, environment variables or options that can be set viapulumi config set.In the "Reference" section, provide a link to the to-be-published documentation.Feel free to refer tothe Pulumi AWS provider READMEas an example.Composing the Provider Code - PrerequisitesPulumi provider repositories have the following general structure:examples/contains sample code which may optionally be included as integration tests to be run as part of a CI/CD pipeline.provider/contains the Go code used to create the provider as well as generate the SDKs in the various languages that Pulumi supports.provider/cmd/pulumi-tfgen-foogenerates the Pulumi resource schema (schema.json), based on the Terraform provider's resources.provider/cmd/pulumi-resource-foogenerates the SDKs in all supported languages from the schema, placing them in thesdk/folder.provider/pkg/resources.gois the location where we will define the Terraform-to-Pulumi mappings for resources.sdk/contains the generated SDK code for each of the language platforms that Pulumi supports, with each supported platform in a separate subfolder.Inprovider/go.mod, add a reference to the upstream Terraform provider in therequiresection, e.g.github.com/foo/terraform-provider-foov0.4.0Inprovider/resources.go, ensure the reference in theimportsection uses the correct Go module path, e.g.:github.com/foo/terraform-provider-foo/fooDownload the dependencies:cdprovider&&gomodtidy&&cd-Create the schema by running the following command:maketfgenNote warnings about unmapped resources and data sources in the command's output.  We map these in the next section, e.g.:warning: resource foo_something not found in provider map; skipping
warning: resource foo_something_else not found in provider map; skipping
warning: data source foo_something not found in provider map; skipping
warning: data source foo_something_else not found in provider map; skippingAdding Mappings, Building the Provider and SDKsIn this section we will add the mappings that allow the interoperation between the Pulumi provider and the Terraform provider.  Terraform resources map to an identically named concept in Pulumi.  Terraform data sources map to plain old functions in your supported programming language of choice.  Pulumi also allows provider functions and resources to be grouped intonamespacesto improve the cohesion of a provider's code, thereby making it easier for developers to use.  If your provider has a large number of resources, consider using namespaces to improve usability.The following instructions all pertain toprovider/resources.go, in the section of the code where we construct atfbridge.ProviderInfoobject:Add resource mappings:For each resource in the provider, add an entry in theResourcesproperty of thetfbridge.ProviderInfo, e.g.:// Most providers will have all resources (and data sources) in the main module.// Note the mapping from snake_case HCL naming conventions to UpperCamelCase Pulumi SDK naming conventions.// The name of the provider is omitted from the mapped name due to the presence of namespaces in all supported Pulumi languages."foo_something":{Tok:tfbridge.MakeResource(mainPkg,mainMod,"Something")},"foo_something_else":{Tok:tfbridge.MakeResource(mainPkg,mainMod,"SomethingElse")},Add CSharpName (if necessary):Dotnet does not allow for fields named the same as the enclosing type, which sometimes results in errors during the dotnet SDK build.
If you see something likeerror CS0542: 'ApiKey': member names cannot be the same as their enclosing type [/Users/guin/go/src/github.com/pulumi/pulumi-artifactory/sdk/dotnet/Pulumi.Artifactory.csproj]you'll want to give your Resource a CSharpName, which can have any value that makes sense:"foo_something_dotnet":{Tok:tfbridge.MakeResource(mainPkg,mainMod,"SomethingDotnet"),Fields:map[string]*tfbridge.SchemaInfo{"something_dotnet":{CSharpName:"SpecialName",},},},See the underlying terraform-bridge code here.Add data source mappings:For each data source in the provider, add an entry in theDataSourcesproperty of thetfbridge.ProviderInfo, e.g.:// Note the 'get' prefix for data sources"foo_something":{Tok:tfbridge.MakeDataSource(mainPkg,mainMod,"getSomething")},"foo_something_else":{Tok:tfbridge.MakeDataSource(mainPkg,mainMod,"getSomethingElse")},Add documentation mapping (sometimes needed):If the upstream provider's repo is not a part of theterraform-providersGitHub organization, specify theGitHubOrgproperty oftfbridge.ProviderInfoto ensure that documentation is picked up by the codegen process, and that attribution for the upstream provider is correct, e.g.:GitHubOrg:"foo",Add provider configuration overrides (not typically needed):Pulumi's Terraform bridge automatically detects configuration options for the upstream provider.  However, in rare cases these settings may need to be overridden, e.g. if we want to change an environment variable default fromAPI_KEYtoFOO_API_KEY.  Examples of common uses cases:"additional_required_parameter":{},"additional_optional_string_parameter":{Default:&tfbridge.DefaultInfo{Value:"default_value",},"additional_optional_boolean_parameter":{Default:&tfbridge.DefaultInfo{Value:true,},// Renamed environment variables can be accounted for like so:"apikey":{Default:&tfbridge.DefaultInfo{EnvVars:[]string{"FOO_API_KEY"},},Build the provider binary and ensure there are no warnings about unmapped resources and no warnings about unmapped data sources:makeproviderYou may see warnings about documentation and examples, including "unexpected code snippets".  These can be safely ignored for now.  Pulumi will add additional documentation on mapping docs in a future revision of this guide.Build the SDKs in the various languages Pulumi supports:makebuild_sdksEnsure the Golang SDK is a proper go module:cdsdk&&gomodtidy&&cd-This will pull in the correct dependencies insdk/go.modas well as setting the dependency tree insdk/go.sum.Finally, ensure the provider code conforms to Go standards:makelint_providerFix any issues found by the linter.Note:If you make revisions to code inresources.go, you must re-run themake tfgentarget to regenerate the schema.
Themake tfgentarget will take the fileschema.jsonand serialize it to a byte array so that it can be included in the build output.
(This is a holdover from Go 1.16, which does not have the ability to directly embed text files. We are working on removing the need for this step.)Sample ProgramIn this section, we will create a Pulumi program in TypeScript that utilizes the provider we created to ensure everything is working properly.Create an account with the provider's service and generate any necessary credentials, e.g. API keys.Email:bot@pulumi.comPassword: (Create a random password in 1Password with the  maximum length and complexity allowed by the provider.)Ensure all secrets (passwords, generated API keys) are stored in Pulumi's 1Password vault.Copy thepulumi-resource-foobinary generated bymake providerand place it in your$PATH($GOPATH/binis a convenient choice), e.g.:cpbin/pulumi-resource-foo$GOPATH/binTell Yarn to use your local copy of the SDK:makeinstall_nodejs_sdkCreate a new Pulumi program in theexamples/directory, e.g.:mkdirexamples/my-example/ts# Change "my-example" to something more meaningful.cdexamples/my-example/ts
puluminewtypescript# (Go through the prompts with the default values)npminstall
yarnlink@pulumi/fooCreate a minimal program for the provider, i.e. one that creates the smallest-footprint resource.  Place this code inindex.ts.Configure any necessary environment variables for authentication, e.g$FOO_USERNAME,$FOO_TOKEN, in your local environment.Ensure the program runs successfully viapulumi up.Once the program completes successfully, verify the resource was created in the provider's UI.Destroy any resources created by the program viapulumi destroy.Optionally, you may create additional examples for SDKs in other languages supported by Pulumi:Python:mkdirexamples/my-example/pycdexamples/my-example/py
puluminewpython# (Go through the prompts with the default values)sourcevenv/bin/activate# use the virtual Python env that Pulumi sets up for youpipinstallpulumi_fooFollow the steps above to verify the program runs successfully.Add End-to-end TestingWe can run integration tests on our examples using the*_test.gofiles in theexamples/folder.Add code toexamples_nodejs_test.goto call the example you created, e.g.:// Swap out MyExample and "my-example" below with the name of your integration test.funcTestAccMyExampleTs(t*testing.T){test:=getJSBaseOptions(t).With(integration.ProgramTestOptions{Dir:filepath.Join(getCwd(t),"my-example","ts"),})integration.ProgramTest(t,&test)}Add a similar function for each example that you want to run in an integration test.  For examples written in other languages, create similar files forexamples_${LANGUAGE}_test.go.You can run these tests locally via Make:maketestYou can also run each test file separately via test tags:cdexamples&&gotest-v-tags=nodejsConfiguring CI with GitHub ActionsThird-party providersFollow the instructions laid out in thedeployment templates.Pulumi InternalIn this section, we'll add the necessary configuration to work with GitHub Actions for Pulumi's standard CI/CD workflows for providers.Generate GitHub workflows perthe instructions in the ci-mgmt repositoryand copy to.github/in this repository.Ensure that any required secrets are present as repository-levelsecretsin GitHub.  These will be used by the integration tests during the CI/CD process.Repository settings: ToggleAllow auto-mergeon in your provider repo to automate GitHub Actions workflow updates.Final StepsEnsure all required configurations (API keys, etc.) are documented in README-PROVIDER.md.Replace this file with the README for the provider and push your changes:mvREADME-PROVIDER.mdREADME.mdIf publishing the npm package fails during the "Publish SDKs" Action, perform the following steps:Go toNPM Packagesand sign in as pulumi-bot.Click on the bot's profile pic and navigate to "Packages".On the left, under "Organizations, click on the Pulumi organization.On the last page of the listed packages, you should see the new package.Under "Settings", set the Package Status to "public".Now you are ready to use the provider, cut releases, and have some well-deserved :ice_cream:!Building the Provider LocallyThere are 2 ways the provider can be built locally:make providerwill use the current operating system and architecture to create a binary that can be used on your PATH.To build the provider for another set of operating systems / architectures, the project usesgoreleaser.
Goreleaser, a CLI tool, that allows a user to build a matrix of binaries.Create a.goreleaser.ymlfile in the root of your project:archives:-id:archivename_template:"{{.Binary}}-{{.Tag}}-{{.Os}}-{{.Arch}}"before:hooks:-make tfgenbuilds:-binary:pulumi-resource-matchboxdir:providergoarch:-amd64-arm64goos:-darwin-windows-linuxignore:[]ldflags:--X github.com/pulumiverse/pulumi-matchbox/provider/pkg/version.Version={{.Tag}}main:./cmd/pulumi-resource-matchbox/sort:ascuse:gitrelease:disable:falsesnapshot:name_template:"{{.Tag}}-SNAPSHOT"To build the provider for the combination of architectures and operating systems, you can run the following CLI command:goreleaserbuild--rm-dist--skip-validateThat will ensure that a list of binaries are available to use:▶treedist
dist
├──CHANGELOG.md
├──artifacts.json
├──config.yaml
├──metadata.json
├──pulumi-matchbox_darwin_amd64_v1
│└──pulumi-resource-matchbox
├──pulumi-matchbox_darwin_arm64
│└──pulumi-resource-matchbox
├──pulumi-matchbox_linux_amd64_v1
│└──pulumi-resource-matchbox
├──pulumi-matchbox_linux_arm64
│└──pulumi-resource-matchbox
├──pulumi-matchbox_windows_amd64_v1
│└──pulumi-resource-matchbox.exe
└──pulumi-matchbox_windows_arm64└──pulumi-resource-matchbox.exeAny of the provider binaries can be used to target the correct machine architectureThe Shim PatternIf you receive the following error:use of internal package github.com/example/terraform-provider-example/internal/provider not allowed, you need to use
the shim model below, and replace the example item:mkdir-pprovider/shim
cat<<-EOF> provider/shim/go.modmodule github.com/example/terraform-provider-example/shimgo 1.18require github.com/hashicorp/terraform-plugin-sdk/v2 v2.22.0require github.com/example/terraform-provider-example v1.0.0EOFcat<<-EOF> provider/shim/shim.gopackage shimimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema""github.com/example/terraform-provider-example/internal/provider")// fix provider.Provider here to match whats in internal/providerfunc Provider() *schema.Provider {return provider.Provider()}EOFcdprovider/shim/&&gomodtidy&&cd../../

cat<<EOF>> provider/go.modreplace github.com/example/terraform-provider-example/shim => ./shimrequire github.com/example/terraform-provider-example/shim v0.0.0EOFcdprovider&&gomodtidy