리눅스
HashiCorp Consul KV 사용하는 방법
변군이글루
2023. 2. 14. 16:10
반응형
HashiCorp Consul KV 사용하는 방법(CLI · REST API · consul-template)
Consul은 단순 Key-Value 저장소 이상의 기능을 제공하지만 그중 가장 기본이자 많이 사용되는 기능이 바로 KV(Key-Value) Store입니다.
consul 사용법
consul kv
더보기
---
Usage: consul kv <subcommand> [options] [args]
This command has subcommands for interacting with Consul's key-value
store. Here are some simple examples, and more detailed examples are
available in the subcommands or the documentation.
Create or update the key named "redis/config/connections" with the value "5":
$ consul kv put redis/config/connections 5
Read this value back:
$ consul kv get redis/config/connections
Or get detailed key information:
$ consul kv get -detailed redis/config/connections
Finally, delete the key:
$ consul kv delete redis/config/connections
For more examples, ask for subcommand help or view the documentation.
Subcommands:
delete Removes data from the KV store
export Exports a tree from the KV store as JSON
get Retrieves or lists data from the KV store
import Imports a tree stored as JSON to the KV store
put Sets or updates data in the KV store
---
1. Consul KV 기본 사용법 (CLI)
데이터 추가(키 생성)
consul kv put web/server/config/webserv1-hostname webserv1
Success! Data written to: web/server/config/webserv1-hostname
consul kv put web/server/config/webserv1-ip 1.1.1.1
Success! Data written to: web/server/config/webserv1-ip
데이터 조회(키 읽기)
consul kv get web/server/config/webserv1-hostname
webserv1
consul kv get web/server/config/webserv1-ip
1.1.1.1
데이터 삭제(키 삭제)
consul kv delete web/server/config/webserv1-hostname
Success! Deleted key: web/server/config/webserv1-hostname
consul kv delete web/server/config/webserv1-ip
Success! Deleted key: web/server/config/webserv1-ip
2. Consul REST API 사용하기
CLI 대신 REST API로도 동일한 기능을 수행할 수 있습니다.
먼저 Consul Client의 실제 접속 IP를 환경 변수로 설정합니다.
export CONSUL_CLIENT_ADDRESS=`ip route get 1.2.3.4 | awk '{ print $7 }' | egrep -v '^$'`
echo $CONSUL_CLIENT_ADDRESS
데이터 저장(PUT)
curl --request PUT --data 'active' http://${CONSUL_CLIENT_ADDRESS}:8500/v1/kv/redis/state
true
데이터 조회(GET)
curl -s http://${CONSUL_CLIENT_ADDRESS}:8500/v1/kv/redis/state | jq
[
{
"LockIndex": 0,
"Key": "redis/state",
"Flags": 0,
"Value": "YWN0aXZl",
"CreateIndex": 74042,
"ModifyIndex": 74042
}
]
- Value는 Base64 인코딩된 문자열입니다.
데이터 삭제(DELETE)
curl -XDELETE http://${CONSUL_CLIENT_ADDRESS}:8500/v1/kv/redis/state
true
3. consul-template로 KV 기반 템플릿 렌더링
Consul KV의 변경 사항을 감지해 파일을 자동 생성하거나 업데이트할 수 있는 강력한 도구가 바로 consul-template입니다.
템플릿 파일 생성(in.tpl 파일)
vim in.tpl
{{ key "foo" }}
consul-template 실행
consul-template -template "in.tpl:out.txt" -once
터미널 하나를 더 띄워 Consul KV에 값을 넣습니다.
consul kv put foo bar
Success! Data written to: foo
결과 출력 확인
cat out.txt
bar
- Consul KV의 값이 템플릿에 자동 반영되어 out.txt 파일에 출력됩니다.
Consul KV를 활용한 기본적인 설정 관리부터, REST API 연동, 템플릿 자동화까지 모두 손쉽게 사용할 수 있습니다.
728x90
반응형