Search code examples
goterraformbazel

Build a custom terraform provider with Bazel


I'm trying to build a custom terraform provider as the link: https://www.terraform.io/docs/extend/writing-custom-providers.html

Building with go is good. But I couldn't make the build work with Bazel.

load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
load("@bazel_gazelle//:def.bzl", "gazelle")

# gazelle:prefix nox
gazelle(name = "gazelle")

go_library(
    name = "go_default_library",
    srcs = [
        "main.go",
        "provider.go",
        "resource_server.go",
    ],
    importpath = "nox",
    visibility = ["//visibility:private"],
    deps = [
        "@com_github_hashicorp_terraform//helper/schema:go_default_library",
        "@com_github_hashicorp_terraform//plugin:go_default_library",
        "@com_github_hashicorp_terraform//terraform:go_default_library",
    ],
)

go_binary(
    name = "nox",
    embed = [":go_default_library"],
    visibility = ["//visibility:public"],
)

Got error:

/home/phuonglu/.cache/bazel/_bazel_phuonglu/1776745e55763483ee3d48d730fcf433/sandbox/linux-sandbox/935/execroot/__main__/external/com_github_hashicorp_terraform/vendor/google.golang
.org/api/option/option.go:163:54: cannot use "github.com/hashicorp/terraform/vendor/google.golang.org/api/internal".NewPoolResolver(int(w), o) (type *"github.com/hashicorp/terraform
/vendor/google.golang.org/api/internal".PoolResolver) as type "google.golang.org/grpc/naming".Resolver in argument to grpc.RoundRobin:
        *"github.com/hashicorp/terraform/vendor/google.golang.org/api/internal".PoolResolver does not implement "google.golang.org/grpc/naming".Resolver (wrong type for Resolve meth
od)
                have Resolve(string) ("github.com/hashicorp/terraform/vendor/google.golang.org/grpc/naming".Watcher, error)
                want Resolve(string) ("google.golang.org/grpc/naming".Watcher, error)

Other error:

ERROR: /home/phuonglu/.cache/bazel/_bazel_phuonglu/ad07032ffc2f7bfb6275d446f85e98cd/external/com_github_aws_aws_sdk_go/aws/signer/v4/BUILD.bazel:3:1: @com_github_aws_aws_sdk_go//aws
/signer/v4:go_default_library: no such attribute 'importpath_aliases' in 'go_library' rule

Solution

  • From the error you pasted, it looks like two copies of the package google.golang.org/grpc/naming are being incorporated into the same binary. This causes a type error: these are different packages (even if the code is identical), and their exported types are not interchangeable.

    The best thing to do here is probably to exclude the vendor directory in the github.com/hashicorp/terraform repository. You can add an argument to Gazelle in the corresponding go_repository rule in WORKSPACE. This prevents Gazelle from generating rules and resolving dependencies in that directory.

    go_repository(
        name = "com_github_hashicorp_terraform",
        importpath = "github.com/hashicorp/terraform",
        # ...
        build_extra_args = ["-exclude=vendor"],
    )