1

I need to start local consul (https://www.consul.io/) using

consul agent -dev

But by default, this local consul must have some key/value existing. I guess there is a way to do that using REST API... Can someone explain to me?

Regards, Nicolas

NicoESIEA
  • 499
  • 1
  • 6
  • 23
  • I will investigate using HTTP Rest API: https://www.consul.io/api/index.html – NicoESIEA Apr 16 '19 at 07:38
  • When you start Consul, it's LV store will be empty. To set up some key-values, you will need either to use REST API or you can also use `consul kv` CLI command (https://www.consul.io/docs/commands/kv.html). `consul kv put test/foo bar` will place value `bar` into path `test/foo`. Whejn running locally you don't need to set `CONSUL_HTTP_ADDR` or `CONSUL_HTTP_TOKEN`, but when running in production with CL enabled, make sure you have these variables exported. – bagljas Apr 16 '19 at 08:28

1 Answers1

2

Here is the script I did base on HTTP Rest API

#!/bin/bash

echo "********* **************** ************"
echo "********* RUN LOCAL CONSUL ************"
echo "********* **************** ************"

# OVERRIDEN VALUES
LOCAL_CONSUL_PATH="." # example: C:\consul_1.4.2_windows_amd64
LOCAL_CONSUL_PORT=8500
LOCAL_ENV="http://localhost:5002" # example: http://localhost:5002

MASTER_TOKEN="no-need-when-for-local-consul-agent"
TOKEN=$MASTER_TOKEN
consulPath="http://localhost:8500"

function run(){
  killConsul
  startConsul
  createKey "sample4unittest" "consul";
  createKey "unittest/sample" "consul";
  createKey "_global/Environment" $LOCAL_ENV;
}

function killConsul(){
  echo "*** killConsul..."
  port=$1
  if [[ -z "$port" ]]; then port=$LOCAL_CONSUL_PORT; fi
  echo $"   KILL CONSUL port[${port}]"
  PID=`netstat -a -o -n  | grep 127.0.0.1:${port} | grep LISTENING | cut -d ' ' -f37-`
  echo $"   Local consul listening PID[${PID}]"
  if [[ ! -z "$PID" ]]; then taskkill -F -PID $PID; fi
  echo "*** killConsul finished"
}

function startConsul(){
  echo "*** startConsul..."
  cd $LOCAL_CONSUL_PATH
  ./consul agent -dev &
  echo "*** startConsul finished"
}

function delete(){
  keyName=$1
  curl -k -H $"X-Consul-Token: ${TOKEN}" \
    --request DELETE \
    $"${consulPath}/v1/kv/${keyName}"
}

function createKey(){
  keyName=$1
  value=$2
  echo "*** Start CreateKey: key[${keyName}] value[${value}]"
  echo "--- DELETE the potential existing key "
  delete $"${keyName}"

  curl -k -H $"X-Consul-Token: ${TOKEN}" \
     --request PUT \
     --data $"${value}" \
     $"${consulPath}/v1/kv/${keyName}"
  echo "*** done"
}

run

Regards, Nicolas

NicoESIEA
  • 499
  • 1
  • 6
  • 23