SamuelFisher / TerraformPluginDotNet

Write Terraform providers in C#.
MIT License
46 stars 14 forks source link

Error when trying to create a Type of Object or map or list in Terraform #32

Closed mazobeid closed 1 year ago

mazobeid commented 1 year ago

Hello,

I want to create a terraform resource that have an attribute as object type. In C#, I create an IDictionary<string, object> but when execute the Terraform plan I got this error below: System.NotSupportedException: Unable to convert System.Collections.Generic.KeyValuePair`2[[System.String, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Object, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] to Terraform type.

Any idea how to create an object in terraform using the C# plugin ? ex.: resource "demo_player" "player" { name = "" player = { name = "" streams = "" } }

THank you

mcintyre321 commented 1 year ago

If you register a custom version of ISchemaBuilder it should work

class MySchemaBuilder : ISchemaBuilder
{
    ... existing code from SchemaBuilder.cs ...
  private static string GetTerraformType(Type t)
  {
   ... existing code ...

   // handle object instead of throwing exception
   var properties = t.GetProperties().Select(p => //maybe filter to only properties with [Key] attribute?
   {
      var key = p.GetCustomAttribute<KeyAttribute>() ?? throw new InvalidOperationException($"Missing {nameof(KeyAttribute)} on {p.Name} in {p.PropertyType.Name}.");

      return "\"" + key.StringKey + "\":" + GetTerraformType(p.PropertyType);
   });
   return "[\"object\",{"+ string.Join(",", properties) + "}]";   
}

I should probably get a PR raised...

SamuelFisher commented 1 year ago

Object types are now supported (535e246).

Please see this example: https://github.com/SamuelFisher/TerraformPluginDotNet/blob/535e24686b395a6271ce96f62c59c486ee408ea7/TerraformPluginDotNet.Test/TestResource.cs#L65-L68