Creating a custom provider Data Source that takes arguments

Hello!

New to Terraform/provider creation (using the plugin framework), and I have a very basic question that I hope someone can help me with!

Following the tutorial (which is great, by the way), I’m able to create a very simple data source that takes no parameters. So my main.tf with the following stanza works fine:

data "shepherd_projects" "test" {
}

So my provider (“shepherd”) has a data source called “project”. This works fine.

My problem comes when I want to be able to specify that this data source needs to take some arguments. So my stanza should/must look like:

data "shepherd_projects" "test" {
  department_id = "893eb7c8-6141-4ea5-92cb-5a84c463461f"
  region_id = "cnco1"
}

(My code needs to take that department_id and region_id and use it to call my own shepherd SDK in the data source Read() method)

How do I implement this?
Running “apply” immediately errors out with complaints that the two arguments are “Unsupported argument”

The tutorial doesn’t cover this (only shows how to create a data source with zero arguments) - and reading up on the core documentation for Data Sources - there is a discussion on how to pass provider configuration to the data source - but not how to get config data from the data source stanza itself.

Googling around the internet, I see examples on how to do this using the SDKV2, but I don’t see any for the plugin framework. This seems like a pretty basic functionality that would be useful in many custom providers, so I’m going nuts thinking I’m missing some big picture.

Any help - or pointers to code samples - would be greatly appreciated. Thank you!

Start thinking in terms of “attributes” rather than “arguments”.

Your “no arguments” data source should have a bunch of attributes which are marked Computed: true in the schema.

Add some additional attributes to your model struct, and mark them with either Required: true or Optional: true in the schema.

Thanks for the reply - while I actually did have attributes defined in my schema - I had nested them incorrectly. Fixing up the schema to allow for proper nesting, I was then able to get the attributes I needed in the Read method and was able to proceed.

So, fixing the schema method was indeed the solution here. Thank you!

Cool. Glad you figured it out.

can you please share what helped you?
because looks like I’m stuck there.

I don’t see how to read/access passed arguments inside Read method.

Maybe you can show example of how to access them? (I can pass arguments but don’t see how to read them properly)

Thanks.

The first things your Read() method should do are:

  • Instantiate a variable of the type which matches your schema (a struct with tfsdk tags)
  • Unpack the configuration supplied by the user onto that struct using req.Config.Get()

Like this.