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

4

1 回答 1

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

于 2019-04-16T11:32:13.277 回答