Comments (5)
I got this to work by adding this to appsettings.json:
"AppSettings": {
"PortNumber": 5000,
"DebugMode": true
}
Then this for Programs.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using TerraformPluginDotNet.ResourceProvider;
namespace TerraformPluginDotNet
{
public class Program
{
public static X509Certificate2 Cert { get; private set; }
public static void Run(string[] args, Action<IServiceCollection, TerraformConstructRegistry> configure)
{
Cert = CertificateGenerator.GenerateSelfSignedCertificate("CN=127.0.0.1", "CN=root ca", CertificateGenerator.GeneratePrivateKey());
var appSettings = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(appSettings)
.CreateLogger();
try
{
CreateHostBuilder(args, appSettings, configure).Build().Run();
}
catch (Exception ex)
{
Log.Logger.Fatal(ex, "Fatal error occurred.");
Environment.Exit(1);
}
finally
{
Log.Logger.Information("Application terminated.");
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args, IConfiguration appSettings, Action<IServiceCollection, TerraformConstructRegistry> configure) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseConfiguration(appSettings)
.ConfigureKestrel(x =>
{
int portNumber = appSettings.GetValue<int>("AppSettings:PortNumber");
bool debugMode = appSettings.GetValue<bool>("AppSettings:DebugMode");
// HTTP2.0 required for Terraform 1.0
x.ConfigureEndpointDefaults(lo => lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2);
if (debugMode)
{
x.ListenLocalhost(portNumber);
}
else
{
x.ListenLocalhost(portNumber, x => x.UseHttps(x =>
{
x.ServerCertificate = Cert;
x.AllowAnyClientCertificate();
}));
}
})
.UseStartup<Startup>()
.ConfigureLogging((_, x) => x.ClearProviders().AddSerilog())
.ConfigureServices(services =>
{
var registry = new TerraformConstructRegistry();
services.AddSingleton(registry);
configure(services, registry);
});
});
}
}
And this for Startup.cs:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TerraformPluginDotNet.DataSourceProvider;
using TerraformPluginDotNet.ResourceProvider;
using TerraformPluginDotNet.Serialization;
using TerraformPluginDotNet.Services;
namespace TerraformPluginDotNet
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddTransient(typeof(DataSourceProviderHost<>));
services.AddTransient(typeof(ResourceProviderHost<>));
services.AddTransient(typeof(IResourceUpgrader<>), typeof(DefaultResourceUpgrader<>));
services.AddTransient<IDynamicValueSerializer, DefaultDynamicValueSerializer>();
}
public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IWebHostEnvironment env, ILogger<Startup> logger)
{
lifetime.ApplicationStarted.Register(() =>
{
logger.LogInformation("Application started.");
string endPoint = $"127.0.0.1:{Configuration.GetValue<int>("AppSettings:PortNumber")}";
if (Configuration.GetValue<bool>("AppSettings:DebugMode"))
{
// Need this info so we can connect Terraform in debugging mode
Console.WriteLine("Provider started, to attach Terraform set the TF_REATTACH_PROVIDERS env var:\n\n");
Console.WriteLine($"SET TF_REATTACH_PROVIDERS={{\"mywebsite.com/mysubdir/terraformdeploy\":{{\"Protocol\":\"grpc\",\"Pid\":{Process.GetCurrentProcess().Id},\"Test\":true,\"Addr\":{{\"Network\":\"tcp\",\"String\":\"{endPoint}\"}}}}}}");
}
else
{
Console.WriteLine($"1|5|tcp|{endPoint}|grpc|{Convert.ToBase64String(Program.Cert.RawData)}");
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<Terraform5ProviderService>();
endpoints.MapGet("/", async context =>
{
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");
});
});
}
}
}
from terraformplugindotnet.
When the provider starts up in debug mode, it echoes something like:
Provider started, to attach Terraform set the TF_REATTACH_PROVIDERS env var:
SET TF_REATTACH_PROVIDERS={"mywebsite.com/mysubdir/terraformdeploy":{"Protocol":"grpc","Pid":68092,"Test":true,"Addr":{"Network":"tcp","String":"127.0.0.1:5000"}}}
This is Windows specific. First copy and paste the 'SET ...' command into a command prompt. Then you need to make sure your provider is set up correctly. If your script looks like this:
terraform {
required_providers {
fusiondeploy = {
source = "mywebsite.com/mysubdir/terraformdeploy"
version = "1.0.0"
}
}
}
Then, to avoid needing a Terraform registry, start in the same folder as your Terraform scripts and copy your provider to the following location:
mywebsite.com\mysubdir\terraformdeploy\1.0.0\windows_amd64\myprovider.exe
Since you're debugging, the executable won't be used, but just needs to be present. You should be able to run Terraform from the script directory now and set breakpoints in Visual Studio. If you stop debugging, remember to paste the new 'SET...' statement back into the command line when you start debugging again.
TOP TIP: Set all log settings to Debug and look in log.txt. This is how I found out that debugging doesn't require https, but does require http 2.0 at least for Terraform 1.0.
from terraformplugindotnet.
Thanks, this looks like a useful tip. I got debugging working by running this project in Visual Studio as normal, and having a separate executable in the Terraform provider directory that just outputs the connection details to the instance being run by Visual Studio.
from terraformplugindotnet.
I have added support for TF_REATTACH_PROVIDERS
and some tests that make use of it. Please see the updated README for details.
from terraformplugindotnet.
Nice addition 🙂 And thanks again - this was a really useful head start for me
from terraformplugindotnet.
Related Issues (9)
- Create NuGet package HOT 2
- Getting this to work in Windows HOT 2
- Can't parse `public_dns` as list<string>
- GetProviderSchema Error
- KeyAttribute has to match property name HOT 1
- PseudoDynamic.Terraform.Toolset HOT 3
- Error when trying to create a Type of Object or map or list in Terraform HOT 2
- Inconsistencies with computed values
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from terraformplugindotnet.