├── e2e ├── providers │ └── example.com │ │ └── example │ │ └── sampleprovider │ │ └── .gitkeep ├── resource.tf ├── cli.tfrc └── conf.tf ├── TerraformPluginDotNet ├── Properties │ └── AssemblyInfo.cs ├── ResourceProvider │ ├── ResourceProvider.cs │ ├── ResourceRegistryRegistration.cs │ ├── DataSourceRegistryRegistration.cs │ ├── IDataSourceProvider.cs │ ├── IResourceRegistryContext.cs │ ├── TerraformResourceProviderException.cs │ ├── IResourceProvider.cs │ ├── IResourceUpgrader.cs │ ├── DefaultResourceUpgrader.cs │ ├── ServiceCollectionResourceRegistryContext.cs │ ├── ResourceRegistry.cs │ ├── DataSourceProviderHost.cs │ └── ResourceProviderHost.cs ├── ProviderConfig │ ├── IProviderConfigurator.cs │ ├── ProviderConfigurationRegistry.cs │ └── ProviderConfigurationHost.cs ├── PluginHostCertificate.cs ├── Schemas │ ├── Types │ │ ├── ITerraformTypeBuilder.cs │ │ ├── TerraformType.cs │ │ └── TerraformTypeBuilder.cs │ ├── ISchemaBuilder.cs │ └── SchemaBuilder.cs ├── Resources │ ├── RequiredAttribute.cs │ ├── ComputedAttribute.cs │ └── SchemaVersionAttribute.cs ├── Serialization │ ├── IDynamicValueSerializer.cs │ ├── DefaultDynamicValueSerializer.cs │ └── ComputedStringValueFormatter.cs ├── EndpointRouteBuilderExtensions.cs ├── TerraformPluginHostOptions.cs ├── Startup.cs ├── serilog.json ├── TerraformPluginDotNet.csproj ├── WebHostBuilderExtensions.cs ├── HostApplicationLifetimeExtensions.cs ├── ServiceCollectionExtensions.cs ├── TerraformPluginHost.cs ├── CertificateGenerator.cs ├── Services │ └── Terraform5ProviderService.cs └── Protos │ └── tfplugin5.2.proto ├── samples ├── SchemaUpgrade │ ├── README.md │ ├── SchemaUpgrade │ │ ├── PreviousVersions │ │ │ └── UpgradableResourceV1.cs │ │ ├── SchemaUpgrade.csproj │ │ ├── UpgradableResourceV2.cs │ │ ├── Program.cs │ │ ├── UpgradableResourceProvider.cs │ │ └── UpgradableResourceUpgrader.cs │ └── SchemaUpgrade.Test │ │ ├── terraform.tfstate │ │ ├── SchemaUpgrade.Test.csproj │ │ └── UpgradableResourceProviderTest.cs ├── DataSourceProvider │ ├── README.md │ ├── DataSourceProvider │ │ ├── Configuration.cs │ │ ├── SampleConfigurator.cs │ │ ├── SampleDataSource.cs │ │ ├── SampleDataSourceProvider.cs │ │ ├── Program.cs │ │ └── DataSourceProvider.csproj │ └── DataSourceProvider.Test │ │ ├── DataSourceProvider.Test.csproj │ │ └── SampleDataSourceProviderTest.cs └── SampleProvider │ ├── SampleProvider │ ├── Configuration.cs │ ├── SampleConfigurator.cs │ ├── SampleFileResource.cs │ ├── Program.cs │ ├── SampleProvider.csproj │ └── SampleFileResourceProvider.cs │ ├── README.md │ └── SampleProvider.Test │ ├── SampleProvider.Test.csproj │ └── SampleProviderTest.cs ├── stylecop.json ├── version.json ├── Directory.Build.props ├── .editorconfig ├── TerraformPluginDotNet.Test ├── TerraformPluginDotNet.Test.csproj ├── Functional │ ├── TestResourceProvider.cs │ └── TerraformResourceTest.cs ├── ResourceProvider │ └── ResourceRegistryTest.cs ├── Schemas │ ├── Types │ │ ├── TerraformTypeTest.cs │ │ └── TerraformTypeBuilderTest.cs │ └── SchemaBuilderTest.cs └── TestResource.cs ├── TerraformPluginDotNet.Testing ├── ITerraformTestInstance.cs ├── TerraformPluginDotNet.Testing.csproj ├── TerraformCommandException.cs ├── TerraformTestInstanceExtensions.cs ├── TerraformTestInstance.cs ├── TerraformTestHost.cs └── Json │ └── TerraformJson.cs ├── LICENSE ├── StyleCopRules.ruleset ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── README.md └── TerraformPluginDotNet.sln /e2e/providers/example.com/example/sampleprovider/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /e2e/resource.tf: -------------------------------------------------------------------------------- 1 | resource "sampleprovider_file" "demo_file" { 2 | path = "./file.txt" 3 | content = "Hello, world!" 4 | } 5 | -------------------------------------------------------------------------------- /e2e/cli.tfrc: -------------------------------------------------------------------------------- 1 | provider_installation { 2 | filesystem_mirror { 3 | path = "./providers" 4 | include = ["example.com/*/*"] 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("TerraformPluginDotNet.Test")] 4 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/ResourceProvider.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | public abstract class ResourceProvider 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/README.md: -------------------------------------------------------------------------------- 1 | SchemaUpgrade 2 | ============== 3 | 4 | Demonstrates how to use versioned resource schemas and upgrade from an older schema to the latest version. 5 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/ResourceRegistryRegistration.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | record ResourceRegistryRegistration(string ResourceName, Type Type); 4 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/DataSourceRegistryRegistration.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | record DataSourceRegistryRegistration(string ResourceName, Type Type); 4 | -------------------------------------------------------------------------------- /stylecop.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", 3 | "settings": {} 4 | } 5 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ProviderConfig/IProviderConfigurator.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ProviderConfig; 2 | 3 | public interface IProviderConfigurator 4 | { 5 | Task ConfigureAsync(T config); 6 | } 7 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/IDataSourceProvider.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | public interface IDataSourceProvider 4 | { 5 | Task ReadAsync(T request); 6 | } 7 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/PluginHostCertificate.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography.X509Certificates; 2 | 3 | namespace TerraformPluginDotNet; 4 | 5 | public record PluginHostCertificate(X509Certificate2 Certificate); 6 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Schemas/Types/ITerraformTypeBuilder.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.Schemas.Types; 2 | 3 | public interface ITerraformTypeBuilder 4 | { 5 | TerraformType GetTerraformType(Type t); 6 | } 7 | -------------------------------------------------------------------------------- /e2e/conf.tf: -------------------------------------------------------------------------------- 1 | provider "sampleprovider" {} 2 | 3 | terraform { 4 | required_providers { 5 | sampleprovider = { 6 | source = "example.com/example/sampleprovider" 7 | version = "1.0.0" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ProviderConfig/ProviderConfigurationRegistry.cs: -------------------------------------------------------------------------------- 1 | using Tfplugin5; 2 | 3 | namespace TerraformPluginDotNet.ProviderConfig; 4 | 5 | record ProviderConfigurationRegistry( 6 | Schema ConfigurationSchema, 7 | Type ConfigurationType); 8 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/IResourceRegistryContext.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | public interface IResourceRegistryContext 4 | { 5 | void RegisterResource(string resourceName); 6 | 7 | void RegisterDataSource(string dataSourceName); 8 | } 9 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Resources/RequiredAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.Resources; 2 | 3 | /// 4 | /// Indicates that a value is required. 5 | /// 6 | [AttributeUsage(AttributeTargets.Property)] 7 | public class RequiredAttribute : Attribute 8 | { 9 | } 10 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Resources/ComputedAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.Resources; 2 | 3 | /// 4 | /// Indicates that a value is "known after apply". 5 | /// 6 | [AttributeUsage(AttributeTargets.Property)] 7 | public class ComputedAttribute : Attribute 8 | { 9 | } 10 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/README.md: -------------------------------------------------------------------------------- 1 | DataSourceProvider 2 | ============== 3 | 4 | Basic example of a custom data source provider. 5 | 6 | This provider defines a new resource type that provides some dummy data. 7 | 8 | ```hcl 9 | data "datasourceprovider_data" "demo_data" { 10 | id = "test" 11 | } 12 | ``` 13 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Serialization/IDynamicValueSerializer.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.Serialization; 2 | 3 | public interface IDynamicValueSerializer 4 | { 5 | T DeserializeJson(ReadOnlyMemory value); 6 | 7 | T DeserializeMsgPack(ReadOnlyMemory value); 8 | 9 | byte[] SerializeMsgPack(T value); 10 | } 11 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using MessagePack; 3 | 4 | namespace SampleProvider; 5 | 6 | [MessagePackObject] 7 | public class Configuration 8 | { 9 | [Key("file_header")] 10 | [Description("Header text to prepend to every file.")] 11 | public string? FileHeader { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using MessagePack; 3 | 4 | namespace DataSourceProvider; 5 | 6 | [MessagePackObject] 7 | public class Configuration 8 | { 9 | [Key("dummy_data")] 10 | [Description("Dummy data returned by the data source provider.")] 11 | public string? Data { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Schemas/ISchemaBuilder.cs: -------------------------------------------------------------------------------- 1 | using Tfplugin5; 2 | 3 | namespace TerraformPluginDotNet.Schemas; 4 | 5 | public interface ISchemaBuilder 6 | { 7 | /// 8 | /// Builds a Terraform schema for the specified CLR type. 9 | /// 10 | /// The type to build a schema for. 11 | Schema BuildSchema(Type type); 12 | } 13 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/TerraformResourceProviderException.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | #nullable enable 4 | 5 | public class TerraformResourceProviderException : Exception 6 | { 7 | public TerraformResourceProviderException(string message, Exception? innerException = default) 8 | : base(message, innerException) 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /version.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", 3 | "version": "0.1-alpha", 4 | "publicReleaseRefSpec": [ 5 | "^refs/heads/master$", 6 | "^refs/heads/v\\d+(?:\\.\\d+)?$" 7 | ], 8 | "nugetPackageVersion": { 9 | "semVer": 2 10 | }, 11 | "cloudBuild": { 12 | "buildNumber": { 13 | "enabled": true 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/IResourceProvider.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | public interface IResourceProvider 4 | { 5 | Task PlanAsync(T? prior, T proposed); 6 | 7 | Task CreateAsync(T planned); 8 | 9 | Task ReadAsync(T resource); 10 | 11 | Task UpdateAsync(T? prior, T planned); 12 | 13 | Task DeleteAsync(T resource); 14 | 15 | Task> ImportAsync(string id); 16 | } 17 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider/SampleConfigurator.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using TerraformPluginDotNet.ProviderConfig; 3 | 4 | namespace SampleProvider; 5 | 6 | public class SampleConfigurator : IProviderConfigurator 7 | { 8 | public Configuration? Config { get; private set; } 9 | 10 | public Task ConfigureAsync(Configuration config) 11 | { 12 | Config = config; 13 | return Task.CompletedTask; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider/SampleConfigurator.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using TerraformPluginDotNet.ProviderConfig; 3 | 4 | namespace DataSourceProvider; 5 | 6 | public class SampleConfigurator : IProviderConfigurator 7 | { 8 | public Configuration? Config { get; private set; } 9 | 10 | public Task ConfigureAsync(Configuration config) 11 | { 12 | Config = config; 13 | return Task.CompletedTask; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade/PreviousVersions/UpgradableResourceV1.cs: -------------------------------------------------------------------------------- 1 | using TerraformPluginDotNet.Resources; 2 | 3 | namespace SchemaUpgrade.PreviousVersions; 4 | 5 | /// 6 | /// An example resource type that can be upgraded. This is V1. 7 | /// 8 | [SchemaVersion(1)] 9 | internal class UpgradableResourceV1 10 | { 11 | public string Id { get; set; } = null!; 12 | 13 | // Renamed to `Data` in V2. 14 | public string Value { get; set; } = null!; 15 | } 16 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Resources/SchemaVersionAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.Resources; 2 | 3 | /// 4 | /// Indicates the version of a Terraform schema to allow version upgrades. 5 | /// 6 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 7 | public class SchemaVersionAttribute : Attribute 8 | { 9 | public SchemaVersionAttribute(long schemaVersion) 10 | { 11 | SchemaVersion = schemaVersion; 12 | } 13 | 14 | public long SchemaVersion { get; } 15 | } 16 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/EndpointRouteBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Routing; 3 | using TerraformPluginDotNet.Services; 4 | 5 | namespace TerraformPluginDotNet; 6 | 7 | public static class EndpointRouteBuilderExtensions 8 | { 9 | public static IEndpointRouteBuilder MapTerraformPlugin(this IEndpointRouteBuilder endpointRouteBuilder) 10 | { 11 | endpointRouteBuilder.MapGrpcService(); 12 | return endpointRouteBuilder; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade/SchemaUpgrade.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net7.0 5 | true 6 | win-x64;linux-x64 7 | false 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/TerraformPluginHostOptions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace TerraformPluginDotNet; 4 | 5 | public class TerraformPluginHostOptions 6 | { 7 | /// 8 | /// The full provider name. For example, `example.com/example/dotnetsample`. 9 | /// 10 | [Required] 11 | public string FullProviderName { get; set; } = null!; 12 | 13 | /// 14 | /// Configures debug mode which listens on H2C instead of TLS. 15 | /// 16 | public bool DebugMode { get; set; } 17 | } 18 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | $(MSBuildThisFileDirectory)StyleCopRules.ruleset 4 | True 5 | true 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /samples/SampleProvider/README.md: -------------------------------------------------------------------------------- 1 | SampleProvider 2 | ============== 3 | 4 | Basic example of a custom resource provider. 5 | 6 | This provider defines a new resource type that creates a file at a specified 7 | path containing the specified text content. 8 | 9 | ```hcl 10 | resource "dotnetsample_file" "demo_file" { 11 | path = "/tmp/file.txt" 12 | content = "this is a test" 13 | } 14 | ``` 15 | 16 | The provider can optionally be configured to prepend a fixed header to every 17 | file. 18 | 19 | ```hcl 20 | provider "dotnetsample" { 21 | file_header = "# File Header" 22 | } 23 | ``` 24 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | dotnet_naming_rule.private_members_with_underscore.symbols = private_fields 3 | dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore 4 | dotnet_naming_rule.private_members_with_underscore.severity = suggestion 5 | 6 | dotnet_naming_symbols.private_fields.applicable_kinds = field 7 | dotnet_naming_symbols.private_fields.applicable_accessibilities = private 8 | 9 | dotnet_naming_style.prefix_underscore.capitalization = camel_case 10 | dotnet_naming_style.prefix_underscore.required_prefix = _ 11 | 12 | csharp_style_namespace_declarations = file_scoped:warning 13 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider/SampleDataSource.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using MessagePack; 3 | using TerraformPluginDotNet.Resources; 4 | using TerraformPluginDotNet.Serialization; 5 | 6 | namespace DataSourceProvider; 7 | 8 | [SchemaVersion(1)] 9 | [MessagePackObject] 10 | public class SampleDataSource 11 | { 12 | [Key("id")] 13 | [Description("Id")] 14 | [Required] 15 | [MessagePackFormatter(typeof(ComputedStringValueFormatter))] 16 | public string? Id { get; set; } 17 | 18 | [Key("data")] 19 | [Description("Dummy data.")] 20 | [MessagePackFormatter(typeof(ComputedStringValueFormatter))] 21 | public string? Data { get; set; } 22 | } 23 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider.Test/SampleProvider.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net7.0 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade.Test/terraform.tfstate: -------------------------------------------------------------------------------- 1 | { 2 | "version": 4, 3 | "terraform_version": "1.2.6", 4 | "serial": 1, 5 | "lineage": "7c851e05-d31f-41a1-a9d9-f5e49477864f", 6 | "outputs": {}, 7 | "resources": [ 8 | { 9 | "mode": "managed", 10 | "type": "schemaupgrade_sampleresource", 11 | "name": "item1", 12 | "provider": "provider[\"example.com/example/schemaupgrade\"]", 13 | "instances": [ 14 | { 15 | "schema_version": 1, 16 | "attributes": { 17 | "value": "some value", 18 | "id": "3177850b-424f-462e-aaa2-6ce4d55fd186" 19 | }, 20 | "sensitive_attributes": [] 21 | } 22 | ] 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/TerraformPluginDotNet.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider.Test/DataSourceProvider.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net7.0 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/ITerraformTestInstance.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace TerraformPluginDotNet.Testing; 5 | 6 | public interface ITerraformTestInstance : IDisposable 7 | { 8 | TimeSpan DefaultCommandTimeout { get; } 9 | 10 | public string WorkDir { get; } 11 | 12 | /// 13 | /// Runs a Terraform command and returns its output. Fails if the Terraform process does not exit with code 0 within the specified timeout. 14 | /// 15 | /// The command to run. 16 | /// Defines how long to wait for Terraform to exit. Defaults to 1 second if not specified. 17 | Task RunCommandAsync(string command, TimeSpan? timeout = default); 18 | } 19 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider/SampleDataSourceProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using TerraformPluginDotNet.ResourceProvider; 3 | 4 | namespace DataSourceProvider; 5 | 6 | public class SampleDataSourceProvider : IDataSourceProvider 7 | { 8 | private readonly SampleConfigurator _configurator; 9 | 10 | public SampleDataSourceProvider(SampleConfigurator configurator) 11 | { 12 | _configurator = configurator; 13 | } 14 | 15 | public Task ReadAsync(SampleDataSource request) 16 | { 17 | return Task.FromResult(new SampleDataSource 18 | { 19 | Id = request.Id, 20 | Data = _configurator.Config?.Data ?? "No dummy data configured", 21 | }); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade/UpgradableResourceV2.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using MessagePack; 3 | using TerraformPluginDotNet.Resources; 4 | using TerraformPluginDotNet.Serialization; 5 | 6 | namespace SchemaUpgrade; 7 | 8 | /// 9 | /// An example resource type that can be upgraded. This is V2. 10 | /// 11 | [SchemaVersion(2)] 12 | [MessagePackObject] 13 | public class UpgradableResourceV2 14 | { 15 | [Key("id")] 16 | [Computed] 17 | [Description("Unique ID for this resource.")] 18 | [MessagePackFormatter(typeof(ComputedStringValueFormatter))] 19 | public string? Id { get; set; } 20 | 21 | // Renamed from `Value` in V1. 22 | [Key("data")] 23 | [Description("Some data.")] 24 | [Required] 25 | public string Data { get; set; } = null!; 26 | } 27 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/IResourceUpgrader.cs: -------------------------------------------------------------------------------- 1 | namespace TerraformPluginDotNet.ResourceProvider; 2 | 3 | /// 4 | /// Upgrades resource state from previous schema versions to the latest version. 5 | /// 6 | /// The type representing the latest schema of the resource. 7 | public interface IResourceUpgrader 8 | { 9 | /// 10 | /// Upgrades a resources state from an older schema to the latest schema. 11 | /// 12 | /// Schema version to upgrade from. 13 | /// Raw data to be upgraded. 14 | /// The resource state represented in the latest schema. 15 | Task UpgradeResourceStateAsync(long schemaVersion, ReadOnlyMemory json); 16 | } 17 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider/SampleFileResource.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using MessagePack; 3 | using TerraformPluginDotNet.Resources; 4 | using TerraformPluginDotNet.Serialization; 5 | 6 | namespace SampleProvider; 7 | 8 | [SchemaVersion(1)] 9 | [MessagePackObject] 10 | public class SampleFileResource 11 | { 12 | [Key("id")] 13 | [Computed] 14 | [Description("Unique ID for this resource.")] 15 | [MessagePackFormatter(typeof(ComputedStringValueFormatter))] 16 | public string? Id { get; set; } 17 | 18 | [Key("path")] 19 | [Description("Path to the file.")] 20 | [Required] 21 | public string Path { get; set; } = null!; 22 | 23 | [Key("content")] 24 | [Description("Contents of the file.")] 25 | [Required] 26 | public string Content { get; set; } = null!; 27 | } 28 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Serialization/DefaultDynamicValueSerializer.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using MessagePack; 3 | 4 | namespace TerraformPluginDotNet.Serialization; 5 | 6 | public class DefaultDynamicValueSerializer : IDynamicValueSerializer 7 | { 8 | public T DeserializeJson(ReadOnlyMemory value) 9 | { 10 | return JsonSerializer.Deserialize(value.Span, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) 11 | ?? throw new InvalidOperationException("Invalid Json provided"); 12 | } 13 | 14 | public T DeserializeMsgPack(ReadOnlyMemory value) 15 | { 16 | return MessagePackSerializer.Deserialize(value); 17 | } 18 | 19 | byte[] IDynamicValueSerializer.SerializeMsgPack(T value) 20 | { 21 | return MessagePackSerializer.Serialize(value); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade.Test/SchemaUpgrade.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net7.0 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/DefaultResourceUpgrader.cs: -------------------------------------------------------------------------------- 1 | using TerraformPluginDotNet.Serialization; 2 | 3 | namespace TerraformPluginDotNet.ResourceProvider; 4 | 5 | /// 6 | /// Default implementation of a resource upgrader that does nothing, and assumes 7 | /// previous versions can be deserialized from JSON into the latest schema version. 8 | /// 9 | class DefaultResourceUpgrader : IResourceUpgrader 10 | { 11 | private readonly IDynamicValueSerializer _serializer; 12 | 13 | public DefaultResourceUpgrader(IDynamicValueSerializer serializer) 14 | { 15 | _serializer = serializer; 16 | } 17 | 18 | public Task UpgradeResourceStateAsync(long schemaVersion, ReadOnlyMemory json) 19 | { 20 | return Task.FromResult(_serializer.DeserializeJson(json) ?? throw new InvalidOperationException("Invalid Json provided")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TerraformPluginDotNet; 4 | using TerraformPluginDotNet.ResourceProvider; 5 | 6 | namespace SampleProvider; 7 | 8 | class Program 9 | { 10 | static Task Main(string[] args) 11 | { 12 | // Use the default plugin host that takes care of certificates and hosting the Grpc services. 13 | 14 | return TerraformPluginHost.RunAsync(args, "example.com/example/sampleprovider", (services, registry) => 15 | { 16 | services.AddSingleton(); 17 | services.AddTerraformProviderConfigurator(); 18 | services.AddSingleton, SampleFileResourceProvider>(); 19 | registry.RegisterResource("sampleprovider_file"); 20 | }); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/TerraformPluginDotNet.Testing.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net7.0 4 | TerraformPluginDotNet.Testing 5 | https://github.com/SamuelFisher/TerraformPluginDotNet 6 | https://github.com/SamuelFisher/TerraformPluginDotNet 7 | Support for writing functional tests for Terraform providers. 8 | MIT 9 | SamuelFisher 10 | 11 | 12 | 13 | 14 | 3.6.133 15 | all 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TerraformPluginDotNet; 4 | using TerraformPluginDotNet.ResourceProvider; 5 | 6 | namespace DataSourceProvider; 7 | 8 | class Program 9 | { 10 | static Task Main(string[] args) 11 | { 12 | // Use the default plugin host that takes care of certificates and hosting the Grpc services. 13 | 14 | return TerraformPluginHost.RunAsync(args, "example.com/example/datasourceprovider", (services, registry) => 15 | { 16 | services.AddSingleton(); 17 | services.AddTerraformProviderConfigurator(); 18 | services.AddSingleton, SampleDataSourceProvider>(); 19 | registry.RegisterDataSource("datasourceprovider_data"); 20 | }); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TerraformPluginDotNet; 4 | using TerraformPluginDotNet.ResourceProvider; 5 | 6 | namespace SchemaUpgrade; 7 | 8 | class Program 9 | { 10 | static Task Main(string[] args) 11 | { 12 | // Use the default plugin host that takes care of certificates and hosting the Grpc services. 13 | 14 | return TerraformPluginHost.RunAsync(args, "example.com/example/schemaupgrade", (services, registry) => 15 | { 16 | // Register the resource and provider in the usual way. 17 | services.AddSingleton, UpgradableResourceProvider>(); 18 | registry.RegisterResource("schemaupgrade_sampleresource"); 19 | 20 | // Register the resource upgrader 21 | services.AddTransient, UpgradableResourceUpgrader>(); 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Samuel Fisher 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Serialization/ComputedStringValueFormatter.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using MessagePack; 3 | using MessagePack.Formatters; 4 | 5 | namespace TerraformPluginDotNet.Serialization; 6 | 7 | public class ComputedStringValueFormatter : IMessagePackFormatter 8 | { 9 | public string? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) 10 | { 11 | if (reader.TryReadNil()) 12 | { 13 | return null; 14 | } 15 | else if (reader.NextMessagePackType == MessagePackType.Extension && reader.TryReadExtensionFormatHeader(out var extHeader) && extHeader.TypeCode == 0) 16 | { 17 | reader.Skip(); 18 | return null; 19 | } 20 | 21 | return reader.ReadString(); 22 | } 23 | 24 | public void Serialize(ref MessagePackWriter writer, string? value, MessagePackSerializerOptions options) 25 | { 26 | if (value == null) 27 | { 28 | writer.WriteExtensionFormat(new ExtensionResult(0, new byte[1])); 29 | return; 30 | } 31 | 32 | writer.WriteString(Encoding.UTF8.GetBytes(value)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/Functional/TestResourceProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using TerraformPluginDotNet.ResourceProvider; 5 | 6 | namespace TerraformPluginDotNet.Test.Functional; 7 | 8 | class TestResourceProvider : IResourceProvider 9 | { 10 | public Task PlanAsync(TestResource prior, TestResource proposed) 11 | { 12 | return Task.FromResult(proposed); 13 | } 14 | 15 | public Task CreateAsync(TestResource planned) 16 | { 17 | planned.Id = Guid.NewGuid().ToString(); 18 | return Task.FromResult(planned); 19 | } 20 | 21 | public Task DeleteAsync(TestResource resource) 22 | { 23 | return Task.CompletedTask; 24 | } 25 | 26 | public Task ReadAsync(TestResource resource) 27 | { 28 | return Task.FromResult(resource); 29 | } 30 | 31 | public Task UpdateAsync(TestResource prior, TestResource planned) 32 | { 33 | return Task.FromResult(planned); 34 | } 35 | 36 | public Task> ImportAsync(string id) 37 | { 38 | throw new NotSupportedException(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider/SampleProvider.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net7.0 5 | true 6 | win-x64;linux-x64 7 | false 8 | terraform-provider-$([System.String]::Copy($(MSBuildProjectName)).ToLowerInvariant()) 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | unknown 17 | windows_amd64 18 | linux_amd64 19 | 20 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider/DataSourceProvider.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net7.0 5 | true 6 | win-x64;linux-x64 7 | false 8 | terraform-provider-$([System.String]::Copy($(MSBuildProjectName)).ToLowerInvariant()) 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | unknown 17 | windows_amd64 18 | linux_amd64 19 | 20 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/ServiceCollectionResourceRegistryContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace TerraformPluginDotNet.ResourceProvider; 4 | 5 | class ServiceCollectionResourceRegistryContext : IResourceRegistryContext 6 | { 7 | private readonly IServiceCollection _services; 8 | 9 | public ServiceCollectionResourceRegistryContext(IServiceCollection services) 10 | { 11 | _services = services; 12 | } 13 | 14 | public void RegisterResource(string resourceName) 15 | { 16 | EnsureValidType(); 17 | 18 | _services.AddSingleton(new ResourceRegistryRegistration(resourceName, typeof(T))); 19 | } 20 | 21 | public void RegisterDataSource(string resourceName) 22 | { 23 | EnsureValidType(); 24 | 25 | _services.AddSingleton(new DataSourceRegistryRegistration(resourceName, typeof(T))); 26 | } 27 | 28 | private static void EnsureValidType() 29 | { 30 | // Validation 31 | if (!typeof(T).IsPublic) 32 | { 33 | // Must be public to allow messagepack serialization. 34 | throw new InvalidOperationException($"Type {typeof(T).FullName} must be public in order to be used as a Terraform resource."); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ProviderConfig/ProviderConfigurationHost.cs: -------------------------------------------------------------------------------- 1 | using TerraformPluginDotNet.Serialization; 2 | using Tfplugin5; 3 | 4 | namespace TerraformPluginDotNet.ProviderConfig; 5 | 6 | class ProviderConfigurationHost 7 | { 8 | private readonly IProviderConfigurator _providerConfigurator; 9 | private readonly IDynamicValueSerializer _serializer; 10 | 11 | public ProviderConfigurationHost( 12 | IProviderConfigurator providerConfigurator, 13 | IDynamicValueSerializer serializer) 14 | { 15 | _providerConfigurator = providerConfigurator; 16 | _serializer = serializer; 17 | } 18 | 19 | public Task ConfigureAsync(Configure.Types.Request request) 20 | { 21 | var config = DeserializeDynamicValue(request.Config); 22 | return _providerConfigurator.ConfigureAsync(config); 23 | } 24 | 25 | private T DeserializeDynamicValue(DynamicValue value) 26 | { 27 | if (!value.Msgpack.IsEmpty) 28 | { 29 | return _serializer.DeserializeMsgPack(value.Msgpack.Memory); 30 | } 31 | 32 | if (!value.Json.IsEmpty) 33 | { 34 | return _serializer.DeserializeJson(value.Json.Memory); 35 | } 36 | 37 | throw new ArgumentException("Either MessagePack or Json must be non-empty.", nameof(value)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/ResourceRegistry.cs: -------------------------------------------------------------------------------- 1 | using TerraformPluginDotNet.Schemas; 2 | using Tfplugin5; 3 | 4 | namespace TerraformPluginDotNet.ResourceProvider; 5 | 6 | class ResourceRegistry 7 | { 8 | public ResourceRegistry( 9 | ISchemaBuilder schemaBulder, 10 | IEnumerable resourceRegistrations, 11 | IEnumerable dataSourceRegistrations) 12 | { 13 | foreach (var registration in resourceRegistrations) 14 | { 15 | Schemas.Add(registration.ResourceName, schemaBulder.BuildSchema(registration.Type)); 16 | Types.Add(registration.ResourceName, registration.Type); 17 | } 18 | foreach (var registration in dataSourceRegistrations) 19 | { 20 | DataSchemas.Add(registration.ResourceName, schemaBulder.BuildSchema(registration.Type)); 21 | DataTypes.Add(registration.ResourceName, registration.Type); 22 | } 23 | } 24 | 25 | public Dictionary Schemas { get; } = new Dictionary(); 26 | 27 | public Dictionary DataSchemas { get; } = new Dictionary(); 28 | 29 | public Dictionary Types { get; } = new Dictionary(); 30 | 31 | public Dictionary DataTypes { get; } = new Dictionary(); 32 | } 33 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/TerraformCommandException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | namespace TerraformPluginDotNet.Testing; 5 | 6 | public class TerraformCommandException : Exception 7 | { 8 | internal TerraformCommandException(string command, int exitCode, string output) 9 | { 10 | Command = command; 11 | ExitCode = exitCode; 12 | Output = output; 13 | Message = $"Terraform exited with code {ExitCode}.{Environment.NewLine}{Environment.NewLine}{output}"; 14 | } 15 | 16 | internal TerraformCommandException(string command, TimeSpan? timedOutAfter, string output) 17 | { 18 | Command = command; 19 | TimedOutAfter = timedOutAfter; 20 | Output = output; 21 | Message = $"Terraform timed out after {TimedOutAfter.Value.TotalSeconds:N2}s.{Environment.NewLine}{Environment.NewLine}{output}"; 22 | } 23 | 24 | public override string Message { get; } 25 | 26 | public string Command { get; } 27 | 28 | public int ExitCode { get; } 29 | 30 | public TimeSpan? TimedOutAfter { get; } 31 | 32 | public string Output { get; } 33 | 34 | public override string ToString() 35 | { 36 | var sb = new StringBuilder(); 37 | sb.AppendLine(Message); 38 | sb.AppendLine(); 39 | sb.AppendLine($"$ terraform {Command}"); 40 | sb.Append(Output); 41 | return sb.ToString(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace TerraformPluginDotNet; 9 | 10 | class Startup 11 | { 12 | public void ConfigureServices(IServiceCollection services) 13 | { 14 | services.AddGrpc(); 15 | services.AddTerraformPluginCore(); 16 | } 17 | 18 | public void Configure( 19 | IApplicationBuilder app, 20 | IHostApplicationLifetime lifetime, 21 | IWebHostEnvironment env, 22 | IOptions pluginHostOptions) 23 | { 24 | lifetime.InitializeTerraformPlugin(app, pluginHostOptions); 25 | 26 | if (env.IsDevelopment()) 27 | { 28 | app.UseDeveloperExceptionPage(); 29 | } 30 | 31 | app.UseRouting(); 32 | 33 | app.UseEndpoints(endpoints => 34 | { 35 | endpoints.MapTerraformPlugin(); 36 | 37 | endpoints.MapGet("/", async context => 38 | { 39 | await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); 40 | }); 41 | }); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade/UpgradableResourceProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using TerraformPluginDotNet.ResourceProvider; 5 | 6 | namespace SchemaUpgrade; 7 | 8 | public class UpgradableResourceProvider : IResourceProvider 9 | { 10 | public Task PlanAsync(UpgradableResourceV2? prior, UpgradableResourceV2 proposed) 11 | { 12 | return Task.FromResult(proposed); 13 | } 14 | 15 | public Task CreateAsync(UpgradableResourceV2 planned) 16 | { 17 | planned.Id = Guid.NewGuid().ToString(); 18 | 19 | // Do nothing 20 | return Task.FromResult(planned); 21 | } 22 | 23 | public Task DeleteAsync(UpgradableResourceV2 resource) 24 | { 25 | // Do nothing 26 | return Task.CompletedTask; 27 | } 28 | 29 | public Task ReadAsync(UpgradableResourceV2 resource) 30 | { 31 | // Do nothing 32 | return Task.FromResult(resource); 33 | } 34 | 35 | public Task UpdateAsync(UpgradableResourceV2? prior, UpgradableResourceV2 planned) 36 | { 37 | // Do nothing 38 | return Task.FromResult(planned); 39 | } 40 | 41 | public Task> ImportAsync(string id) 42 | { 43 | throw new NotSupportedException(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/serilog.json: -------------------------------------------------------------------------------- 1 | { 2 | "Serilog": { 3 | "Using": [ "Serilog.Expressions", "Serilog.Sinks.File" ], 4 | "Enrich": [ "FromLogContext" ], 5 | "WriteTo": [ 6 | { 7 | "Name": "File", 8 | "Args": { "path": "log.txt" } 9 | } 10 | ], 11 | "MinimumLevel": { 12 | "Default": "Information", 13 | "Override": { 14 | "Grpc": "Warning", 15 | "Microsoft": "Information", 16 | "Microsoft.AspNetCore.Routing.EndpointMiddleware": "Error", 17 | "Microsoft.AspNetCore.Server.Kestrel": "Error" 18 | } 19 | }, 20 | "Filter": [ 21 | { 22 | "Name": "ByExcluding", 23 | "Args": { 24 | "expression": "RequestPath like '%plugin.%'" 25 | } 26 | }, 27 | { 28 | "Name": "ByExcluding", 29 | "Args": { 30 | "expression": "RequestPath like '%tfplugin5.Provider/GetSchema'" 31 | } 32 | }, 33 | { 34 | "Name": "ByExcluding", 35 | "Args": { 36 | "expression": "RequestPath like '%tfplugin5.Provider/ValidateResourceTypeConfig'" 37 | } 38 | }, 39 | { 40 | "Name": "ByExcluding", 41 | "Args": { 42 | "expression": "RequestPath like '%tfplugin5.Provider/Configure'" 43 | } 44 | }, 45 | { 46 | "Name": "ByExcluding", 47 | "Args": { 48 | "expression": "RequestPath like '%tfplugin5.Provider/PrepareProviderConfig'" 49 | } 50 | } 51 | ] 52 | } 53 | } -------------------------------------------------------------------------------- /StyleCopRules.ruleset: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade/UpgradableResourceUpgrader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using SchemaUpgrade.PreviousVersions; 4 | using TerraformPluginDotNet.ResourceProvider; 5 | using TerraformPluginDotNet.Serialization; 6 | 7 | namespace SchemaUpgrade; 8 | 9 | /// 10 | /// Updates to . 11 | /// 12 | public class UpgradableResourceUpgrader : IResourceUpgrader 13 | { 14 | private readonly IDynamicValueSerializer _serializer; 15 | 16 | public UpgradableResourceUpgrader(IDynamicValueSerializer serializer) 17 | { 18 | _serializer = serializer; 19 | } 20 | 21 | public Task UpgradeResourceStateAsync(long schemaVersion, ReadOnlyMemory json) 22 | { 23 | switch (schemaVersion) 24 | { 25 | case 1: 26 | // Upgrade from V1 to V2. 27 | var v1 = _serializer.DeserializeJson(json); 28 | var v2 = new UpgradableResourceV2 29 | { 30 | Id = v1.Id, 31 | Data = v1.Value, 32 | }; 33 | return Task.FromResult(v2); 34 | case 2: 35 | // Already the latest version. 36 | return Task.FromResult(_serializer.DeserializeJson(json)); 37 | default: 38 | throw new NotSupportedException(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/TerraformTestInstanceExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text.Json; 3 | using System.Threading.Tasks; 4 | using TerraformPluginDotNet.Testing.Json; 5 | 6 | namespace TerraformPluginDotNet.Testing; 7 | 8 | public static class TerraformTestInstanceExtensions 9 | { 10 | public static Task InitAsync(this ITerraformTestInstance terraform) 11 | { 12 | return terraform.RunCommandAsync("init -no-color"); 13 | } 14 | 15 | public static Task PlanAsync(this ITerraformTestInstance terraform) 16 | { 17 | return terraform.RunCommandAsync("plan -no-color"); 18 | } 19 | 20 | public static async Task PlanWithOutputAsync(this ITerraformTestInstance terraform) 21 | { 22 | var tmp = Path.GetTempFileName(); 23 | 24 | try 25 | { 26 | await terraform.RunCommandAsync($"plan -no-color -out=\"{tmp}\""); 27 | var jsonPlan = await terraform.RunCommandAsync($"show -json \"{tmp}\""); 28 | return JsonSerializer.Deserialize(jsonPlan); 29 | } 30 | finally 31 | { 32 | File.Delete(tmp); 33 | } 34 | } 35 | 36 | public static Task ApplyAsync(this ITerraformTestInstance terraform) 37 | { 38 | return terraform.RunCommandAsync("apply -no-color -input=false -auto-approve=true"); 39 | } 40 | 41 | public static Task ImportAsync(this ITerraformTestInstance terraform, string address, string id) 42 | { 43 | return terraform.RunCommandAsync($"import -no-color {address} {id}"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/TerraformPluginDotNet.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net7.0 4 | TerraformPluginDotNet 5 | https://github.com/SamuelFisher/TerraformPluginDotNet 6 | https://github.com/SamuelFisher/TerraformPluginDotNet 7 | Write Terraform providers in C#. 8 | MIT 9 | SamuelFisher 10 | true 11 | enable 12 | enable 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 3.6.133 25 | all 26 | 27 | 28 | 29 | 30 | Always 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/DataSourceProviderHost.cs: -------------------------------------------------------------------------------- 1 | using TerraformPluginDotNet.Serialization; 2 | using Tfplugin5; 3 | 4 | namespace TerraformPluginDotNet.ResourceProvider; 5 | 6 | class DataSourceProviderHost 7 | { 8 | private readonly IDataSourceProvider _dataSourceProvider; 9 | private readonly IDynamicValueSerializer _serializer; 10 | 11 | public DataSourceProviderHost( 12 | IDataSourceProvider dataSourceProvider, 13 | IDynamicValueSerializer serializer) 14 | { 15 | _dataSourceProvider = dataSourceProvider; 16 | _serializer = serializer; 17 | } 18 | 19 | public async Task ReadDataSource(ReadDataSource.Types.Request request) 20 | { 21 | var current = DeserializeDynamicValue(request.Config); 22 | 23 | var read = await _dataSourceProvider.ReadAsync(current); 24 | var readSerialized = SerializeDynamicValue(read); 25 | 26 | return new ReadDataSource.Types.Response 27 | { 28 | State = readSerialized, 29 | }; 30 | } 31 | 32 | private T DeserializeDynamicValue(DynamicValue value) 33 | { 34 | if (!value.Msgpack.IsEmpty) 35 | { 36 | return _serializer.DeserializeMsgPack(value.Msgpack.Memory); 37 | } 38 | 39 | if (!value.Json.IsEmpty) 40 | { 41 | return _serializer.DeserializeJson(value.Json.Memory); 42 | } 43 | 44 | throw new ArgumentException("Either MessagePack or Json must be non-empty.", nameof(value)); 45 | } 46 | 47 | private DynamicValue SerializeDynamicValue(T value) 48 | { 49 | return new DynamicValue { Msgpack = Google.Protobuf.ByteString.CopyFrom(_serializer.SerializeMsgPack(value)) }; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/ResourceProvider/ResourceRegistryTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging.Abstractions; 2 | using NUnit.Framework; 3 | using TerraformPluginDotNet.ResourceProvider; 4 | using TerraformPluginDotNet.Schemas; 5 | using TerraformPluginDotNet.Schemas.Types; 6 | using Tfplugin5; 7 | 8 | namespace TerraformPluginDotNet.Test.ResourceProvider; 9 | 10 | [TestFixture] 11 | public class ResourceRegistryTest 12 | { 13 | [Test] 14 | public void TestRegisterResource() 15 | { 16 | var registry = BuildRegistry(); 17 | 18 | Assert.That(registry.Schemas.Keys, Is.EquivalentTo(new[] { "test_resource" })); 19 | Assert.That(registry.Schemas["test_resource"], Is.InstanceOf()); 20 | 21 | Assert.That(registry.Types.Keys, Is.EquivalentTo(new[] { "test_resource" })); 22 | Assert.That(registry.Types["test_resource"], Is.EqualTo(typeof(TestResource))); 23 | } 24 | 25 | [Test] 26 | public void TestRegisterDataSource() 27 | { 28 | var registry = BuildRegistry(); 29 | 30 | Assert.That(registry.DataSchemas.Keys, Is.EquivalentTo(new[] { "test_data_source" })); 31 | Assert.That(registry.DataSchemas["test_data_source"], Is.InstanceOf()); 32 | 33 | Assert.That(registry.DataTypes.Keys, Is.EquivalentTo(new[] { "test_data_source" })); 34 | Assert.That(registry.DataTypes["test_data_source"], Is.EqualTo(typeof(TestResource))); 35 | } 36 | 37 | private static ResourceRegistry BuildRegistry() 38 | { 39 | var registration = new ResourceRegistryRegistration("test_resource", typeof(TestResource)); 40 | var dataSourceRegistration = new DataSourceRegistryRegistration("test_data_source", typeof(TestResource)); 41 | var registry = new ResourceRegistry(new SchemaBuilder(NullLogger.Instance, new TerraformTypeBuilder()), new[] { registration }, new[] { dataSourceRegistration }); 42 | return registry; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/WebHostBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.AspNetCore.Server.Kestrel.Core; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Options; 5 | using TerraformPluginDotNet.ResourceProvider; 6 | 7 | namespace TerraformPluginDotNet; 8 | 9 | public static class WebHostBuilderExtensions 10 | { 11 | public const int DefaultPort = 5344; 12 | 13 | public static IWebHostBuilder ConfigureTerraformPlugin(this IWebHostBuilder webBuilder, Action configureRegistry, int port = DefaultPort) 14 | { 15 | webBuilder.ConfigureKestrel(kestrel => 16 | { 17 | var debugMode = kestrel.ApplicationServices.GetRequiredService>().Value.DebugMode; 18 | 19 | if (debugMode) 20 | { 21 | kestrel.ListenLocalhost(port, x => x.Protocols = HttpProtocols.Http2); 22 | } 23 | else 24 | { 25 | kestrel.ListenLocalhost(port, x => x.UseHttps(x => 26 | { 27 | var certificate = kestrel.ApplicationServices.GetService(); 28 | if (certificate == null) 29 | { 30 | throw new InvalidOperationException("Debug mode is not enabled, but no certificate was found."); 31 | } 32 | 33 | x.ServerCertificate = certificate.Certificate; 34 | x.AllowAnyClientCertificate(); 35 | })); 36 | } 37 | }); 38 | 39 | webBuilder.UseStartup(); 40 | 41 | webBuilder.ConfigureServices(services => 42 | { 43 | var registryContext = services.AddTerraformResourceRegistry(); 44 | configureRegistry(services, registryContext); 45 | }); 46 | 47 | return webBuilder; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/HostApplicationLifetimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting.Server.Features; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace TerraformPluginDotNet; 8 | 9 | public static class HostApplicationLifetimeExtensions 10 | { 11 | public static IHostApplicationLifetime InitializeTerraformPlugin(this IHostApplicationLifetime lifetime, IApplicationBuilder app, IOptions pluginHostOptions) 12 | { 13 | lifetime.ApplicationStarted.Register(() => 14 | { 15 | var serverAddress = app.ServerFeatures.Get()?.Addresses.First() ?? throw new InvalidOperationException($"{nameof(IServerAddressesFeature)} not found in {nameof(app.ServerFeatures)}"); 16 | var serverUri = new Uri(serverAddress); 17 | var host = serverUri.Host == "localhost" ? "127.0.0.1" : serverUri.Host; 18 | 19 | if (pluginHostOptions.Value.DebugMode) 20 | { 21 | Console.WriteLine("Debug mode enabled (no certificate). Run Terraform with the following environment variable set:"); 22 | Console.WriteLine($@"TF_REATTACH_PROVIDERS={{""{pluginHostOptions.Value.FullProviderName}"":{{""Protocol"":""grpc"",""Pid"":{Environment.ProcessId},""Test"":true,""Addr"":{{""Network"":""tcp"",""String"":""{host}:{serverUri.Port}""}}}}}}"); 23 | } 24 | else 25 | { 26 | var pluginHostCertificate = app.ApplicationServices.GetRequiredService(); 27 | 28 | // Terraform seems not to like Base64 padding, so we trim 29 | var base64EncodedCertificate = Convert.ToBase64String(pluginHostCertificate.Certificate.RawData).TrimEnd('='); 30 | Console.WriteLine($"1|5|tcp|{host}:{serverUri.Port}|grpc|{base64EncodedCertificate}"); 31 | } 32 | }); 33 | 34 | return lifetime; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request, workflow_dispatch] 3 | 4 | jobs: 5 | ci: 6 | runs-on: ${{ matrix.os }} 7 | strategy: 8 | matrix: 9 | os: [ubuntu-22.04, windows-2022] 10 | steps: 11 | - uses: actions/checkout@v3 12 | with: 13 | fetch-depth: 0 # Required for nbgv 14 | - uses: actions/setup-dotnet@v3 15 | with: 16 | dotnet-version: '7.0.x' 17 | - name: Restore 18 | run: dotnet restore 19 | - name: Build 20 | run: dotnet build --configuration Release --no-restore 21 | - name: Test 22 | run: dotnet test --no-restore 23 | - uses: hashicorp/setup-terraform@v2 24 | with: 25 | terraform_version: 1.2.6 26 | terraform_wrapper: false 27 | - name: Set TF_PLUGIN_DOTNET_TEST_TF_BIN (Ubuntu) 28 | if: startsWith(matrix.os, 'ubuntu') 29 | run: echo "TF_PLUGIN_DOTNET_TEST_TF_BIN=$(which terraform)" >> $GITHUB_ENV 30 | - name: Set TF_PLUGIN_DOTNET_TEST_TF_BIN (Windows) 31 | if: startsWith(matrix.os, 'windows') 32 | run: echo "TF_PLUGIN_DOTNET_TEST_TF_BIN=$(get-command terraform | select-object -ExpandProperty source)" >> $env:GITHUB_ENV 33 | - name: Functional tests 34 | run: dotnet test --no-restore --filter Category=Functional 35 | - name: E2E tests 36 | env: 37 | RUNTIME_IDENTIFIER: "${{ startsWith(matrix.os, 'windows') && 'win-x64' || 'linux-x64' }}" 38 | TF_CLI_CONFIG_FILE: "cli.tfrc" 39 | run: | 40 | dotnet publish samples/SampleProvider/SampleProvider/SampleProvider.csproj -r ${{ env.RUNTIME_IDENTIFIER }} --self-contained -c Release -p:PublishSingleFile=true 41 | cp samples/SampleProvider/SampleProvider/bin/Release/net7.0/*.zip e2e/providers/example.com/example/sampleprovider 42 | cd e2e 43 | terraform init 44 | terraform plan 45 | - name: Pack 46 | run: dotnet pack --no-restore --configuration Release -o packages 47 | - name: Upload packages as artefacts 48 | if: startsWith(matrix.os, 'windows') 49 | uses: actions/upload-artifact@v2 50 | with: 51 | name: packages 52 | path: packages/*.nupkg 53 | retention-days: 5 54 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/Schemas/Types/TerraformTypeTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using NUnit.Framework; 4 | using TerraformPluginDotNet.Schemas.Types; 5 | 6 | namespace TerraformPluginDotNet.Test.Schemas.Types; 7 | 8 | [TestFixture] 9 | public class TerraformTypeTest 10 | { 11 | [Test] 12 | public void TestTfObjectEqualityWhenEqual() 13 | { 14 | var obj1 = new TerraformType.TfObject( 15 | new Dictionary() 16 | { 17 | ["a"] = new TerraformType.TfNumber(), 18 | ["b"] = new TerraformType.TfNumber(), 19 | ["c"] = new TerraformType.TfNumber(), 20 | }.ToImmutableDictionary(), 21 | ImmutableHashSet.Create("a", "b")); 22 | 23 | var obj2 = new TerraformType.TfObject( 24 | new Dictionary() 25 | { 26 | ["c"] = new TerraformType.TfNumber(), 27 | ["b"] = new TerraformType.TfNumber(), 28 | ["a"] = new TerraformType.TfNumber(), 29 | }.ToImmutableDictionary(), 30 | ImmutableHashSet.Create("b", "a")); 31 | 32 | Assert.That(obj1.GetHashCode(), Is.EqualTo(obj2.GetHashCode())); 33 | Assert.That(obj1, Is.EqualTo(obj2)); 34 | } 35 | 36 | [Test] 37 | public void TestTfObjectEqualityWhenNotEqual() 38 | { 39 | var obj1 = new TerraformType.TfObject( 40 | new Dictionary() 41 | { 42 | ["a"] = new TerraformType.TfNumber(), 43 | ["b"] = new TerraformType.TfNumber(), 44 | ["c"] = new TerraformType.TfNumber(), 45 | }.ToImmutableDictionary(), 46 | ImmutableHashSet.Create("a", "b")); 47 | 48 | var obj2 = new TerraformType.TfObject( 49 | new Dictionary() 50 | { 51 | ["c"] = new TerraformType.TfNumber(), 52 | ["b"] = new TerraformType.TfNumber(), 53 | ["a"] = new TerraformType.TfNumber(), 54 | }.ToImmutableDictionary(), 55 | ImmutableHashSet.Create("a")); 56 | 57 | Assert.That(obj1, Is.Not.EqualTo(obj2)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using TerraformPluginDotNet.ProviderConfig; 3 | using TerraformPluginDotNet.ResourceProvider; 4 | using TerraformPluginDotNet.Schemas; 5 | using TerraformPluginDotNet.Schemas.Types; 6 | using TerraformPluginDotNet.Serialization; 7 | 8 | namespace TerraformPluginDotNet; 9 | 10 | /// 11 | /// Use the extensions in this class for more granular configuration of the Terraform plugin. 12 | /// For simpler setup, use . 13 | /// 14 | public static class ServiceCollectionExtensions 15 | { 16 | public static IServiceCollection AddTerraformPluginCore(this IServiceCollection services) 17 | { 18 | services.AddTransient(); 19 | services.AddTransient(); 20 | services.AddTransient(typeof(ProviderConfigurationHost<>)); 21 | services.AddTransient(typeof(ResourceProviderHost<>)); 22 | services.AddTransient(typeof(DataSourceProviderHost<>)); 23 | services.AddTransient(typeof(IResourceUpgrader<>), typeof(DefaultResourceUpgrader<>)); 24 | services.AddTransient(); 25 | return services; 26 | } 27 | 28 | public static IResourceRegistryContext AddTerraformResourceRegistry(this IServiceCollection services) 29 | { 30 | services.AddOptions().ValidateDataAnnotations(); 31 | services.AddSingleton(); 32 | 33 | var registryContext = new ServiceCollectionResourceRegistryContext(services); 34 | return registryContext; 35 | } 36 | 37 | /// 38 | /// Adds a configurator that will be called when configuring this terraform plugin. 39 | /// 40 | public static IServiceCollection AddTerraformProviderConfigurator(this IServiceCollection services) 41 | where TProviderConfigurator : IProviderConfigurator 42 | { 43 | services.AddSingleton(s => new ProviderConfigurationRegistry( 44 | ConfigurationSchema: s.GetRequiredService().BuildSchema(typeof(TConfig)), 45 | ConfigurationType: typeof(TConfig))); 46 | 47 | services.AddTransient>(s => s.GetRequiredService()); 48 | return services; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Schemas/SchemaBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | using Google.Protobuf; 4 | using Microsoft.Extensions.Logging; 5 | using TerraformPluginDotNet.Resources; 6 | using TerraformPluginDotNet.Schemas.Types; 7 | using Tfplugin5; 8 | using KeyAttribute = MessagePack.KeyAttribute; 9 | 10 | namespace TerraformPluginDotNet.Schemas; 11 | 12 | class SchemaBuilder : ISchemaBuilder 13 | { 14 | private readonly ILogger _logger; 15 | private readonly ITerraformTypeBuilder _typeBuilder; 16 | 17 | public SchemaBuilder(ILogger logger, ITerraformTypeBuilder typeBuilder) 18 | { 19 | _logger = logger; 20 | _typeBuilder = typeBuilder; 21 | } 22 | 23 | public Schema BuildSchema(Type type) 24 | { 25 | var schemaVersionAttribute = type.GetCustomAttribute(); 26 | if (schemaVersionAttribute == null) 27 | { 28 | _logger.LogWarning($"Missing {nameof(SchemaVersionAttribute)} when generating schema for {type.FullName}."); 29 | } 30 | 31 | var properties = type.GetProperties(); 32 | 33 | var block = new Schema.Types.Block(); 34 | foreach (var property in properties) 35 | { 36 | var key = property.GetCustomAttribute() ?? throw new InvalidOperationException($"Missing {nameof(KeyAttribute)} on {property.Name} in {type.Name}."); 37 | 38 | var description = property.GetCustomAttribute(); 39 | var required = TerraformTypeBuilder.IsRequiredAttribute(property); 40 | var computed = property.GetCustomAttribute() != null; 41 | var terraformType = _typeBuilder.GetTerraformType(property.PropertyType); 42 | 43 | if (terraformType is TerraformType.TfObject _ && !required) 44 | { 45 | throw new InvalidOperationException("Optional object types are not supported."); 46 | } 47 | 48 | block.Attributes.Add(new Schema.Types.Attribute 49 | { 50 | Name = key.StringKey, 51 | Type = ByteString.CopyFromUtf8(terraformType.ToJson()), 52 | Description = description?.Description, 53 | Optional = !required, 54 | Required = required, 55 | Computed = computed, 56 | }); 57 | } 58 | 59 | return new Schema 60 | { 61 | Version = schemaVersionAttribute?.SchemaVersion ?? 0, 62 | Block = block, 63 | }; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/TerraformTestInstance.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.IO; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace TerraformPluginDotNet.Testing; 9 | 10 | class TerraformTestInstance : ITerraformTestInstance 11 | { 12 | private readonly string _terraformBin; 13 | private readonly string _providerName; 14 | private readonly int _port; 15 | 16 | public TerraformTestInstance(string terraformBin, string providerName, int port, string workDir) 17 | { 18 | _terraformBin = terraformBin; 19 | _providerName = providerName; 20 | _port = port; 21 | WorkDir = workDir; 22 | } 23 | 24 | public string WorkDir { get; private set; } 25 | 26 | public TimeSpan DefaultCommandTimeout { get; set; } = TimeSpan.FromMinutes(1); 27 | 28 | public async Task RunCommandAsync(string command, TimeSpan? timeout = null) 29 | { 30 | timeout ??= DefaultCommandTimeout; 31 | 32 | var startInfo = new ProcessStartInfo(_terraformBin, command) 33 | { 34 | WorkingDirectory = WorkDir, 35 | RedirectStandardOutput = true, 36 | RedirectStandardError = true, 37 | }; 38 | 39 | startInfo.EnvironmentVariables.Add("TF_REATTACH_PROVIDERS", $@"{{""example.com/example/{_providerName}"":{{""Protocol"":""grpc"",""Pid"":{Environment.ProcessId},""Test"":true,""Addr"":{{""Network"":""tcp"",""String"":""127.0.0.1:{_port}""}}}}}}"); 40 | var p = Process.Start(startInfo); 41 | 42 | var output = new StringBuilder(); 43 | p.OutputDataReceived += (sender, e) => output.AppendLine(e.Data); 44 | p.ErrorDataReceived += (sender, e) => output.AppendLine(e.Data); 45 | p.BeginOutputReadLine(); 46 | p.BeginErrorReadLine(); 47 | 48 | var timeoutCts = new CancellationTokenSource(); 49 | timeoutCts.CancelAfter(timeout.Value); 50 | 51 | try 52 | { 53 | await p.WaitForExitAsync(timeoutCts.Token); 54 | } 55 | catch (TaskCanceledException) 56 | { 57 | p.Kill(); 58 | await p.WaitForExitAsync(); 59 | throw new TerraformCommandException(command, timeout, output.ToString()); 60 | } 61 | 62 | if (p.ExitCode != 0) 63 | { 64 | throw new TerraformCommandException(command, p.ExitCode, output.ToString()); 65 | } 66 | 67 | return output.ToString(); 68 | } 69 | 70 | public void Dispose() 71 | { 72 | Directory.Delete(WorkDir, true); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /samples/SchemaUpgrade/SchemaUpgrade.Test/UpgradableResourceProviderTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using NUnit.Framework; 8 | using TerraformPluginDotNet.ResourceProvider; 9 | using TerraformPluginDotNet.Testing; 10 | 11 | namespace SchemaUpgrade.Test; 12 | 13 | [TestFixture(Category = "Functional", Explicit = true)] 14 | public class UpgradableResourceProviderTest 15 | { 16 | private const string ProviderName = "schemaupgrade"; 17 | 18 | private TerraformTestHost _host; 19 | 20 | [OneTimeSetUp] 21 | public void Setup() 22 | { 23 | _host = new TerraformTestHost(Environment.GetEnvironmentVariable("TF_PLUGIN_DOTNET_TEST_TF_BIN")); 24 | _host.Start($"example.com/example/{ProviderName}", Configure); 25 | } 26 | 27 | [OneTimeTearDown] 28 | public async Task TearDown() 29 | { 30 | await _host.DisposeAsync(); 31 | } 32 | 33 | private void Configure(IServiceCollection services, IResourceRegistryContext registryContext) 34 | { 35 | services.AddSingleton, UpgradableResourceProvider>(); 36 | registryContext.RegisterResource($"{ProviderName}_sampleresource"); 37 | services.AddTransient, UpgradableResourceUpgrader>(); 38 | } 39 | 40 | [Test] 41 | public async Task TestUpdateOlderResourceVersion() 42 | { 43 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 44 | 45 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 46 | 47 | await File.WriteAllTextAsync(resourcePath, $@" 48 | resource ""{ProviderName}_sampleresource"" ""item1"" {{ 49 | data = ""some value"" 50 | }} 51 | "); 52 | 53 | var tfstate = Assembly.GetExecutingAssembly().GetManifestResourceStream("SchemaUpgrade.Test.terraform.tfstate"); 54 | using (var tfStateFile = File.Create(Path.Combine(terraform.WorkDir, "terraform.tfstate"))) 55 | { 56 | await tfstate.CopyToAsync(tfStateFile); 57 | } 58 | 59 | var plan = await terraform.PlanWithOutputAsync(); 60 | 61 | // State should be upgraded, but there are no changes to apply. 62 | var resourceChange = plan.ResourceChanges.Single().Change; 63 | Assert.That(resourceChange.Actions.Single(), Is.EqualTo("no-op")); 64 | Assert.That(resourceChange.After.GetProperty("data").GetString(), Is.EqualTo(resourceChange.Before.GetProperty("data").GetString())); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/Schemas/SchemaBuilderTest.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Microsoft.Extensions.Logging.Abstractions; 3 | using NUnit.Framework; 4 | using TerraformPluginDotNet.Schemas; 5 | using TerraformPluginDotNet.Schemas.Types; 6 | 7 | namespace TerraformPluginDotNet.Test.Schemas; 8 | 9 | [TestFixture] 10 | public class SchemaBuilderTest 11 | { 12 | private SchemaBuilder _schemaBuilder; 13 | 14 | [SetUp] 15 | public void Setup() 16 | { 17 | _schemaBuilder = new SchemaBuilder( 18 | NullLogger.Instance, 19 | new TerraformTypeBuilder()); 20 | } 21 | 22 | [Test] 23 | public void TestSchema() 24 | { 25 | var schema = _schemaBuilder.BuildSchema(typeof(TestResource)); 26 | 27 | Assert.That(schema.Block, Is.Not.Null); 28 | 29 | var attributes = schema.Block.Attributes; 30 | Assert.That(attributes, Has.Count.EqualTo(15)); 31 | 32 | var idAttr = attributes.Single(x => x.Name == "id"); 33 | Assert.That(idAttr.Type.ToStringUtf8(), Is.EqualTo("\"string\"")); 34 | Assert.That(idAttr.Description, Is.EqualTo("Unique ID for this resource.")); 35 | Assert.That(idAttr.Optional, Is.True); 36 | Assert.That(idAttr.Required, Is.False); 37 | Assert.That(idAttr.Computed, Is.True); 38 | 39 | var requiredStrAttr = attributes.Single(x => x.Name == "required_string"); 40 | Assert.That(requiredStrAttr.Type.ToStringUtf8(), Is.EqualTo("\"string\"")); 41 | Assert.That(requiredStrAttr.Description, Is.EqualTo("This is required.")); 42 | Assert.That(requiredStrAttr.Optional, Is.False); 43 | Assert.That(requiredStrAttr.Required, Is.True); 44 | Assert.That(requiredStrAttr.Computed, Is.False); 45 | 46 | var requiredIntAttr = attributes.Single(x => x.Name == "required_int"); 47 | Assert.That(requiredIntAttr.Type.ToStringUtf8(), Is.EqualTo("\"number\"")); 48 | Assert.That(requiredIntAttr.Description, Is.EqualTo("This is required.")); 49 | Assert.That(requiredIntAttr.Optional, Is.False); 50 | Assert.That(requiredIntAttr.Required, Is.True); 51 | Assert.That(requiredIntAttr.Computed, Is.False); 52 | 53 | var requiredObjectAttr = attributes.Single(x => x.Name == "object_1"); 54 | Assert.That( 55 | requiredObjectAttr.Type.ToStringUtf8(), 56 | Is.EqualTo("""["object",{"nested_int":"number","required_string":"string"},["nested_int"]]""")); 57 | Assert.That(requiredObjectAttr.Description, Is.EqualTo("An object.")); 58 | Assert.That(requiredObjectAttr.Optional, Is.False); 59 | Assert.That(requiredObjectAttr.Required, Is.True); 60 | Assert.That(requiredObjectAttr.Computed, Is.False); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider/SampleFileResourceProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using TerraformPluginDotNet.ResourceProvider; 7 | 8 | namespace SampleProvider; 9 | 10 | public class SampleFileResourceProvider : IResourceProvider 11 | { 12 | private readonly SampleConfigurator _configurator; 13 | 14 | public SampleFileResourceProvider(SampleConfigurator configurator) 15 | { 16 | _configurator = configurator; 17 | } 18 | 19 | public Task PlanAsync(SampleFileResource? prior, SampleFileResource proposed) 20 | { 21 | return Task.FromResult(proposed); 22 | } 23 | 24 | public async Task CreateAsync(SampleFileResource planned) 25 | { 26 | planned.Id = Guid.NewGuid().ToString(); 27 | await File.WriteAllTextAsync(planned.Path, BuildContent(planned.Content)); 28 | return planned; 29 | } 30 | 31 | public Task DeleteAsync(SampleFileResource resource) 32 | { 33 | File.Delete(resource.Path); 34 | return Task.CompletedTask; 35 | } 36 | 37 | public async Task ReadAsync(SampleFileResource resource) 38 | { 39 | var content = await File.ReadAllTextAsync(resource.Path); 40 | resource.Content = content; 41 | return resource; 42 | } 43 | 44 | public async Task UpdateAsync(SampleFileResource? prior, SampleFileResource planned) 45 | { 46 | await File.WriteAllTextAsync(planned.Path, BuildContent(planned.Content)); 47 | return planned; 48 | } 49 | 50 | public async Task> ImportAsync(string id) 51 | { 52 | // Id is not SampleFileResource.Id, it's the "import ID" supplied by Terraform 53 | // and in this provider, is defined to be the file name. 54 | 55 | if (!File.Exists(id)) 56 | { 57 | throw new TerraformResourceProviderException($"File '{id}' does not exist."); 58 | } 59 | 60 | var content = await File.ReadAllTextAsync(id); 61 | 62 | return new[] 63 | { 64 | new SampleFileResource 65 | { 66 | Id = Guid.NewGuid().ToString(), 67 | Path = id, 68 | Content = content, 69 | }, 70 | }; 71 | } 72 | 73 | private string BuildContent(string content) 74 | { 75 | if (_configurator.Config?.FileHeader is not string header) 76 | { 77 | return content; 78 | } 79 | 80 | var sb = new StringBuilder(); 81 | sb.AppendLine(header); 82 | sb.Append(content); 83 | return sb.ToString(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /samples/DataSourceProvider/DataSourceProvider.Test/SampleDataSourceProviderTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using NUnit.Framework; 6 | using TerraformPluginDotNet; 7 | using TerraformPluginDotNet.ResourceProvider; 8 | using TerraformPluginDotNet.Testing; 9 | 10 | namespace DataSourceProvider.Test; 11 | 12 | [TestFixture(Category = "Functional", Explicit = true)] 13 | public class SampleDataSourceProviderTest 14 | { 15 | private const string ProviderName = "datasourceprovider"; 16 | 17 | private TerraformTestHost _host; 18 | 19 | [OneTimeSetUp] 20 | public void Setup() 21 | { 22 | _host = new TerraformTestHost(Environment.GetEnvironmentVariable("TF_PLUGIN_DOTNET_TEST_TF_BIN")); 23 | _host.Start($"example.com/example/{ProviderName}", Configure); 24 | } 25 | 26 | [OneTimeTearDown] 27 | public async Task TearDown() 28 | { 29 | await _host.DisposeAsync(); 30 | } 31 | 32 | private void Configure(IServiceCollection services, IResourceRegistryContext registryContext) 33 | { 34 | services.AddSingleton(); 35 | services.AddTerraformProviderConfigurator(); 36 | services.AddSingleton, SampleDataSourceProvider>(); 37 | registryContext.RegisterDataSource($"{ProviderName}_data"); 38 | } 39 | 40 | [Test] 41 | public async Task TestReadDataSource() 42 | { 43 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 44 | 45 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 46 | 47 | await File.WriteAllTextAsync(resourcePath, $@" 48 | data ""{ProviderName}_data"" ""demo_data"" {{ 49 | id = ""test"" 50 | }} 51 | "); 52 | 53 | var output = await terraform.PlanWithOutputAsync(); 54 | 55 | Assert.That(output.PriorState.Values.RootModule.Resources[0].Values.GetProperty("data").GetString(), Is.EqualTo("No dummy data configured")); 56 | } 57 | 58 | [Test] 59 | public async Task TestConfigureDataSource() 60 | { 61 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName, configureProvider: false); 62 | 63 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 64 | 65 | await File.WriteAllTextAsync(resourcePath, $@" 66 | provider ""{ProviderName}"" {{ 67 | dummy_data = ""This is dummy data"" 68 | }} 69 | 70 | data ""{ProviderName}_data"" ""demo_data"" {{ 71 | id = ""test"" 72 | }} 73 | 74 | "); 75 | 76 | var output = await terraform.PlanWithOutputAsync(); 77 | 78 | Assert.That(output.PriorState.Values.RootModule.Resources[0].Values.GetProperty("data").GetString(), Is.EqualTo("This is dummy data")); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/TestResource.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using MessagePack; 5 | using TerraformPluginDotNet.Resources; 6 | using TerraformPluginDotNet.Serialization; 7 | 8 | namespace TerraformPluginDotNet.Test; 9 | 10 | [SchemaVersion(1)] 11 | [MessagePackObject] 12 | public class TestResource 13 | { 14 | [Key("id")] 15 | [Computed] 16 | [Description("Unique ID for this resource.")] 17 | [MessagePackFormatter(typeof(ComputedStringValueFormatter))] 18 | public string Id { get; set; } 19 | 20 | [Key("required_string")] 21 | [Description("This is required.")] 22 | [Required] 23 | public string RequiredString { get; set; } 24 | 25 | [Key("required_int")] 26 | [Description("This is required.")] 27 | public int RequiredInt { get; set; } 28 | 29 | [Key("int_attribute")] 30 | [Description("Int attribute.")] 31 | public int? IntAttribute { get; set; } 32 | 33 | [Key("boolean_attribute")] 34 | [Description("A boolean attribute.")] 35 | public bool? BooleanAttribute { get; set; } 36 | 37 | [Key("float_attribute")] 38 | [Description("A float attribute.")] 39 | public float? FloatAttribute { get; set; } 40 | 41 | [Key("double_attribute")] 42 | [Description("A double attribute.")] 43 | public float? DoubleAttribute { get; set; } 44 | 45 | [Key("string_set_attribute")] 46 | [Description("A string set attribute.")] 47 | public HashSet StringSetAttribute { get; set; } 48 | 49 | [Key("string_list_attribute")] 50 | [Description("A string list attribute.")] 51 | public List StringListAttribute { get; set; } 52 | 53 | [Key("int_list_attribute")] 54 | [Description("An int list attribute.")] 55 | public List IntListAttribute { get; set; } 56 | 57 | [Key("string_map_attribute")] 58 | [Description("A string map attribute.")] 59 | public Dictionary StringMapAttribute { get; set; } 60 | 61 | [Key("int_map_attribute")] 62 | [Description("An int map attribute.")] 63 | public Dictionary IntMapAttribute { get; set; } 64 | 65 | [Key("object_1")] 66 | [Description("An object.")] 67 | [Required] 68 | public TestObjectWithOptionalAttributes Object1 { get; set; } 69 | 70 | [Key("object_2")] 71 | [Description("An object.")] 72 | [Required] 73 | public TestObjectNoOptionalAttributes Object2 { get; set; } 74 | 75 | [Key("tuple_attribute")] 76 | [Description("A tuple attribute.")] 77 | public Tuple TupleAttribute { get; set; } 78 | } 79 | 80 | [MessagePackObject] 81 | public class TestObjectWithOptionalAttributes 82 | { 83 | [Key("required_string")] 84 | [Required] 85 | public string RequiredString { get; set; } 86 | 87 | [Key("nested_int")] 88 | public int? NestedInt { get; set; } 89 | } 90 | 91 | [MessagePackObject] 92 | public class TestObjectNoOptionalAttributes 93 | { 94 | [Key("required_string")] 95 | [Required] 96 | public string RequiredString { get; set; } 97 | } 98 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/TerraformPluginHost.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Options; 6 | using Serilog; 7 | using TerraformPluginDotNet.ResourceProvider; 8 | 9 | namespace TerraformPluginDotNet; 10 | 11 | /// 12 | /// Use this class to create a default host for a Terraform plugin. 13 | /// 14 | public static class TerraformPluginHost 15 | { 16 | public static async Task RunAsync(string[] args, string fullProviderName, Action configure, CancellationToken token = default) 17 | { 18 | var serilogConfiguration = new ConfigurationBuilder() 19 | .AddJsonFile("serilog.json", optional: true) 20 | .Build(); 21 | 22 | Log.Logger = new LoggerConfiguration() 23 | .ReadFrom.Configuration(serilogConfiguration) 24 | .CreateBootstrapLogger(); 25 | 26 | try 27 | { 28 | await CreateHostBuilder(args, fullProviderName, configure).Build().RunAsync(token); 29 | } 30 | catch (Exception ex) 31 | { 32 | Log.Logger.Fatal(ex, "Fatal error occurred."); 33 | } 34 | finally 35 | { 36 | Log.Logger.Information("Application terminated."); 37 | Log.CloseAndFlush(); 38 | } 39 | } 40 | 41 | public static IHostBuilder CreateHostBuilder( 42 | string[] args, 43 | string fullProviderName, 44 | Action configure) => 45 | Host.CreateDefaultBuilder(args) 46 | .ConfigureAppConfiguration(configuration => 47 | { 48 | configuration.AddJsonFile(Path.Combine(AppContext.BaseDirectory, "serilog.json"), optional: true); 49 | configuration.AddJsonFile("serilog.json", optional: true); 50 | }) 51 | .ConfigureServices((host, services) => 52 | { 53 | services.Configure(host.Configuration); 54 | services.Configure(x => x.FullProviderName = fullProviderName); 55 | services.AddSingleton(new PluginHostCertificate( 56 | Certificate: CertificateGenerator.GenerateSelfSignedCertificate("CN=127.0.0.1", "CN=root ca", CertificateGenerator.GeneratePrivateKey()))); 57 | }) 58 | .ConfigureWebHostDefaults(webBuilder => 59 | { 60 | webBuilder.ConfigureTerraformPlugin(configure); 61 | }) 62 | .UseSerilog((context, services, configuration) => 63 | { 64 | configuration 65 | .ReadFrom.Configuration(context.Configuration) 66 | .ReadFrom.Services(services) 67 | .Enrich.FromLogContext(); 68 | 69 | // Only write to console in debug mode because Terraform reads connection details from stdout. 70 | if (services.GetRequiredService>().Value.DebugMode) 71 | { 72 | configuration.WriteTo.Console(); 73 | } 74 | }); 75 | } 76 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/Schemas/Types/TerraformTypeBuilderTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using MessagePack; 4 | using NUnit.Framework; 5 | using TerraformPluginDotNet.Resources; 6 | using TerraformPluginDotNet.Schemas.Types; 7 | 8 | namespace TerraformPluginDotNet.Test.Schemas.Types; 9 | 10 | [TestFixture] 11 | public class TerraformTypeBuilderTest 12 | { 13 | private TerraformTypeBuilder _typeBuilder; 14 | 15 | [SetUp] 16 | public void Setup() 17 | { 18 | _typeBuilder = new TerraformTypeBuilder(); 19 | } 20 | 21 | [TestCase(typeof(int), ExpectedResult = @"""number""")] 22 | [TestCase(typeof(bool), ExpectedResult = @"""bool""")] 23 | [TestCase(typeof(float), ExpectedResult = @"""number""")] 24 | [TestCase(typeof(double), ExpectedResult = @"""number""")] 25 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["string"]]""")] 26 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["number","number"]]""")] 27 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["bool","bool","bool"]]""")] 28 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["string","string","string","string"]]""")] 29 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["string","string","string","string","string"]]""")] 30 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["string","string","string","string","string","string"]]""")] 31 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["string","number","bool","string","number","bool","number"]]""")] 32 | [TestCase(typeof(Tuple), ExpectedResult = """["tuple",["string","string","string","string","string","string","string","string"]]""")] 33 | [TestCase(typeof(List), ExpectedResult = """["list","string"]""")] 34 | [TestCase(typeof(List), ExpectedResult = """["list","number"]""")] 35 | [TestCase(typeof(Dictionary), ExpectedResult = """["map","string"]""")] 36 | [TestCase(typeof(Dictionary), ExpectedResult = """["map","number"]""")] 37 | [TestCase(typeof(TestObjectWithOptionalAttributes), ExpectedResult = """["object",{"nested_int":"number","required_string":"string"},["nested_int"]]""")] 38 | [TestCase(typeof(TestObjectNoOptionalAttributes), ExpectedResult = """["object",{"required_string":"string"},[]]""")] 39 | public string TestGetTerraformTypeAsJson(Type inputType) 40 | { 41 | return _typeBuilder.GetTerraformType(inputType).ToJson(); 42 | } 43 | 44 | [Test] 45 | public void TestObjectMissingMessagePackAttribute() 46 | { 47 | Assert.Throws(() => _typeBuilder.GetTerraformType(typeof(TestMissingAttrObjectResource))); 48 | } 49 | 50 | [SchemaVersion(1)] 51 | [MessagePackObject] 52 | class TestMissingAttrObjectResource 53 | { 54 | [Key("object_attribute")] 55 | [Required] 56 | public TestMissingAttrObject ObjectAttribute { get; set; } 57 | } 58 | 59 | // Missing [MessagePackObject] 60 | class TestMissingAttrObject 61 | { 62 | [Key("some_attribute")] 63 | [Required] 64 | public string SomeAttribute { get; set; } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/TerraformTestHost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Net.Sockets; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Hosting; 10 | using TerraformPluginDotNet.ResourceProvider; 11 | 12 | namespace TerraformPluginDotNet.Testing; 13 | 14 | public class TerraformTestHost : IAsyncDisposable 15 | { 16 | private readonly string _terraformBin; 17 | private readonly int _port; 18 | 19 | private readonly CancellationTokenSource _cancelHost; 20 | private Task _host; 21 | 22 | public TerraformTestHost(string terraformBin, int? port = default) 23 | { 24 | port ??= FindFreePort(); 25 | 26 | if (string.IsNullOrEmpty(terraformBin) || !File.Exists(terraformBin)) 27 | { 28 | throw new ArgumentException($"Terraform binary not found at '{terraformBin}'.", nameof(terraformBin)); 29 | } 30 | 31 | _cancelHost = new CancellationTokenSource(); 32 | _terraformBin = terraformBin; 33 | _port = port.Value; 34 | } 35 | 36 | public void Start(string fullProviderName, Action configure) 37 | { 38 | if (_host != null) 39 | { 40 | throw new InvalidOperationException("Host has already been started."); 41 | } 42 | 43 | _host = Host.CreateDefaultBuilder() 44 | .ConfigureWebHostDefaults(x => x.ConfigureTerraformPlugin(configure, _port)) 45 | .ConfigureServices(x => x.Configure(x => 46 | { 47 | x.FullProviderName = fullProviderName; 48 | x.DebugMode = true; 49 | })) 50 | .Build() 51 | .RunAsync(_cancelHost.Token); 52 | } 53 | 54 | public async Task CreateTerraformTestInstanceAsync(string providerName, bool configureProvider = true, bool configureTerraform = true) 55 | { 56 | var workDir = Path.Combine(Path.GetTempPath(), $"TerraformPluginDotNet_{Guid.NewGuid()}"); 57 | Directory.CreateDirectory(workDir); 58 | 59 | var terraform = new TerraformTestInstance(_terraformBin, providerName, _port, workDir); 60 | 61 | if (configureProvider || configureTerraform) 62 | { 63 | var configFile = new StringBuilder(); 64 | 65 | if (configureProvider) 66 | { 67 | configFile.Append($@" 68 | provider ""{providerName}"" {{}} 69 | "); 70 | } 71 | 72 | if (configureTerraform) 73 | { 74 | configFile.Append($@" 75 | terraform {{ 76 | required_providers {{ 77 | {providerName} = {{ 78 | source = ""example.com/example/{providerName}"" 79 | version = ""1.0.0"" 80 | }} 81 | }} 82 | }} 83 | "); 84 | } 85 | 86 | await File.WriteAllTextAsync(workDir + "/conf.tf", configFile.ToString()); 87 | 88 | await terraform.InitAsync(); 89 | } 90 | 91 | return terraform; 92 | } 93 | 94 | public async ValueTask DisposeAsync() 95 | { 96 | if (_host == null) 97 | { 98 | return; 99 | } 100 | 101 | _cancelHost.Cancel(); 102 | await _host; 103 | } 104 | 105 | private static int FindFreePort() 106 | { 107 | var port = 0; 108 | var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 109 | 110 | try 111 | { 112 | var endPoint = new IPEndPoint(IPAddress.Loopback, 0); 113 | socket.Bind(endPoint); 114 | endPoint = (IPEndPoint)socket.LocalEndPoint; 115 | port = endPoint.Port; 116 | } 117 | finally 118 | { 119 | socket.Close(); 120 | } 121 | 122 | return port; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | x64/ 18 | x86/ 19 | build/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studo 2015 cache/options directory 25 | .vs/ 26 | 27 | # MSTest test Results 28 | [Tt]est[Rr]esult*/ 29 | [Bb]uild[Ll]og.* 30 | 31 | # NUNIT 32 | *.VisualState.xml 33 | TestResult.xml 34 | 35 | # Build Results of an ATL Project 36 | [Dd]ebugPS/ 37 | [Rr]eleasePS/ 38 | dlldata.c 39 | 40 | *_i.c 41 | *_p.c 42 | *_i.h 43 | *.ilk 44 | *.meta 45 | *.obj 46 | *.pch 47 | *.pdb 48 | *.pgc 49 | *.pgd 50 | *.rsp 51 | *.sbr 52 | *.tlb 53 | *.tli 54 | *.tlh 55 | *.tmp 56 | *.tmp_proj 57 | *.log 58 | *.vspscc 59 | *.vssscc 60 | .builds 61 | *.pidb 62 | *.svclog 63 | *.scc 64 | 65 | # Chutzpah Test files 66 | _Chutzpah* 67 | 68 | # Visual C++ cache files 69 | ipch/ 70 | *.aps 71 | *.ncb 72 | *.opensdf 73 | *.sdf 74 | *.cachefile 75 | 76 | # Visual Studio profiler 77 | *.psess 78 | *.vsp 79 | *.vspx 80 | 81 | # TFS 2012 Local Workspace 82 | $tf/ 83 | 84 | # Guidance Automation Toolkit 85 | *.gpState 86 | 87 | # ReSharper is a .NET coding add-in 88 | _ReSharper*/ 89 | *.[Rr]e[Ss]harper 90 | *.DotSettings.user 91 | 92 | # JustCode is a .NET coding addin-in 93 | .JustCode 94 | 95 | # TeamCity is a build add-in 96 | _TeamCity* 97 | 98 | # DotCover is a Code Coverage Tool 99 | *.dotCover 100 | 101 | # NCrunch 102 | _NCrunch_* 103 | .*crunch*.local.xml 104 | 105 | # MightyMoose 106 | *.mm.* 107 | AutoTest.Net/ 108 | 109 | # Web workbench (sass) 110 | .sass-cache/ 111 | 112 | # Installshield output folder 113 | [Ee]xpress/ 114 | 115 | # DocProject is a documentation generator add-in 116 | DocProject/buildhelp/ 117 | DocProject/Help/*.HxT 118 | DocProject/Help/*.HxC 119 | DocProject/Help/*.hhc 120 | DocProject/Help/*.hhk 121 | DocProject/Help/*.hhp 122 | DocProject/Help/Html2 123 | DocProject/Help/html 124 | 125 | # Click-Once directory 126 | publish/ 127 | 128 | # Publish Web Output 129 | *.[Pp]ublish.xml 130 | *.azurePubxml 131 | # TODO: Comment the next line if you want to checkin your web deploy settings 132 | # but database connection strings (with potential passwords) will be unencrypted 133 | *.pubxml 134 | *.publishproj 135 | 136 | # NuGet Packages 137 | *.nupkg 138 | # The packages folder can be ignored because of Package Restore 139 | **/packages/* 140 | # except build/, which is used as an MSBuild target. 141 | !**/packages/build/ 142 | # Uncomment if necessary however generally it will be regenerated when needed 143 | #!**/packages/repositories.config 144 | 145 | # Windows Azure Build Output 146 | csx/ 147 | *.build.csdef 148 | 149 | # Windows Store app package directory 150 | AppPackages/ 151 | 152 | # Others 153 | *.[Cc]ache 154 | ClientBin/ 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | bower_components/ 163 | 164 | # RIA/Silverlight projects 165 | Generated_Code/ 166 | 167 | # Backup & report files from converting an old project file 168 | # to a newer Visual Studio version. Backup files are not needed, 169 | # because we have git ;-) 170 | _UpgradeReport_Files/ 171 | Backup*/ 172 | UpgradeLog*.XML 173 | UpgradeLog*.htm 174 | 175 | # SQL Server files 176 | *.mdf 177 | *.ldf 178 | 179 | # Business Intelligence projects 180 | *.rdl.data 181 | *.bim.layout 182 | *.bim_*.settings 183 | 184 | # Microsoft Fakes 185 | FakesAssemblies/ 186 | 187 | # Node.js Tools for Visual Studio 188 | .ntvs_analysis.dat 189 | 190 | # Visual Studio 6 build log 191 | *.plg 192 | 193 | # Visual Studio 6 workspace options file 194 | *.opt 195 | 196 | # Web files 197 | src/**/lib/ 198 | *.sln.ide/ 199 | *.md.cshtml 200 | src/**/css/ 201 | *.min.css 202 | *.min.js 203 | launchSettings.json 204 | 205 | **/wwwroot/dist/ 206 | **/wwwroot/assets/ 207 | 208 | test.runsettings 209 | /e2e/.terraform/ 210 | /e2e/providers/**/*.zip 211 | !/e2e/providers/**/.gitkeep 212 | /e2e/.terraform.lock.hcl 213 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/CertificateGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | using System.Security.Cryptography.X509Certificates; 3 | using Org.BouncyCastle.Asn1; 4 | using Org.BouncyCastle.Asn1.Pkcs; 5 | using Org.BouncyCastle.Asn1.X509; 6 | using Org.BouncyCastle.Crypto; 7 | using Org.BouncyCastle.Crypto.Generators; 8 | using Org.BouncyCastle.Crypto.Operators; 9 | using Org.BouncyCastle.Crypto.Parameters; 10 | using Org.BouncyCastle.Crypto.Prng; 11 | using Org.BouncyCastle.Math; 12 | using Org.BouncyCastle.OpenSsl; 13 | using Org.BouncyCastle.Pkcs; 14 | using Org.BouncyCastle.Security; 15 | using Org.BouncyCastle.Utilities; 16 | using Org.BouncyCastle.X509; 17 | 18 | namespace TerraformPluginDotNet; 19 | 20 | public static class CertificateGenerator 21 | { 22 | private const int KeyStrength = 2048; 23 | 24 | public static AsymmetricKeyParameter GeneratePrivateKey() 25 | { 26 | var randomGenerator = new CryptoApiRandomGenerator(); 27 | var random = new SecureRandom(randomGenerator); 28 | 29 | // Generate Key 30 | var keyGenerationParameters = new KeyGenerationParameters(random, KeyStrength); 31 | var keyPairGenerator = new RsaKeyPairGenerator(); 32 | keyPairGenerator.Init(keyGenerationParameters); 33 | return keyPairGenerator.GenerateKeyPair().Private; 34 | } 35 | 36 | public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey) 37 | { 38 | var randomGenerator = new CryptoApiRandomGenerator(); 39 | var random = new SecureRandom(randomGenerator); 40 | var certificateGenerator = new X509V3CertificateGenerator(); 41 | 42 | // Serial Number 43 | var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); 44 | certificateGenerator.SetSerialNumber(serialNumber); 45 | 46 | // Issuer and SN 47 | var subjectDN = new X509Name(subjectName); 48 | var issuerDN = new X509Name(issuerName); 49 | certificateGenerator.SetIssuerDN(issuerDN); 50 | certificateGenerator.SetSubjectDN(subjectDN); 51 | 52 | // SAN 53 | var subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, "localhost")); 54 | certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); 55 | 56 | // Validity 57 | var notBefore = DateTime.UtcNow.Date; 58 | var notAfter = notBefore.AddYears(2); 59 | certificateGenerator.SetNotBefore(notBefore); 60 | certificateGenerator.SetNotAfter(notAfter); 61 | 62 | // Public Key 63 | var keyGenerationParameters = new KeyGenerationParameters(random, KeyStrength); 64 | var keyPairGenerator = new RsaKeyPairGenerator(); 65 | keyPairGenerator.Init(keyGenerationParameters); 66 | var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); 67 | certificateGenerator.SetPublicKey(subjectKeyPair.Public); 68 | 69 | // Sign certificate 70 | var signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", issuerPrivKey, random); 71 | var certificate = certificateGenerator.Generate(signatureFactory); 72 | var x509 = new X509Certificate2(certificate.GetEncoded(), (string?)null, X509KeyStorageFlags.Exportable); 73 | 74 | // Private key 75 | var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); 76 | 77 | var seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded()); 78 | if (seq.Count != 9) 79 | { 80 | throw new PemException("Invalid RSA private key"); 81 | } 82 | 83 | var rsa = RsaPrivateKeyStructure.GetInstance(seq); 84 | var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); 85 | 86 | var parms = DotNetUtilities.ToRSAParameters(rsaparams); 87 | var rsa1 = RSA.Create(); 88 | rsa1.ImportParameters(parms); 89 | 90 | // https://github.com/dotnet/runtime/issues/23749 91 | var cert = x509.CopyWithPrivateKey(rsa1); 92 | 93 | return new X509Certificate2(cert.Export(X509ContentType.Pkcs12)); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Testing/Json/TerraformJson.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace TerraformPluginDotNet.Testing.Json; 7 | 8 | // See https://www.terraform.io/internals/json-format#plan-representation 9 | public record TerraformJsonPlan 10 | { 11 | [JsonPropertyName("format_version")] 12 | public string FormatVersion { get; init; } 13 | 14 | [JsonPropertyName("terraform_version")] 15 | public string TerraformVersion { get; init; } 16 | 17 | [JsonPropertyName("planned_values")] 18 | public TerraformPlannedValues PlannedValues { get; init; } 19 | 20 | [JsonPropertyName("output_changes")] 21 | public Dictionary OutputChanges { get; init; } 22 | 23 | [JsonPropertyName("resource_changes")] 24 | public ImmutableList ResourceChanges { get; init; } 25 | 26 | [JsonPropertyName("prior_state")] 27 | public PriorState PriorState { get; init; } 28 | } 29 | 30 | public record TerraformJsonResourceChange 31 | { 32 | [JsonPropertyName("address")] 33 | public string Address { get; init; } 34 | 35 | [JsonPropertyName("previous_address")] 36 | public string PreviousAddress { get; init; } 37 | 38 | [JsonPropertyName("module_address")] 39 | public string ModuleAddress { get; init; } 40 | 41 | [JsonPropertyName("mode")] 42 | public string Mode { get; init; } 43 | 44 | [JsonPropertyName("type")] 45 | public string Type { get; init; } 46 | 47 | [JsonPropertyName("name")] 48 | public string Name { get; init; } 49 | 50 | [JsonPropertyName("index")] 51 | public int Index { get; init; } 52 | 53 | [JsonPropertyName("deposed")] 54 | public string Deposed { get; init; } 55 | 56 | [JsonPropertyName("change")] 57 | public TerraformJsonChange Change { get; init; } 58 | 59 | [JsonPropertyName("action_reason")] 60 | public string ActionReason { get; init; } 61 | } 62 | 63 | // See https://www.terraform.io/internals/json-format#change-representation 64 | public record TerraformJsonChange 65 | { 66 | [JsonPropertyName("actions")] 67 | public ImmutableList Actions { get; init; } 68 | 69 | [JsonPropertyName("before")] 70 | public JsonElement Before { get; init; } 71 | 72 | [JsonPropertyName("after")] 73 | public JsonElement After { get; init; } 74 | } 75 | 76 | public record PriorState 77 | { 78 | [JsonPropertyName("format_version")] 79 | public string FormatVersion { get; init; } 80 | 81 | [JsonPropertyName("terraform_version")] 82 | public string TerraformVersion { get; init; } 83 | 84 | [JsonPropertyName("values")] 85 | public StateValues Values { get; init; } 86 | } 87 | 88 | public class StateValues 89 | { 90 | [JsonPropertyName("root_module")] 91 | public Module RootModule { get; init; } 92 | } 93 | 94 | public class Module 95 | { 96 | [JsonPropertyName("resources")] 97 | public ImmutableList Resources { get; init; } 98 | } 99 | 100 | public class Resource 101 | { 102 | [JsonPropertyName("address")] 103 | public string Address { get; init; } 104 | 105 | [JsonPropertyName("mode")] 106 | public string Mode { get; init; } 107 | 108 | [JsonPropertyName("type")] 109 | public string Type { get; init; } 110 | 111 | [JsonPropertyName("name")] 112 | public string Name { get; init; } 113 | 114 | [JsonPropertyName("provider_name")] 115 | public string ProviderName { get; init; } 116 | 117 | [JsonPropertyName("schema_version")] 118 | public int SchemaVersion { get; init; } 119 | 120 | [JsonPropertyName("values")] 121 | public JsonElement Values { get; init; } 122 | 123 | [JsonPropertyName("sensitive_values")] 124 | public JsonElement SensitiveValues { get; init; } 125 | } 126 | 127 | public record TerraformPlannedValues 128 | { 129 | [JsonPropertyName("outputs")] 130 | public Dictionary Outputs { get; init; } 131 | } 132 | 133 | public record TerraformPlannedValue 134 | { 135 | [JsonPropertyName("sensitive")] 136 | public bool Sensitive { get; init; } 137 | 138 | [JsonPropertyName("type")] 139 | public string Type { get; init; } 140 | 141 | [JsonPropertyName("value")] 142 | public string Value { get; init; } 143 | } 144 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/ResourceProvider/ResourceProviderHost.cs: -------------------------------------------------------------------------------- 1 | using TerraformPluginDotNet.Serialization; 2 | using Tfplugin5; 3 | 4 | namespace TerraformPluginDotNet.ResourceProvider; 5 | 6 | class ResourceProviderHost 7 | { 8 | private readonly IResourceProvider _resourceProvider; 9 | private readonly IResourceUpgrader _resourceUpgrader; 10 | private readonly IDynamicValueSerializer _serializer; 11 | 12 | public ResourceProviderHost( 13 | IResourceProvider resourceProvider, 14 | IResourceUpgrader resourceUpgrader, 15 | IDynamicValueSerializer serializer) 16 | { 17 | _resourceProvider = resourceProvider; 18 | _resourceUpgrader = resourceUpgrader; 19 | _serializer = serializer; 20 | } 21 | 22 | public async Task UpgradeResourceState(UpgradeResourceState.Types.Request request) 23 | { 24 | var upgraded = await _resourceUpgrader.UpgradeResourceStateAsync(request.Version, request.RawState.Json.Memory); 25 | var upgradedSerialized = SerializeDynamicValue(upgraded); 26 | 27 | return new UpgradeResourceState.Types.Response 28 | { 29 | UpgradedState = upgradedSerialized, 30 | }; 31 | } 32 | 33 | public async Task ReadResource(ReadResource.Types.Request request) 34 | { 35 | var current = DeserializeDynamicValue(request.CurrentState); 36 | 37 | var read = await _resourceProvider.ReadAsync(current); 38 | var readSerialized = SerializeDynamicValue(read); 39 | 40 | return new ReadResource.Types.Response 41 | { 42 | NewState = readSerialized, 43 | }; 44 | } 45 | 46 | public async Task PlanResourceChange(PlanResourceChange.Types.Request request) 47 | { 48 | var prior = DeserializeDynamicValue(request.PriorState); 49 | var proposed = DeserializeDynamicValue(request.ProposedNewState); 50 | 51 | var planned = await _resourceProvider.PlanAsync(prior, proposed); 52 | var plannedSerialized = SerializeDynamicValue(planned); 53 | 54 | return new PlanResourceChange.Types.Response 55 | { 56 | PlannedState = plannedSerialized, 57 | }; 58 | } 59 | 60 | public async Task ApplyResourceChange(ApplyResourceChange.Types.Request request) 61 | { 62 | var prior = DeserializeDynamicValue(request.PriorState); 63 | var planned = DeserializeDynamicValue(request.PlannedState); 64 | 65 | if (planned == null) 66 | { 67 | // Delete 68 | await _resourceProvider.DeleteAsync(prior); 69 | return new ApplyResourceChange.Types.Response(); 70 | } 71 | else if (prior == null) 72 | { 73 | // Create 74 | var created = await _resourceProvider.CreateAsync(planned); 75 | var createdSerialized = SerializeDynamicValue(created); 76 | return new ApplyResourceChange.Types.Response 77 | { 78 | NewState = createdSerialized, 79 | }; 80 | } 81 | else 82 | { 83 | // Update 84 | var updated = await _resourceProvider.UpdateAsync(prior, planned); 85 | var updatedSerialized = SerializeDynamicValue(updated); 86 | return new ApplyResourceChange.Types.Response 87 | { 88 | NewState = updatedSerialized, 89 | }; 90 | } 91 | } 92 | 93 | public async Task ImportResourceState(ImportResourceState.Types.Request request) 94 | { 95 | var imported = await _resourceProvider.ImportAsync(request.Id); 96 | 97 | var response = new ImportResourceState.Types.Response(); 98 | response.ImportedResources.AddRange(imported.Select(resource => new ImportResourceState.Types.ImportedResource 99 | { 100 | TypeName = request.TypeName, 101 | State = SerializeDynamicValue(resource), 102 | })); 103 | 104 | return response; 105 | } 106 | 107 | private T DeserializeDynamicValue(DynamicValue value) 108 | { 109 | if (!value.Msgpack.IsEmpty) 110 | { 111 | return _serializer.DeserializeMsgPack(value.Msgpack.Memory); 112 | } 113 | 114 | if (!value.Json.IsEmpty) 115 | { 116 | return _serializer.DeserializeJson(value.Json.Memory); 117 | } 118 | 119 | throw new ArgumentException("Either MessagePack or Json must be non-empty.", nameof(value)); 120 | } 121 | 122 | private DynamicValue SerializeDynamicValue(T value) 123 | { 124 | return new DynamicValue { Msgpack = Google.Protobuf.ByteString.CopyFrom(_serializer.SerializeMsgPack(value)) }; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Schemas/Types/TerraformType.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | 3 | namespace TerraformPluginDotNet.Schemas.Types; 4 | 5 | public abstract record TerraformType 6 | { 7 | // Prevent external derived classes. 8 | private TerraformType() 9 | { 10 | } 11 | 12 | /// 13 | /// Returns the Terraform JSON representation of this type. 14 | /// 15 | public abstract string ToJson(); 16 | 17 | public sealed record TfString() : TerraformType() 18 | { 19 | public override string ToJson() => "\"string\""; 20 | } 21 | 22 | public sealed record TfNumber() : TerraformType() 23 | { 24 | public override string ToJson() => "\"number\""; 25 | } 26 | 27 | public sealed record TfBool() : TerraformType() 28 | { 29 | public override string ToJson() => "\"bool\""; 30 | } 31 | 32 | public sealed record TfMap(TerraformType ValueType) : TerraformType() 33 | { 34 | public override string ToJson() => $"""["map",{ValueType.ToJson()}]"""; 35 | } 36 | 37 | public sealed record TfList(TerraformType ElementType) : TerraformType() 38 | { 39 | public override string ToJson() => $"""["list",{ElementType.ToJson()}]"""; 40 | } 41 | 42 | public sealed record TfSet(TerraformType ElementType) : TerraformType() 43 | { 44 | public override string ToJson() => $"""["set",{ElementType.ToJson()}]"""; 45 | } 46 | 47 | public sealed record TfTuple : TerraformType 48 | { 49 | public TfTuple(ImmutableList elementTypes) 50 | { 51 | ElementTypes = elementTypes; 52 | } 53 | 54 | public ImmutableList ElementTypes { get; } 55 | 56 | public override string ToJson() 57 | { 58 | var elementTypes = string.Join(",", ElementTypes.Select(x => x.ToJson())); 59 | return $"[\"tuple\",[{elementTypes}]]"; 60 | } 61 | 62 | public bool Equals(TfTuple? other) 63 | { 64 | if (other == null) 65 | { 66 | return false; 67 | } 68 | 69 | return ElementTypes.Count == other.ElementTypes.Count && 70 | !ElementTypes.Except(other.ElementTypes).Any(); 71 | } 72 | 73 | public override int GetHashCode() 74 | { 75 | unchecked 76 | { 77 | int hash = 17; 78 | 79 | foreach (var element in ElementTypes) 80 | { 81 | hash = hash * 31 + element.GetHashCode(); 82 | } 83 | 84 | return hash; 85 | } 86 | } 87 | } 88 | 89 | public sealed record TfObject : TerraformType 90 | { 91 | public TfObject( 92 | ImmutableDictionary attributes, 93 | ImmutableHashSet optionalAttributes) 94 | { 95 | if (optionalAttributes.Except(attributes.Keys).Any()) 96 | { 97 | throw new ArgumentException( 98 | $"{nameof(optionalAttributes)} contain an element that is not defined in {nameof(attributes)}.", 99 | nameof(optionalAttributes)); 100 | } 101 | 102 | Attributes = attributes; 103 | OptionalAttributes = optionalAttributes; 104 | } 105 | 106 | public ImmutableDictionary Attributes { get; } 107 | 108 | public ImmutableHashSet OptionalAttributes { get; } 109 | 110 | public override string ToJson() 111 | { 112 | var attrTypes = string.Join(",", Attributes.OrderBy(x => x.Key).Select(x => $"\"{x.Key}\":{x.Value.ToJson()}")); 113 | var optionalAttrs = string.Join(",", OptionalAttributes.OrderBy(x => x).Select(x => $"\"{x}\"")); 114 | return $"[\"object\",{{{attrTypes}}},[{optionalAttrs}]]"; 115 | } 116 | 117 | public bool Equals(TfObject? other) 118 | { 119 | if (other == null) 120 | { 121 | return false; 122 | } 123 | 124 | return OptionalAttributes.SetEquals(other.OptionalAttributes) && 125 | Attributes.Count == other.Attributes.Count && 126 | !Attributes.Except(other.Attributes).Any(); 127 | } 128 | 129 | public override int GetHashCode() 130 | { 131 | unchecked 132 | { 133 | int hash = 17; 134 | 135 | foreach (var element in Attributes) 136 | { 137 | hash = hash * 31 + element.GetHashCode(); 138 | } 139 | 140 | foreach (var element in OptionalAttributes) 141 | { 142 | hash = hash * 31 + element.GetHashCode(); 143 | } 144 | 145 | return hash; 146 | } 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | TerraformPluginDotNet 2 | ===================== 3 | 4 | [![Build status](https://github.com/SamuelFisher/TerraformPluginDotNet/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/SamuelFisher/TerraformPluginDotNet/actions) 5 | 6 | Write custom Terraform providers in C#. See the samples directory for an example provider. 7 | 8 | For more information on this project, see 9 | [this blog post](https://samuelfisher.co.uk/2021/01/terraform-provider-csharp). 10 | 11 | ## Packages 12 | 13 | Package | Version 14 | ------------------------------|--------- 15 | TerraformPluginDotNet | [![NuGet](https://img.shields.io/nuget/vpre/TerraformPluginDotNet.svg)](https://www.nuget.org/packages/TerraformPluginDotNet) 16 | TerraformPluginDotNet.Testing | [![NuGet](https://img.shields.io/nuget/vpre/TerraformPluginDotNet.Testing.svg)](https://www.nuget.org/packages/TerraformPluginDotNet.Testing) 17 | 18 | ## Features 19 | 20 | Currently supports functionality for: 21 | 22 | - Provider configuration 23 | - Resources: 24 | - Create 25 | - Update 26 | - Delete 27 | - Import 28 | - Schema upgrade 29 | - Data sources 30 | 31 | ## Usage 32 | 33 | ### Defining Resources 34 | 35 | To define a custom Terraform resource, create a class to represent the resource: 36 | 37 | ```csharp 38 | [SchemaVersion(1)] 39 | [MessagePackObject] 40 | public class MyResource 41 | { 42 | [Key("id")] 43 | [Computed] 44 | [Description("Unique ID for this resource.")] 45 | [MessagePackFormatter(typeof(ComputedValueFormatter))] 46 | public string Id { get; set; } 47 | 48 | [Key("some_value")] 49 | [JsonPropertyName("some_value")] 50 | [Description("Some value in the resource.")] 51 | [Required] 52 | public string SomeValue { get; set; } 53 | } 54 | ``` 55 | 56 | Please note: 57 | 58 | 1. The class must be serializable as MessagePack. 59 | 2. The class must be serializable by `System.Text.Json`. 60 | - Currently, `JsonPropertyName` must be specified to match multi-word property names as snake case. 61 | 62 | Create an `IResourceProvier` for the resource: 63 | 64 | ```csharp 65 | public class MyResourceProvider : IResourceProvider 66 | { 67 | public Task PlanAsync(MyResource prior, MyResource proposed) 68 | { 69 | // Do something 70 | } 71 | 72 | ... 73 | } 74 | ``` 75 | 76 | See the samples directory for a full example. 77 | 78 | ### Usage In Terraform 79 | 80 | This section explains how to use the `samples/SampleProvider` project with 81 | Terraform. To define your own provider and resource types, create your own 82 | project following the same structure as SampleProvider. 83 | 84 | Instructions are for Linux x64 with Terraform v0.13.3. May work on other platforms 85 | and Terraform versions. 86 | 87 | 1. In the `samples/SampleProvider/SampleProvider` directory, publish a self-contained single-file binary: 88 | 89 | ``` 90 | dotnet publish -r linux-x64 --self-contained -c release -p:PublishSingleFile=true 91 | ``` 92 | 93 | 2. Copy the binary built above, and `serilog.json` to your Terraform plugins directory: 94 | 95 | ```bash 96 | # Create plugin directory 97 | mkdir -p ~/.terraform.d/plugins/example.com/example/sampleprovider/1.0.0/linux_amd64/ 98 | 99 | # Copy binary 100 | cp ./bin/release/net7.0/linux-x64/publish/SampleProvider ~/.terraform.d/plugins/example.com/example/sampleprovider/1.0.0/linux_amd64/terraform-provider-sampleprovider 101 | 102 | # Copy log config 103 | cp ./bin/release/net7.0/linux-x64/publish/serilog.json ~/.terraform.d/plugins/example.com/example/sampleprovider/1.0.0/linux_amd64/serilog.json 104 | ``` 105 | 106 | 3. Create a new Terraform project or open an existing one. The remaining commands 107 | are run in this directory. 108 | 109 | 3. Add to `versions.tf`: 110 | 111 | ```hcl 112 | terraform { 113 | required_providers { 114 | sampleprovider = { 115 | source = "example.com/example/sampleprovider" 116 | version = "1.0.0" 117 | } 118 | } 119 | } 120 | ``` 121 | 122 | 3. Add to `providers.tf`: 123 | 124 | ```hcl 125 | provider "sampleprovider" {} 126 | ``` 127 | 128 | 4. Define a resource in `sample.tf` 129 | 130 | ```hcl 131 | resource "sampleprovider_file" "demo_file" { 132 | path = "/tmp/file.txt" 133 | content = "this is a test" 134 | } 135 | ``` 136 | 137 | 5. Initialize Terraform with the new plugin: `terraform init` 138 | 6. Run `terraform apply` 139 | 7. File at `/tmp/file.txt` should contain the contents `this is a test` 140 | 141 | See `log.txt` in your working directory for troubleshooting. 142 | 143 | ## Debugging 144 | 145 | Terraform can attach to an already started provider by making use of debug mode, 146 | which allows debugging in Visual Studio. To do this, start the SampleProvider 147 | project with the `--DebugMode=true` argument. By default, this will also cause 148 | log messages to be written to the console in addition to a file. 149 | 150 | Once started, it will output an environment variable that can be used to 151 | instruct Terraform to connect to this already running provider. 152 | 153 | For more information, see 154 | [Running Terraform With A Provider in Debug Mode](https://www.terraform.io/docs/extend/debugging.html#running-terraform-with-a-provider-in-debug-mode). 155 | 156 | ## Testing 157 | 158 | Tests that involve running Terraform are marked with `Category=Functional`. To run 159 | these tests, you will need to have Terraform installed and set the environment 160 | variable `TF_PLUGIN_DOTNET_TEST_TF_BIN`. 161 | 162 | For example: 163 | 164 | ```bash 165 | $ TF_PLUGIN_DOTNET_TEST_TF_BIN=/usr/bin/terraform dotnet test --filter Category=Functional 166 | ``` 167 | 168 | In Visual Studio, you can create a `test.runsettings` file to do this: 169 | 170 | ```xml 171 | 172 | 173 | 174 | 175 | C:\Path\To\terraform.exe 176 | 177 | 178 | 179 | ``` 180 | 181 | The `TerraformPluginDotNet.Testing` package can be used to help with writing 182 | tests for custom providers. See `samples/SampleProvider/SampleProvider.Test`. 183 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32421.90 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TerraformPluginDotNet", "TerraformPluginDotNet\TerraformPluginDotNet.csproj", "{970720D7-EB60-4FED-B018-1FB4D3BE6476}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6C058BAB-F093-4BC1-A3B5-64E3CD34080E}" 9 | ProjectSection(SolutionItems) = preProject 10 | .editorconfig = .editorconfig 11 | EndProjectSection 12 | EndProject 13 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{50C52917-AE5D-4F53-BA93-092CB6D76025}" 14 | EndProject 15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TerraformPluginDotNet.Test", "TerraformPluginDotNet.Test\TerraformPluginDotNet.Test.csproj", "{EE43AB61-09E2-4464-835E-C52D35AC4CB3}" 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleProvider", "samples\SampleProvider\SampleProvider\SampleProvider.csproj", "{BA1A484A-E4B4-4D8C-8BF5-99B55F69A3FA}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleProvider.Test", "samples\SampleProvider\SampleProvider.Test\SampleProvider.Test.csproj", "{1A658183-230D-4CED-A410-A088ADA43945}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TerraformPluginDotNet.Testing", "TerraformPluginDotNet.Testing\TerraformPluginDotNet.Testing.csproj", "{0168B353-B5D4-45DF-8372-5BBEE1B6A6C4}" 22 | EndProject 23 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SchemaUpgrade", "samples\SchemaUpgrade\SchemaUpgrade\SchemaUpgrade.csproj", "{0FC32FFB-42DA-493A-AEF3-69A82E743237}" 24 | EndProject 25 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SchemaUpgrade.Test", "samples\SchemaUpgrade\SchemaUpgrade.Test\SchemaUpgrade.Test.csproj", "{7FF7611C-FB28-476E-B821-B0AC97DFA5F8}" 26 | EndProject 27 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataSourceProvider", "samples\DataSourceProvider\DataSourceProvider\DataSourceProvider.csproj", "{98403831-CB6A-4B24-B829-7ACCB78F423A}" 28 | EndProject 29 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataSourceProvider.Test", "samples\DataSourceProvider\DataSourceProvider.Test\DataSourceProvider.Test.csproj", "{ADBDFDA9-7C8F-467D-94A4-12DDDDCE82AA}" 30 | EndProject 31 | Global 32 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 33 | Debug|Any CPU = Debug|Any CPU 34 | Release|Any CPU = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 37 | {970720D7-EB60-4FED-B018-1FB4D3BE6476}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {970720D7-EB60-4FED-B018-1FB4D3BE6476}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {970720D7-EB60-4FED-B018-1FB4D3BE6476}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {970720D7-EB60-4FED-B018-1FB4D3BE6476}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {EE43AB61-09E2-4464-835E-C52D35AC4CB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {EE43AB61-09E2-4464-835E-C52D35AC4CB3}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {EE43AB61-09E2-4464-835E-C52D35AC4CB3}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {EE43AB61-09E2-4464-835E-C52D35AC4CB3}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {BA1A484A-E4B4-4D8C-8BF5-99B55F69A3FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {BA1A484A-E4B4-4D8C-8BF5-99B55F69A3FA}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {BA1A484A-E4B4-4D8C-8BF5-99B55F69A3FA}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {BA1A484A-E4B4-4D8C-8BF5-99B55F69A3FA}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {1A658183-230D-4CED-A410-A088ADA43945}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {1A658183-230D-4CED-A410-A088ADA43945}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {1A658183-230D-4CED-A410-A088ADA43945}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {1A658183-230D-4CED-A410-A088ADA43945}.Release|Any CPU.Build.0 = Release|Any CPU 53 | {0168B353-B5D4-45DF-8372-5BBEE1B6A6C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 54 | {0168B353-B5D4-45DF-8372-5BBEE1B6A6C4}.Debug|Any CPU.Build.0 = Debug|Any CPU 55 | {0168B353-B5D4-45DF-8372-5BBEE1B6A6C4}.Release|Any CPU.ActiveCfg = Release|Any CPU 56 | {0168B353-B5D4-45DF-8372-5BBEE1B6A6C4}.Release|Any CPU.Build.0 = Release|Any CPU 57 | {0FC32FFB-42DA-493A-AEF3-69A82E743237}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 58 | {0FC32FFB-42DA-493A-AEF3-69A82E743237}.Debug|Any CPU.Build.0 = Debug|Any CPU 59 | {0FC32FFB-42DA-493A-AEF3-69A82E743237}.Release|Any CPU.ActiveCfg = Release|Any CPU 60 | {0FC32FFB-42DA-493A-AEF3-69A82E743237}.Release|Any CPU.Build.0 = Release|Any CPU 61 | {7FF7611C-FB28-476E-B821-B0AC97DFA5F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 62 | {7FF7611C-FB28-476E-B821-B0AC97DFA5F8}.Debug|Any CPU.Build.0 = Debug|Any CPU 63 | {7FF7611C-FB28-476E-B821-B0AC97DFA5F8}.Release|Any CPU.ActiveCfg = Release|Any CPU 64 | {7FF7611C-FB28-476E-B821-B0AC97DFA5F8}.Release|Any CPU.Build.0 = Release|Any CPU 65 | {98403831-CB6A-4B24-B829-7ACCB78F423A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 66 | {98403831-CB6A-4B24-B829-7ACCB78F423A}.Debug|Any CPU.Build.0 = Debug|Any CPU 67 | {98403831-CB6A-4B24-B829-7ACCB78F423A}.Release|Any CPU.ActiveCfg = Release|Any CPU 68 | {98403831-CB6A-4B24-B829-7ACCB78F423A}.Release|Any CPU.Build.0 = Release|Any CPU 69 | {ADBDFDA9-7C8F-467D-94A4-12DDDDCE82AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 70 | {ADBDFDA9-7C8F-467D-94A4-12DDDDCE82AA}.Debug|Any CPU.Build.0 = Debug|Any CPU 71 | {ADBDFDA9-7C8F-467D-94A4-12DDDDCE82AA}.Release|Any CPU.ActiveCfg = Release|Any CPU 72 | {ADBDFDA9-7C8F-467D-94A4-12DDDDCE82AA}.Release|Any CPU.Build.0 = Release|Any CPU 73 | EndGlobalSection 74 | GlobalSection(SolutionProperties) = preSolution 75 | HideSolutionNode = FALSE 76 | EndGlobalSection 77 | GlobalSection(NestedProjects) = preSolution 78 | {BA1A484A-E4B4-4D8C-8BF5-99B55F69A3FA} = {50C52917-AE5D-4F53-BA93-092CB6D76025} 79 | {1A658183-230D-4CED-A410-A088ADA43945} = {50C52917-AE5D-4F53-BA93-092CB6D76025} 80 | {0FC32FFB-42DA-493A-AEF3-69A82E743237} = {50C52917-AE5D-4F53-BA93-092CB6D76025} 81 | {7FF7611C-FB28-476E-B821-B0AC97DFA5F8} = {50C52917-AE5D-4F53-BA93-092CB6D76025} 82 | {98403831-CB6A-4B24-B829-7ACCB78F423A} = {50C52917-AE5D-4F53-BA93-092CB6D76025} 83 | {ADBDFDA9-7C8F-467D-94A4-12DDDDCE82AA} = {50C52917-AE5D-4F53-BA93-092CB6D76025} 84 | EndGlobalSection 85 | GlobalSection(ExtensibilityGlobals) = postSolution 86 | SolutionGuid = {6F7700C3-5F6B-4D22-A507-A2EA099D993D} 87 | EndGlobalSection 88 | EndGlobal 89 | -------------------------------------------------------------------------------- /samples/SampleProvider/SampleProvider.Test/SampleProviderTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using NUnit.Framework; 7 | using TerraformPluginDotNet; 8 | using TerraformPluginDotNet.ResourceProvider; 9 | using TerraformPluginDotNet.Testing; 10 | 11 | namespace SampleProvider.Test; 12 | 13 | [TestFixture(Category = "Functional", Explicit = true)] 14 | public class SampleProviderTest 15 | { 16 | private const string ProviderName = "sampleprovider"; 17 | 18 | private TerraformTestHost _host; 19 | 20 | [OneTimeSetUp] 21 | public void Setup() 22 | { 23 | _host = new TerraformTestHost(Environment.GetEnvironmentVariable("TF_PLUGIN_DOTNET_TEST_TF_BIN")); 24 | _host.Start($"example.com/example/{ProviderName}", Configure); 25 | } 26 | 27 | [OneTimeTearDown] 28 | public async Task TearDown() 29 | { 30 | await _host.DisposeAsync(); 31 | } 32 | 33 | private void Configure(IServiceCollection services, IResourceRegistryContext registryContext) 34 | { 35 | services.AddSingleton(); 36 | services.AddTerraformProviderConfigurator(); 37 | services.AddSingleton, SampleFileResourceProvider>(); 38 | registryContext.RegisterResource($"{ProviderName}_file"); 39 | } 40 | 41 | [Test] 42 | public async Task TestCreateFile() 43 | { 44 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 45 | 46 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 47 | var testFilePath = Path.Combine(terraform.WorkDir, "test.txt"); 48 | var fileContent = "this is a test"; 49 | 50 | await File.WriteAllTextAsync(resourcePath, $@" 51 | resource ""{ProviderName}_file"" ""demo_file"" {{ 52 | path = ""{testFilePath.Replace("\\", "\\\\")}"" 53 | content = ""{fileContent}"" 54 | }} 55 | "); 56 | 57 | await terraform.PlanAsync(); 58 | await terraform.ApplyAsync(); 59 | 60 | Assert.That(File.Exists(testFilePath)); 61 | Assert.That(await File.ReadAllTextAsync(testFilePath), Is.EqualTo(fileContent)); 62 | } 63 | 64 | [Test] 65 | public async Task TestUpdateFile() 66 | { 67 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 68 | 69 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 70 | var testFilePath = Path.Combine(terraform.WorkDir, "test.txt"); 71 | 72 | await File.WriteAllTextAsync(resourcePath, $@" 73 | resource ""{ProviderName}_file"" ""demo_file"" {{ 74 | path = ""{testFilePath.Replace("\\", "\\\\")}"" 75 | content = ""Content 1"" 76 | }} 77 | "); 78 | 79 | await terraform.PlanAsync(); 80 | await terraform.ApplyAsync(); 81 | 82 | var updatedContent = "Content 2"; 83 | await File.WriteAllTextAsync(resourcePath, $@" 84 | resource ""{ProviderName}_file"" ""demo_file"" {{ 85 | path = ""{testFilePath.Replace("\\", "\\\\")}"" 86 | content = ""{updatedContent}"" 87 | }} 88 | "); 89 | 90 | await terraform.PlanAsync(); 91 | await terraform.ApplyAsync(); 92 | 93 | Assert.That(File.Exists(testFilePath)); 94 | Assert.That(await File.ReadAllTextAsync(testFilePath), Is.EqualTo(updatedContent)); 95 | } 96 | 97 | [Test] 98 | public async Task TestDeleteFile() 99 | { 100 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 101 | 102 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 103 | var testFilePath = Path.Combine(terraform.WorkDir, "test.txt"); 104 | 105 | await File.WriteAllTextAsync(resourcePath, $@" 106 | resource ""{ProviderName}_file"" ""demo_file"" {{ 107 | path = ""{testFilePath.Replace("\\", "\\\\")}"" 108 | content = ""Content"" 109 | }} 110 | "); 111 | 112 | await terraform.ApplyAsync(); 113 | 114 | await File.WriteAllTextAsync(resourcePath, string.Empty); 115 | await terraform.PlanAsync(); 116 | await terraform.ApplyAsync(); 117 | 118 | Assert.That(File.Exists(testFilePath), Is.False); 119 | } 120 | 121 | [Test] 122 | public async Task TestImportFile() 123 | { 124 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 125 | 126 | var resourceAddress = $"{ProviderName}_file.imported"; 127 | 128 | var resourcePath = Path.Combine(terraform.WorkDir, "imported.tf"); 129 | var testFilePath = Path.Combine(terraform.WorkDir, "test.txt"); 130 | await File.WriteAllTextAsync(testFilePath, "Something to import."); 131 | 132 | await File.WriteAllTextAsync(resourcePath, $@" 133 | resource ""{ProviderName}_file"" ""imported"" {{ 134 | path = ""{testFilePath.Replace("\\", "\\\\")}"" 135 | content = ""Something to import."" 136 | }} 137 | "); 138 | 139 | await terraform.ImportAsync(resourceAddress, testFilePath); 140 | 141 | var changes = await terraform.PlanWithOutputAsync(); 142 | Assert.That(changes.ResourceChanges.SelectMany(x => x.Change.Actions).All(x => x == "no-op"), Is.True); 143 | } 144 | 145 | [Test] 146 | public async Task TestConfigureFileHeader() 147 | { 148 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName, configureProvider: false); 149 | 150 | await File.AppendAllTextAsync(terraform.WorkDir + "/conf.tf", $@" 151 | provider ""{ProviderName}"" {{ 152 | file_header = ""# File Header"" 153 | }} 154 | "); 155 | 156 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 157 | var testFilePath = Path.Combine(terraform.WorkDir, "test.txt"); 158 | var fileContent = "this is a test"; 159 | 160 | await File.WriteAllTextAsync(resourcePath, $@" 161 | resource ""{ProviderName}_file"" ""demo_file"" {{ 162 | path = ""{testFilePath.Replace("\\", "\\\\")}"" 163 | content = ""{fileContent}"" 164 | }} 165 | "); 166 | 167 | await terraform.PlanAsync(); 168 | await terraform.ApplyAsync(); 169 | 170 | Assert.That(File.Exists(testFilePath)); 171 | Assert.That( 172 | NormalizeLineEndings(await File.ReadAllTextAsync(testFilePath)), 173 | Is.EqualTo(NormalizeLineEndings($@" 174 | # File Header 175 | {fileContent} 176 | ".Trim()))); 177 | } 178 | 179 | private static string NormalizeLineEndings(string input) => input.Replace("\r\n", "\n"); 180 | } 181 | -------------------------------------------------------------------------------- /TerraformPluginDotNet.Test/Functional/TerraformResourceTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Text.Json; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using NUnit.Framework; 8 | using TerraformPluginDotNet.ResourceProvider; 9 | using TerraformPluginDotNet.Testing; 10 | 11 | namespace TerraformPluginDotNet.Test.Functional; 12 | 13 | [TestFixture(Category = "Functional", Explicit = true)] 14 | public class TerraformResourceTest 15 | { 16 | private const string ProviderName = "test"; 17 | 18 | private TerraformTestHost _host; 19 | 20 | [OneTimeSetUp] 21 | public void Setup() 22 | { 23 | _host = new TerraformTestHost(Environment.GetEnvironmentVariable("TF_PLUGIN_DOTNET_TEST_TF_BIN")); 24 | _host.Start($"example.com/example/{ProviderName}", Configure); 25 | } 26 | 27 | [OneTimeTearDown] 28 | public async Task TearDown() 29 | { 30 | await _host.DisposeAsync(); 31 | } 32 | 33 | private void Configure(IServiceCollection services, IResourceRegistryContext registryContext) 34 | { 35 | services.AddSingleton, TestResourceProvider>(); 36 | registryContext.RegisterResource($"{ProviderName}_resource"); 37 | } 38 | 39 | [Test] 40 | public async Task TestPlanCreateAllFields() 41 | { 42 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 43 | 44 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 45 | 46 | await File.WriteAllTextAsync(resourcePath, """ 47 | resource "test_resource" "test" { 48 | required_string = "value" 49 | required_int = 1 50 | int_attribute = 1 51 | boolean_attribute = true 52 | float_attribute = 1.0 53 | double_attribute = 1.0 54 | string_set_attribute = ["one", "two"] 55 | string_list_attribute = ["one", "two", "three"] 56 | int_list_attribute = [1, 2, 3] 57 | string_map_attribute = { 58 | a = "one", 59 | b = "two", 60 | c = "three" 61 | } 62 | int_map_attribute = { 63 | a = 1, 64 | b = 2, 65 | c = 3 66 | } 67 | object_1 = { 68 | required_string = "value" 69 | nested_int = 1 70 | } 71 | object_2 = { 72 | required_string = "value" 73 | } 74 | tuple_attribute = [1, "value"] 75 | } 76 | """); 77 | 78 | var plan = await terraform.PlanWithOutputAsync(); 79 | 80 | Assert.That(plan.ResourceChanges, Has.Count.EqualTo(1)); 81 | Assert.That(plan.ResourceChanges.Single().Change.Actions.Single(), Is.EqualTo("create")); 82 | Assert.That(plan.ResourceChanges.Single().Change.Before.ValueKind, Is.EqualTo(JsonValueKind.Null)); 83 | 84 | var after = JsonSerializer.Serialize(plan.ResourceChanges.Single().Change.After, new JsonSerializerOptions() { WriteIndented = true }); 85 | var expected = """ 86 | { 87 | "boolean_attribute": true, 88 | "double_attribute": 1, 89 | "float_attribute": 1, 90 | "int_attribute": 1, 91 | "int_list_attribute": [ 92 | 1, 93 | 2, 94 | 3 95 | ], 96 | "int_map_attribute": { 97 | "a": 1, 98 | "b": 2, 99 | "c": 3 100 | }, 101 | "object_1": { 102 | "nested_int": 1, 103 | "required_string": "value" 104 | }, 105 | "object_2": { 106 | "required_string": "value" 107 | }, 108 | "required_int": 1, 109 | "required_string": "value", 110 | "string_list_attribute": [ 111 | "one", 112 | "two", 113 | "three" 114 | ], 115 | "string_map_attribute": { 116 | "a": "one", 117 | "b": "two", 118 | "c": "three" 119 | }, 120 | "string_set_attribute": [ 121 | "one", 122 | "two" 123 | ], 124 | "tuple_attribute": [ 125 | 1, 126 | "value" 127 | ] 128 | } 129 | """; 130 | 131 | Assert.That(after, Is.EqualTo(expected)); 132 | } 133 | 134 | [Test] 135 | public async Task TestPlanCreateOnlyRequiredFields() 136 | { 137 | using var terraform = await _host.CreateTerraformTestInstanceAsync(ProviderName); 138 | 139 | var resourcePath = Path.Combine(terraform.WorkDir, "file.tf"); 140 | 141 | await File.WriteAllTextAsync(resourcePath, """ 142 | resource "test_resource" "test" { 143 | required_string = "value" 144 | required_int = 1 145 | object_1 = { 146 | required_string = "test" 147 | } 148 | object_2 = { 149 | required_string = "test" 150 | } 151 | } 152 | """); 153 | 154 | var plan = await terraform.PlanWithOutputAsync(); 155 | 156 | Assert.That(plan.ResourceChanges, Has.Count.EqualTo(1)); 157 | Assert.That(plan.ResourceChanges.Single().Change.Actions.Single(), Is.EqualTo("create")); 158 | Assert.That(plan.ResourceChanges.Single().Change.Before.ValueKind, Is.EqualTo(JsonValueKind.Null)); 159 | 160 | var after = JsonSerializer.Serialize(plan.ResourceChanges.Single().Change.After, new JsonSerializerOptions() { WriteIndented = true }); 161 | var expected = """ 162 | { 163 | "boolean_attribute": null, 164 | "double_attribute": null, 165 | "float_attribute": null, 166 | "int_attribute": null, 167 | "int_list_attribute": null, 168 | "int_map_attribute": null, 169 | "object_1": { 170 | "nested_int": null, 171 | "required_string": "test" 172 | }, 173 | "object_2": { 174 | "required_string": "test" 175 | }, 176 | "required_int": 1, 177 | "required_string": "value", 178 | "string_list_attribute": null, 179 | "string_map_attribute": null, 180 | "string_set_attribute": null, 181 | "tuple_attribute": null 182 | } 183 | """; 184 | 185 | Assert.That(after, Is.EqualTo(expected)); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Schemas/Types/TerraformTypeBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Reflection; 3 | using TerraformPluginDotNet.Resources; 4 | using KeyAttribute = MessagePack.KeyAttribute; 5 | using MessagePackObject = MessagePack.MessagePackObjectAttribute; 6 | 7 | namespace TerraformPluginDotNet.Schemas.Types; 8 | 9 | class TerraformTypeBuilder : ITerraformTypeBuilder 10 | { 11 | public TerraformType GetTerraformType(Type t) 12 | { 13 | if (t.IsValueType && Nullable.GetUnderlyingType(t) is Type underlyingType) 14 | { 15 | t = underlyingType; 16 | } 17 | 18 | if (t == typeof(string)) 19 | { 20 | return new TerraformType.TfString(); 21 | } 22 | 23 | if (t == typeof(int) || t == typeof(float) || t == typeof(double)) 24 | { 25 | return new TerraformType.TfNumber(); 26 | } 27 | 28 | if (t == typeof(bool)) 29 | { 30 | return new TerraformType.TfBool(); 31 | } 32 | 33 | var genericType = t.IsGenericType ? t.GetGenericTypeDefinition() : null; 34 | 35 | if (genericType == typeof(Tuple<>)) 36 | { 37 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 38 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type)); 39 | } 40 | 41 | if (genericType == typeof(Tuple<,>)) 42 | { 43 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 44 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 45 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type)); 46 | } 47 | 48 | if (genericType == typeof(Tuple<,,>)) 49 | { 50 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 51 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 52 | var el2Type = GetTerraformType(t.GenericTypeArguments[2]); 53 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type, el2Type)); 54 | } 55 | 56 | if (genericType == typeof(Tuple<,,,>)) 57 | { 58 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 59 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 60 | var el2Type = GetTerraformType(t.GenericTypeArguments[2]); 61 | var el3Type = GetTerraformType(t.GenericTypeArguments[3]); 62 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type, el2Type, el3Type)); 63 | } 64 | 65 | if (genericType == typeof(Tuple<,,,,>)) 66 | { 67 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 68 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 69 | var el2Type = GetTerraformType(t.GenericTypeArguments[2]); 70 | var el3Type = GetTerraformType(t.GenericTypeArguments[3]); 71 | var el4Type = GetTerraformType(t.GenericTypeArguments[4]); 72 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type, el2Type, el3Type, el4Type)); 73 | } 74 | 75 | if (genericType == typeof(Tuple<,,,,,>)) 76 | { 77 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 78 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 79 | var el2Type = GetTerraformType(t.GenericTypeArguments[2]); 80 | var el3Type = GetTerraformType(t.GenericTypeArguments[3]); 81 | var el4Type = GetTerraformType(t.GenericTypeArguments[4]); 82 | var el5Type = GetTerraformType(t.GenericTypeArguments[5]); 83 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type, el2Type, el3Type, el4Type, el5Type)); 84 | } 85 | 86 | if (genericType == typeof(Tuple<,,,,,,>)) 87 | { 88 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 89 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 90 | var el2Type = GetTerraformType(t.GenericTypeArguments[2]); 91 | var el3Type = GetTerraformType(t.GenericTypeArguments[3]); 92 | var el4Type = GetTerraformType(t.GenericTypeArguments[4]); 93 | var el5Type = GetTerraformType(t.GenericTypeArguments[5]); 94 | var el6Type = GetTerraformType(t.GenericTypeArguments[6]); 95 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type, el2Type, el3Type, el4Type, el5Type, el6Type)); 96 | } 97 | 98 | if (genericType == typeof(Tuple<,,,,,,,>)) 99 | { 100 | var el0Type = GetTerraformType(t.GenericTypeArguments[0]); 101 | var el1Type = GetTerraformType(t.GenericTypeArguments[1]); 102 | var el2Type = GetTerraformType(t.GenericTypeArguments[2]); 103 | var el3Type = GetTerraformType(t.GenericTypeArguments[3]); 104 | var el4Type = GetTerraformType(t.GenericTypeArguments[4]); 105 | var el5Type = GetTerraformType(t.GenericTypeArguments[5]); 106 | var el6Type = GetTerraformType(t.GenericTypeArguments[6]); 107 | var el7Type = GetTerraformType(t.GenericTypeArguments[7]); 108 | return new TerraformType.TfTuple(ImmutableList.Create(el0Type, el1Type, el2Type, el3Type, el4Type, el5Type, el6Type, el7Type)); 109 | } 110 | 111 | var genericInterfaces = t.GetInterfaces() 112 | .Where(x => x.IsGenericType) 113 | .GroupBy(x => x.GetGenericTypeDefinition()) 114 | .ToDictionary(x => x.Key, x => x.First()); 115 | 116 | if (genericInterfaces.TryGetValue(typeof(IDictionary<,>), out var dictType)) 117 | { 118 | var valueType = GetTerraformType(dictType.GenericTypeArguments[1]); 119 | return new TerraformType.TfMap(valueType); 120 | } 121 | 122 | if (genericInterfaces.TryGetValue(typeof(ISet<>), out var setType)) 123 | { 124 | var elementType = GetTerraformType(setType.GenericTypeArguments.Single()); 125 | return new TerraformType.TfSet(elementType); 126 | } 127 | 128 | if (genericInterfaces.TryGetValue(typeof(ICollection<>), out var collectionType)) 129 | { 130 | var elementType = GetTerraformType(collectionType.GenericTypeArguments.Single()); 131 | return new TerraformType.TfList(elementType); 132 | } 133 | 134 | return GetTerraformTypeAsObject(t); 135 | } 136 | 137 | private TerraformType GetTerraformTypeAsObject(Type t) 138 | { 139 | if (t.GetCustomAttribute() == null) 140 | { 141 | throw new InvalidOperationException($"Type {t.Name} is represented as a Terraform object, but is missing a {nameof(MessagePackObject)} attribute."); 142 | } 143 | 144 | var properties = t.GetProperties(); 145 | var attrTypes = properties.ToDictionary( 146 | prop => prop.GetCustomAttribute()?.StringKey ?? throw new InvalidOperationException($"Missing {nameof(KeyAttribute)} on {prop.Name} in {t.Name}."), 147 | prop => GetTerraformType(prop.PropertyType)); 148 | var optionalAttrs = properties.Where(x => !IsRequiredAttribute(x)).Select(x => x.GetCustomAttribute()?.StringKey ?? throw new InvalidOperationException($"Missing {nameof(KeyAttribute)} on {x.Name} in {t.Name}.")).ToList(); 149 | return new TerraformType.TfObject(attrTypes.ToImmutableDictionary(), optionalAttrs.ToImmutableHashSet()); 150 | } 151 | 152 | public static bool IsRequiredAttribute(PropertyInfo property) 153 | { 154 | return property.GetCustomAttribute() != null || 155 | (property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Services/Terraform5ProviderService.cs: -------------------------------------------------------------------------------- 1 | using Grpc.Core; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using TerraformPluginDotNet.ProviderConfig; 5 | using TerraformPluginDotNet.ResourceProvider; 6 | using Tfplugin5; 7 | 8 | namespace TerraformPluginDotNet.Services; 9 | 10 | class Terraform5ProviderService : Provider.ProviderBase 11 | { 12 | private readonly ILogger _logger; 13 | private readonly IHostApplicationLifetime _lifetime; 14 | private readonly ResourceRegistry _resourceRegistry; 15 | private readonly IServiceProvider _serviceProvider; 16 | private readonly ProviderConfigurationRegistry? _providerConfiguration; 17 | 18 | public Terraform5ProviderService( 19 | ILogger logger, 20 | IHostApplicationLifetime lifetime, 21 | ResourceRegistry resourceRegistry, 22 | IServiceProvider serviceProvider, 23 | ProviderConfigurationRegistry? providerConfiguration = null) 24 | { 25 | _logger = logger; 26 | _lifetime = lifetime; 27 | _resourceRegistry = resourceRegistry; 28 | _serviceProvider = serviceProvider; 29 | _providerConfiguration = providerConfiguration; 30 | } 31 | 32 | public override async Task Configure(Configure.Types.Request request, ServerCallContext context) 33 | { 34 | if (_providerConfiguration == null) 35 | { 36 | return new Configure.Types.Response { }; 37 | } 38 | 39 | var configurationHostType = typeof(ProviderConfigurationHost<>).MakeGenericType(_providerConfiguration.ConfigurationType); 40 | var configurationHost = _serviceProvider.GetService(configurationHostType); 41 | await (Task)configurationHostType.GetMethod(nameof(ProviderConfigurationHost.ConfigureAsync))! 42 | .Invoke(configurationHost, new[] { request })!; 43 | return new Configure.Types.Response { }; 44 | } 45 | 46 | public override Task GetSchema(GetProviderSchema.Types.Request request, ServerCallContext context) 47 | { 48 | var res = new GetProviderSchema.Types.Response 49 | { 50 | Provider = _providerConfiguration?.ConfigurationSchema ?? new Schema { Block = new Schema.Types.Block { } }, 51 | }; 52 | 53 | foreach (var schema in _resourceRegistry.Schemas) 54 | { 55 | res.ResourceSchemas.Add(schema.Key, schema.Value); 56 | } 57 | 58 | foreach (var schema in _resourceRegistry.DataSchemas) 59 | { 60 | res.DataSourceSchemas.Add(schema.Key, schema.Value); 61 | } 62 | 63 | return Task.FromResult(res); 64 | } 65 | 66 | public override Task PlanResourceChange(PlanResourceChange.Types.Request request, ServerCallContext context) 67 | { 68 | if (!_resourceRegistry.Types.TryGetValue(request.TypeName, out var resourceType)) 69 | { 70 | return Task.FromResult(new Tfplugin5.PlanResourceChange.Types.Response 71 | { 72 | Diagnostics = 73 | { 74 | new Diagnostic { Detail = "Unknown type name." }, 75 | }, 76 | }); 77 | } 78 | 79 | var providerHostType = typeof(ResourceProviderHost<>).MakeGenericType(resourceType); 80 | var provider = _serviceProvider.GetService(providerHostType); 81 | return (Task)providerHostType.GetMethod(nameof(ResourceProviderHost.PlanResourceChange))! 82 | .Invoke(provider, new[] { request })!; 83 | } 84 | 85 | public override Task ApplyResourceChange(ApplyResourceChange.Types.Request request, ServerCallContext context) 86 | { 87 | if (!_resourceRegistry.Types.TryGetValue(request.TypeName, out var resourceType)) 88 | { 89 | return Task.FromResult(new ApplyResourceChange.Types.Response 90 | { 91 | Diagnostics = 92 | { 93 | new Diagnostic { Detail = "Unknown type name." }, 94 | }, 95 | }); 96 | } 97 | 98 | var providerHostType = typeof(ResourceProviderHost<>).MakeGenericType(resourceType); 99 | var provider = _serviceProvider.GetService(providerHostType); 100 | return (Task)providerHostType.GetMethod(nameof(ResourceProviderHost.ApplyResourceChange))! 101 | .Invoke(provider, new[] { request })!; 102 | } 103 | 104 | public override Task UpgradeResourceState(UpgradeResourceState.Types.Request request, ServerCallContext context) 105 | { 106 | if (!_resourceRegistry.Types.TryGetValue(request.TypeName, out var resourceType)) 107 | { 108 | return Task.FromResult(new UpgradeResourceState.Types.Response 109 | { 110 | Diagnostics = 111 | { 112 | new Diagnostic { Detail = "Unknown type name." }, 113 | }, 114 | }); 115 | } 116 | 117 | var providerHostType = typeof(ResourceProviderHost<>).MakeGenericType(resourceType); 118 | var provider = _serviceProvider.GetService(providerHostType); 119 | return (Task)providerHostType.GetMethod(nameof(ResourceProviderHost.UpgradeResourceState))! 120 | .Invoke(provider, new[] { request })!; 121 | } 122 | 123 | public override Task ReadResource(ReadResource.Types.Request request, ServerCallContext context) 124 | { 125 | if (!_resourceRegistry.Types.TryGetValue(request.TypeName, out var resourceType)) 126 | { 127 | return Task.FromResult(new ReadResource.Types.Response 128 | { 129 | Diagnostics = 130 | { 131 | new Diagnostic { Detail = "Unknown type name." }, 132 | }, 133 | }); 134 | } 135 | 136 | var providerHostType = typeof(ResourceProviderHost<>).MakeGenericType(resourceType); 137 | var provider = _serviceProvider.GetService(providerHostType); 138 | return (Task)providerHostType.GetMethod(nameof(ResourceProviderHost.ReadResource))! 139 | .Invoke(provider, new[] { request })!; 140 | } 141 | 142 | public override Task ImportResourceState(ImportResourceState.Types.Request request, ServerCallContext context) 143 | { 144 | if (!_resourceRegistry.Types.TryGetValue(request.TypeName, out var resourceType)) 145 | { 146 | return Task.FromResult(new ImportResourceState.Types.Response 147 | { 148 | Diagnostics = 149 | { 150 | new Diagnostic { Detail = "Unknown type name." }, 151 | }, 152 | }); 153 | } 154 | 155 | var providerHostType = typeof(ResourceProviderHost<>).MakeGenericType(resourceType); 156 | var provider = _serviceProvider.GetService(providerHostType); 157 | return (Task)providerHostType.GetMethod(nameof(ResourceProviderHost.ImportResourceState))! 158 | .Invoke(provider, new[] { request })!; 159 | } 160 | 161 | public override Task PrepareProviderConfig(PrepareProviderConfig.Types.Request request, ServerCallContext context) 162 | { 163 | return Task.FromResult(new PrepareProviderConfig.Types.Response()); 164 | } 165 | 166 | public override Task Stop(Stop.Types.Request request, ServerCallContext context) 167 | { 168 | _lifetime.StopApplication(); 169 | _lifetime.ApplicationStopped.WaitHandle.WaitOne(); 170 | return Task.FromResult(new Stop.Types.Response()); 171 | } 172 | 173 | public override Task ValidateDataSourceConfig(ValidateDataSourceConfig.Types.Request request, ServerCallContext context) 174 | { 175 | return Task.FromResult(new ValidateDataSourceConfig.Types.Response()); 176 | } 177 | 178 | public override Task ValidateResourceTypeConfig(ValidateResourceTypeConfig.Types.Request request, ServerCallContext context) 179 | { 180 | return Task.FromResult(new ValidateResourceTypeConfig.Types.Response()); 181 | } 182 | 183 | public override Task ReadDataSource(ReadDataSource.Types.Request request, ServerCallContext context) 184 | { 185 | if (!_resourceRegistry.DataTypes.TryGetValue(request.TypeName, out var resourceType)) 186 | { 187 | return Task.FromResult(new ReadDataSource.Types.Response 188 | { 189 | Diagnostics = 190 | { 191 | new Diagnostic { Detail = "Unknown type name." }, 192 | }, 193 | }); 194 | } 195 | 196 | var providerHostType = typeof(DataSourceProviderHost<>).MakeGenericType(resourceType); 197 | var provider = _serviceProvider.GetService(providerHostType); 198 | return (Task)providerHostType.GetMethod(nameof(DataSourceProviderHost.ReadDataSource))! 199 | .Invoke(provider, new[] { request })!; 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /TerraformPluginDotNet/Protos/tfplugin5.2.proto: -------------------------------------------------------------------------------- 1 | // This file is from https://github.com/hashicorp/terraform/blob/master/docs/plugin-protocol/tfplugin5.2.proto 2 | // Licensed under the terms of the Mozilla Public License 2.0, available here: 3 | // https://github.com/hashicorp/terraform/blob/master/LICENSE 4 | // 5 | // This file defines version 5.2 of the RPC protocol. To implement a plugin 6 | // against this protocol, copy this definition into your own codebase and 7 | // use protoc to generate stubs for your target language. 8 | // 9 | // This file will not be updated. Any minor versions of protocol 5 to follow 10 | // should copy this file and modify the copy while maintaing backwards 11 | // compatibility. Breaking changes, if any are required, will come 12 | // in a subsequent major version with its own separate proto definition. 13 | // 14 | // Note that only the proto files included in a release tag of Terraform are 15 | // official protocol releases. Proto files taken from other commits may include 16 | // incomplete changes or features that did not make it into a final release. 17 | // In all reasonable cases, plugin developers should take the proto file from 18 | // the tag of the most recent release of Terraform, and not from the master 19 | // branch or any other development branch. 20 | // 21 | syntax = "proto3"; 22 | option go_package = "github.com/hashicorp/terraform/internal/tfplugin5"; 23 | 24 | package tfplugin5; 25 | 26 | // DynamicValue is an opaque encoding of terraform data, with the field name 27 | // indicating the encoding scheme used. 28 | message DynamicValue { 29 | bytes msgpack = 1; 30 | bytes json = 2; 31 | } 32 | 33 | message Diagnostic { 34 | enum Severity { 35 | INVALID = 0; 36 | ERROR = 1; 37 | WARNING = 2; 38 | } 39 | Severity severity = 1; 40 | string summary = 2; 41 | string detail = 3; 42 | AttributePath attribute = 4; 43 | } 44 | 45 | message AttributePath { 46 | message Step { 47 | oneof selector { 48 | // Set "attribute_name" to represent looking up an attribute 49 | // in the current object value. 50 | string attribute_name = 1; 51 | // Set "element_key_*" to represent looking up an element in 52 | // an indexable collection type. 53 | string element_key_string = 2; 54 | int64 element_key_int = 3; 55 | } 56 | } 57 | repeated Step steps = 1; 58 | } 59 | 60 | message Stop { 61 | message Request { 62 | } 63 | message Response { 64 | string Error = 1; 65 | } 66 | } 67 | 68 | // RawState holds the stored state for a resource to be upgraded by the 69 | // provider. It can be in one of two formats, the current json encoded format 70 | // in bytes, or the legacy flatmap format as a map of strings. 71 | message RawState { 72 | bytes json = 1; 73 | map flatmap = 2; 74 | } 75 | 76 | enum StringKind { 77 | PLAIN = 0; 78 | MARKDOWN = 1; 79 | } 80 | 81 | // Schema is the configuration schema for a Resource, Provider, or Provisioner. 82 | message Schema { 83 | message Block { 84 | int64 version = 1; 85 | repeated Attribute attributes = 2; 86 | repeated NestedBlock block_types = 3; 87 | string description = 4; 88 | StringKind description_kind = 5; 89 | bool deprecated = 6; 90 | } 91 | 92 | message Attribute { 93 | string name = 1; 94 | bytes type = 2; 95 | string description = 3; 96 | bool required = 4; 97 | bool optional = 5; 98 | bool computed = 6; 99 | bool sensitive = 7; 100 | StringKind description_kind = 8; 101 | bool deprecated = 9; 102 | } 103 | 104 | message NestedBlock { 105 | enum NestingMode { 106 | INVALID = 0; 107 | SINGLE = 1; 108 | LIST = 2; 109 | SET = 3; 110 | MAP = 4; 111 | GROUP = 5; 112 | } 113 | 114 | string type_name = 1; 115 | Block block = 2; 116 | NestingMode nesting = 3; 117 | int64 min_items = 4; 118 | int64 max_items = 5; 119 | } 120 | 121 | // The version of the schema. 122 | // Schemas are versioned, so that providers can upgrade a saved resource 123 | // state when the schema is changed. 124 | int64 version = 1; 125 | 126 | // Block is the top level configuration block for this schema. 127 | Block block = 2; 128 | } 129 | 130 | service Provider { 131 | //////// Information about what a provider supports/expects 132 | rpc GetSchema(GetProviderSchema.Request) returns (GetProviderSchema.Response); 133 | rpc PrepareProviderConfig(PrepareProviderConfig.Request) returns (PrepareProviderConfig.Response); 134 | rpc ValidateResourceTypeConfig(ValidateResourceTypeConfig.Request) returns (ValidateResourceTypeConfig.Response); 135 | rpc ValidateDataSourceConfig(ValidateDataSourceConfig.Request) returns (ValidateDataSourceConfig.Response); 136 | rpc UpgradeResourceState(UpgradeResourceState.Request) returns (UpgradeResourceState.Response); 137 | 138 | //////// One-time initialization, called before other functions below 139 | rpc Configure(Configure.Request) returns (Configure.Response); 140 | 141 | //////// Managed Resource Lifecycle 142 | rpc ReadResource(ReadResource.Request) returns (ReadResource.Response); 143 | rpc PlanResourceChange(PlanResourceChange.Request) returns (PlanResourceChange.Response); 144 | rpc ApplyResourceChange(ApplyResourceChange.Request) returns (ApplyResourceChange.Response); 145 | rpc ImportResourceState(ImportResourceState.Request) returns (ImportResourceState.Response); 146 | 147 | rpc ReadDataSource(ReadDataSource.Request) returns (ReadDataSource.Response); 148 | 149 | //////// Graceful Shutdown 150 | rpc Stop(Stop.Request) returns (Stop.Response); 151 | } 152 | 153 | message GetProviderSchema { 154 | message Request { 155 | } 156 | message Response { 157 | Schema provider = 1; 158 | map resource_schemas = 2; 159 | map data_source_schemas = 3; 160 | repeated Diagnostic diagnostics = 4; 161 | Schema provider_meta = 5; 162 | } 163 | } 164 | 165 | message PrepareProviderConfig { 166 | message Request { 167 | DynamicValue config = 1; 168 | } 169 | message Response { 170 | DynamicValue prepared_config = 1; 171 | repeated Diagnostic diagnostics = 2; 172 | } 173 | } 174 | 175 | message UpgradeResourceState { 176 | message Request { 177 | string type_name = 1; 178 | 179 | // version is the schema_version number recorded in the state file 180 | int64 version = 2; 181 | 182 | // raw_state is the raw states as stored for the resource. Core does 183 | // not have access to the schema of prior_version, so it's the 184 | // provider's responsibility to interpret this value using the 185 | // appropriate older schema. The raw_state will be the json encoded 186 | // state, or a legacy flat-mapped format. 187 | RawState raw_state = 3; 188 | } 189 | message Response { 190 | // new_state is a msgpack-encoded data structure that, when interpreted with 191 | // the _current_ schema for this resource type, is functionally equivalent to 192 | // that which was given in prior_state_raw. 193 | DynamicValue upgraded_state = 1; 194 | 195 | // diagnostics describes any errors encountered during migration that could not 196 | // be safely resolved, and warnings about any possibly-risky assumptions made 197 | // in the upgrade process. 198 | repeated Diagnostic diagnostics = 2; 199 | } 200 | } 201 | 202 | message ValidateResourceTypeConfig { 203 | message Request { 204 | string type_name = 1; 205 | DynamicValue config = 2; 206 | } 207 | message Response { 208 | repeated Diagnostic diagnostics = 1; 209 | } 210 | } 211 | 212 | message ValidateDataSourceConfig { 213 | message Request { 214 | string type_name = 1; 215 | DynamicValue config = 2; 216 | } 217 | message Response { 218 | repeated Diagnostic diagnostics = 1; 219 | } 220 | } 221 | 222 | message Configure { 223 | message Request { 224 | string terraform_version = 1; 225 | DynamicValue config = 2; 226 | } 227 | message Response { 228 | repeated Diagnostic diagnostics = 1; 229 | } 230 | } 231 | 232 | message ReadResource { 233 | message Request { 234 | string type_name = 1; 235 | DynamicValue current_state = 2; 236 | bytes private = 3; 237 | DynamicValue provider_meta = 4; 238 | } 239 | message Response { 240 | DynamicValue new_state = 1; 241 | repeated Diagnostic diagnostics = 2; 242 | bytes private = 3; 243 | } 244 | } 245 | 246 | message PlanResourceChange { 247 | message Request { 248 | string type_name = 1; 249 | DynamicValue prior_state = 2; 250 | DynamicValue proposed_new_state = 3; 251 | DynamicValue config = 4; 252 | bytes prior_private = 5; 253 | DynamicValue provider_meta = 6; 254 | } 255 | 256 | message Response { 257 | DynamicValue planned_state = 1; 258 | repeated AttributePath requires_replace = 2; 259 | bytes planned_private = 3; 260 | repeated Diagnostic diagnostics = 4; 261 | 262 | 263 | // This may be set only by the helper/schema "SDK" in the main Terraform 264 | // repository, to request that Terraform Core >=0.12 permit additional 265 | // inconsistencies that can result from the legacy SDK type system 266 | // and its imprecise mapping to the >=0.12 type system. 267 | // The change in behavior implied by this flag makes sense only for the 268 | // specific details of the legacy SDK type system, and are not a general 269 | // mechanism to avoid proper type handling in providers. 270 | // 271 | // ==== DO NOT USE THIS ==== 272 | // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== 273 | // ==== DO NOT USE THIS ==== 274 | bool legacy_type_system = 5; 275 | } 276 | } 277 | 278 | message ApplyResourceChange { 279 | message Request { 280 | string type_name = 1; 281 | DynamicValue prior_state = 2; 282 | DynamicValue planned_state = 3; 283 | DynamicValue config = 4; 284 | bytes planned_private = 5; 285 | DynamicValue provider_meta = 6; 286 | } 287 | message Response { 288 | DynamicValue new_state = 1; 289 | bytes private = 2; 290 | repeated Diagnostic diagnostics = 3; 291 | 292 | // This may be set only by the helper/schema "SDK" in the main Terraform 293 | // repository, to request that Terraform Core >=0.12 permit additional 294 | // inconsistencies that can result from the legacy SDK type system 295 | // and its imprecise mapping to the >=0.12 type system. 296 | // The change in behavior implied by this flag makes sense only for the 297 | // specific details of the legacy SDK type system, and are not a general 298 | // mechanism to avoid proper type handling in providers. 299 | // 300 | // ==== DO NOT USE THIS ==== 301 | // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== 302 | // ==== DO NOT USE THIS ==== 303 | bool legacy_type_system = 4; 304 | } 305 | } 306 | 307 | message ImportResourceState { 308 | message Request { 309 | string type_name = 1; 310 | string id = 2; 311 | } 312 | 313 | message ImportedResource { 314 | string type_name = 1; 315 | DynamicValue state = 2; 316 | bytes private = 3; 317 | } 318 | 319 | message Response { 320 | repeated ImportedResource imported_resources = 1; 321 | repeated Diagnostic diagnostics = 2; 322 | } 323 | } 324 | 325 | message ReadDataSource { 326 | message Request { 327 | string type_name = 1; 328 | DynamicValue config = 2; 329 | DynamicValue provider_meta = 3; 330 | } 331 | message Response { 332 | DynamicValue state = 1; 333 | repeated Diagnostic diagnostics = 2; 334 | } 335 | } 336 | 337 | service Provisioner { 338 | rpc GetSchema(GetProvisionerSchema.Request) returns (GetProvisionerSchema.Response); 339 | rpc ValidateProvisionerConfig(ValidateProvisionerConfig.Request) returns (ValidateProvisionerConfig.Response); 340 | rpc ProvisionResource(ProvisionResource.Request) returns (stream ProvisionResource.Response); 341 | rpc Stop(Stop.Request) returns (Stop.Response); 342 | } 343 | 344 | message GetProvisionerSchema { 345 | message Request { 346 | } 347 | message Response { 348 | Schema provisioner = 1; 349 | repeated Diagnostic diagnostics = 2; 350 | } 351 | } 352 | 353 | message ValidateProvisionerConfig { 354 | message Request { 355 | DynamicValue config = 1; 356 | } 357 | message Response { 358 | repeated Diagnostic diagnostics = 1; 359 | } 360 | } 361 | 362 | message ProvisionResource { 363 | message Request { 364 | DynamicValue config = 1; 365 | DynamicValue connection = 2; 366 | } 367 | message Response { 368 | string output = 1; 369 | repeated Diagnostic diagnostics = 2; 370 | } 371 | } 372 | --------------------------------------------------------------------------------