I can initialise the Consul services at startup using the /consul/config directory. I would like to be able to initialise my application settings into the Consul kv store when I start the Consul container. Is this possible?
I wanted a simple approach to set application settings in Consul for a microservice project. I'm sure there are a number of existing tools but I wanted something that was lightweight and suits my development process. So rather than try to work with some of @mgyongyosi's suggestions I wrote a quick dotnet console application to do the (not so) heavy lifting. Under the project root directory I've created a directory structure Consul/kv
. The child directories under that path represent keys in the Consul KV store and a json
file at a leaf represents the application settings. Note there is only expected to be a single json
file per leaf directory. The application uses the Consul.NET nuget package for communicating with Consul.
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Consul;
namespace ConfigureConsulKv
{
class Program
{
private static readonly string _basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"Projects", "MyProject", "Consul", "kv");
static void Main(string[] args)
{
RecurseDirectory(_basePath);
}
static void RecurseDirectory(string path)
{
foreach (var dir in Directory.EnumerateDirectories(path)) RecurseDirectory(dir);
var file = Directory.EnumerateFiles(path, "*.json").FirstOrDefault();
if (!string.IsNullOrWhiteSpace(file))
{
var key = path.Substring(_basePath.Length + 1);
var json = File.ReadAllBytes(file);
Console.WriteLine($"key {key} file {file}");
using (var client = new ConsulClient())
{
var attempt = client.KV.Put(new KVPair(key) { Value = json }).Result;
Console.WriteLine($"status {attempt.StatusCode}");
}
}
}
}
}