如何使用bash使用预定义的键值运行CONSUL(agent -dev)

时间:2019-04-15 11:58:59

标签: bash startup consul consul-kv

我需要使用

启动本地领事(https://www.consul.io/
consul agent -dev

但是默认情况下,此本地领事必须具有一些键/值。 我想有一种使用REST API的方法...有人可以向我解释吗?

关于, 尼古拉斯

1 个答案:

答案 0 :(得分:0)

这是我基于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

关于, 尼古拉斯