[root@dhcp-10-201-102-248 ~]# consul usage: consul [--version] [--help] <command> [<args>] Available commands are: agent Runs a Consul agent configtest Validate config file event Fire a new event exec Executes a command on Consul nodes force-leave Forces a member of the cluster to enter the "left" state info Provides debugging information for operators join Tell Consul agent to join cluster keygen Generates a new encryption key keyring Manages gossip layer encryption keys kv Interact with the key-value store leave Gracefully leaves the Consul cluster and shuts down lock Execute a command holding a lock maint Controls node or service maintenance mode members Lists the members of a Consul cluster monitor Stream logs from a Consul agent operator Provides cluster-level tools for Consul operators reload Triggers the agent to reload configuration files rtt Estimates network round trip time between nodes snapshot Saves, restores and inspects snapshots of Consul server state version Prints the Consul version watch Watch for changes in Consul123456789101112131415161718192021222324
如果你得到一个consul not be found的错误,你的PATH可能没有正确设置.请返回检查你的consul的安装路径是否包含在PATH中.
[root@dhcp-10-201-102-198 ~]# consul members Node Address Status Type Build Protocol DC s1 10.201.102.198:8301 alive server 0.7.4 2 dc1 s2 10.201.102.199:8301 alive server 0.7.4 2 dc1 s3 10.201.102.200:8301 alive server 0.7.4 2 dc112345
启动 Consul Client
1
consul agent -data-dir /tmp/consul -node=c1 -bind=10.201.102.248 -config-dir=/etc/consul.d/ -join 10.201.102.1981
[root@dhcp-10-201-102-248 ~]# consul members Node Address Status Type Build Protocol DC c1 10.201.102.248:8301 alive client 0.7.4 2 dc1 s1 10.201.102.198:8301 alive server 0.7.4 2 dc1 s2 10.201.102.199:8301 alive server 0.7.4 2 dc1 s3 10.201.102.200:8301 alive server 0.7.4 2 dc1123456
加入集群
1 2 3 4 5 6
[root@dhcp-10-201-102-248 ~]# consul join 10.201.102.198 Node Address Status Type Build Protocol DC c1 10.201.102.248:8301 alive client 0.7.4 2 dc1 s1 10.201.102.198:8301 alive server 0.7.4 2 dc1 s2 10.201.102.199:8301 alive server 0.7.4 2 dc1 s3 10.201.102.200:8301 alive server 0.7.4 2 dc1123456
[root@dhcp-10-201-102-198 ~]# consul usage: consul [--version] [--help] <command> [<args>] Available commands are: agent Runs a Consul agent 运行一个consul agent configtest Validate config file event Fire a new event exec Executes a command on Consul nodes 在consul节点上执行一个命令 force-leave Forces a member of the cluster to enter the "left" state 强制节点成员在集群中的状态转换到left状态 info Provides debugging information for operators 提供操作的debug级别的信息 join Tell Consul agent to join cluster 加入consul节点到集群中 keygen Generates a new encryption key 生成一个新的加密key keyring Manages gossip layer encryption keys kv Interact with the key-value store leave Gracefully leaves the Consul cluster and shuts down lock Execute a command holding a lock maint Controls node or service maintenance mode members Lists the members of a Consul cluster 列出集群中成员 monitor Stream logs from a Consul agent 打印consul节点的日志信息 operator Provides cluster-level tools for Consul operators reload Triggers the agent to reload configuration files 触发节点重新加载配置文件 rtt Estimates network round trip time between nodes snapshot Saves, restores and inspects snapshots of Consul server state version Prints the Consul version 打印consul的版本信息 watch Watch for changes in Consul 监控consul的改变123456789101112131415161718192021222324
==> Usage: consul agent [options] Starts the Consul agent and runs until an interrupt is received. The agent represents a single node in a cluster. Options: -advertise=addr Sets the advertise address to use -advertise-wan=addr Sets address to advertise on wan instead of advertise addr -bootstrap Sets server to bootstrap mode -bind=0.0.0.0 Sets the bind address for cluster communication -http-port=8500 Sets the HTTP API port to listen on -bootstrap-expect=0 Sets server to expect bootstrap mode. -client=127.0.0.1 Sets the address to bind for client access. This includes RPC, DNS, HTTP and HTTPS (if configured) -config-file=foo Path to a JSON file to read configuration from. This can be specified multiple times. -config-dir=foo Path to a directory to read configuration files from. This will read every file ending in ".json" as configuration in this directory in alphabetical order. This can be specified multiple times. -data-dir=path Path to a data directory to store agent state -dev Starts the agent in development mode. -recursor=1.2.3.4 Address of an upstream DNS server. Can be specified multiple times. -dc=east-aws Datacenter of the agent (deprecated: use 'datacenter' instead). -datacenter=east-aws Datacenter of the agent. -encrypt=key Provides the gossip encryption key -join=1.2.3.4 Address of an agent to join at start time. Can be specified multiple times. -join-wan=1.2.3.4 Address of an agent to join -wan at start time. Can be specified multiple times. -retry-join=1.2.3.4 Address of an agent to join at start time with retries enabled. Can be specified multiple times. -retry-interval=30s Time to wait between join attempts. -retry-max=0 Maximum number of join attempts. Defaults to 0, which will retry indefinitely. -retry-join-ec2-region EC2 Region to use for discovering servers to join. -retry-join-ec2-tag-key EC2 tag key to filter on for server discovery -retry-join-ec2-tag-value EC2 tag value to filter on for server discovery -retry-join-gce-project-name Google Compute Engine project to discover servers in -retry-join-gce-zone-pattern Google Compute Engine region or zone to discover servers in (regex pattern) -retry-join-gce-tag-value Google Compute Engine tag value to filter for server discovery -retry-join-gce-credentials-file Path to credentials JSON file to use with Google Compute Engine -retry-join-wan=1.2.3.4 Address of an agent to join -wan at start time with retries enabled. Can be specified multiple times. -retry-interval-wan=30s Time to wait between join -wan attempts. -retry-max-wan=0 Maximum number of join -wan attempts. Defaults to 0, which will retry indefinitely. -log-level=info Log level of the agent. -node=hostname Name of this node. Must be unique in the cluster -node-meta=key:value An arbitrary metadata key/value pair for this node. This can be specified multiple times. -protocol=N Sets the protocol version. Defaults to latest. -rejoin Ignores a previous leave and attempts to rejoin the cluster. -server Switches agent to server mode. -syslog Enables logging to syslog -ui Enables the built-in static web UI server -ui-dir=path Path to directory containing the Web UI resources -pid-file=path Path to file to store agent PID123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
/v1/catalog/register : Registers a new node, service, or check /v1/catalog/deregister : Deregisters a node, service, or check /v1/catalog/datacenters : Lists known datacenters /v1/catalog/nodes : Lists nodes in a given DC /v1/catalog/services : Lists services in a given DC /v1/catalog/service/<service> : Lists the nodes in a given service /v1/catalog/node/<node> : Lists the services provided by a node1234567
/v1/session/create: Creates a new session /v1/session/destroy/<session>: Destroys a given session /v1/session/info/<session>: Queries a given session /v1/session/node/<node>: Lists sessions belonging to a node /v1/session/list: Lists all the active sessions12345
acl
acl endpoints用来create、update、destory、query acl
1 2 3 4 5 6
/v1/acl/create: Creates a new token with policy /v1/acl/update: Update the policy of a token /v1/acl/destroy/<id>: Destroys a given token /v1/acl/info/<id>: Queries the policy of a given token /v1/acl/clone/<id>: Creates a new token by cloning an existing token /v1/acl/list: Lists all the active tokens123456
#### 配置文件 ```Consul-Template```配置文件是使用[HashiCorp Configuration Language (HCL)](https://github.com/hashicorp/hcl)编写的.这意味着```Consul Template```是和JSON兼容的,查看更多信息请查看 [HCL 规范](https://github.com/hashicorp/hcl) 配置文件语法支持上面的所有的选项,除非在表格中进行标明. ```json // 这是要连接的Consul Agent的地址.默认为127.0.0.1:8500.这是Consul的默认绑定地址和端口. // 不建议你直接与 Consul的 Server直接进行交互,请与本地的Consul Agent进行交互.这样做是有一些原因 // 最重要的是本地agent可以复用与server的连接.减少HTTP的连接数.另外这个地址更好记. consul = "127.0.0.1:8500" // 这是用于连接Consul的ACL token. 如果你的集群未启用就不需要设置. // // 这个选项也可以通过环境变量 CONSUL_TOKEN 来进行设置 token = "abcd1234" // 这是监听出发reload事件的信号,默认值如下所示.将这个值设置为空将引起 CT ,从而不监听reload事件 reload_signal = "SIGHUP" // 这是监听出发core dump事件的信号,默认值如下所示.将这个值设置为空将引起 CT ,从而不监听core dump信号 dump_signal = "SIGQUIT" // 这是监听出发graceful stop事件的信号,默认值如下所示.将这个值设置为空将引起 CT ,从而不监听graceful stop信号 kill_signal = "SIGINT" // 这是连接Consul的重试时间.Consul Template是高容错的设计.这意味着,出现失败他不会退出.而按照 // 分布式系统的惯例进行指数补偿和重试来等待集群恢复. retry = "10s" // This is the maximum interval to allow "stale" data. By default, only the // Consul leader will respond to queries; any requests to a follower will // forward to the leader. In large clusters with many requests, this is not as // scalable, so this option allows any follower to respond to a query, so long // as the last-replicated data is within these bounds. Higher values result in // less cluster load, but are more likely to have outdated data. // 这是允许陈旧数据的最大时间.Consul默认只有领袖对请求进行相应.所有对追随者的请求将被转发给领袖. // 在有大量请求的大型集群中,这显得不够有扩展性.所以这个选项允许任何追随者响应查询,只要最后复制的数据 // 在这个范围内.数值越高,越减少集群负载,但是更容易接受到过期数据. max_stale = "10m" // 这是log的等级,如果你找到了bug,请打开debug 日志,这样我们可以更好的定位问题.这个选项也可用在命令行. log_level = "warn" // 这是存放Consul Template 进程的PID文件的路径,如果你计划发送定制的信号到这个进程这会比较有用. pid_file = "/path/to/pid" // 这是一个静止定时器,他定义了在模板渲染之前等待集群达到一致状态的最小和最大时间. // 这对于一些变化较大的系统中比较有用,可以减少模板渲染的次数 wait = "5s:10s" // 这是 Vault配置的开始 // Vault是HashiCorp的另外一个产品 vault { // This is the address of the Vault leader. The protocol (http(s)) portion // of the address is required. address = "https://vault.service.consul:8200" // This is the token to use when communicating with the Vault server. // Like other tools that integrate with Vault, Consul Template makes the // assumption that you provide it with a Vault token; it does not have the // incorporated logic to generate tokens via Vault's auth methods. // // This value can also be specified via the environment variable VAULT_TOKEN. token = "abcd1234" // This option tells Consul Template to automatically renew the Vault token // given. If you are unfamiliar with Vault's architecture, Vault requires // tokens be renewed at some regular interval or they will be revoked. Consul // Template will automatically renew the token at half the lease duration of // the token. The default value is true, but this option can be disabled if // you want to renew the Vault token using an out-of-band process. // // Note that secrets specified in a template (using {{secret}} for example) // are always renewed, even if this option is set to false. This option only // applies to the top-level Vault token itself. renew = true // This section details the SSL options for connecting to the Vault server. // Please see the SSL options below for more information (they are the same). ssl { // ... } } // 这部分配置请求的基本的权限验证信息 auth { enabled = true username = "test" password = "test" } // 这部分配置连接到Consul服务器的SSL信息. ssl { // 使用SSL需要先打开这个开关 enabled = true // This enables SSL peer verification. The default value is "true", which // will check the global CA chain to make sure the given certificates are // valid. If you are using a self-signed certificate that you have not added // to the CA chain, you may want to disable SSL verification. However, please // understand this is a potential security vulnerability. verify = false // This is the path to the certificate to use to authenticate. If just a // certificate is provided, it is assumed to contain both the certificate and // the key to convert to an X509 certificate. If both the certificate and // key are specified, Consul Template will automatically combine them into an // X509 certificate for you. cert = "/path/to/client/cert" key = "/path/to/client/key" // This is the path to the certificate authority to use as a CA. This is // useful for self-signed certificates or for organizations using their own // internal certificate authority. ca_cert = "/path/to/ca" } // 设置连接到syslog服务器的配置 // 用于进行日志记录syslog { // 打开开关 enabled = true // 设备名称 facility = "LOCAL5" } // This block defines the configuration for de-duplication mode. Please see the // de-duplication mode documentation later in the README for more information // on how de-duplication mode operates. deduplicate { // This enables de-duplication mode. Specifying any other options also enables // de-duplication mode. enabled = true // This is the prefix to the path in Consul's KV store where de-duplication // templates will be pre-rendered and stored. prefix = "consul-template/dedup/" } // This block defines the configuration for exec mode. Please see the exec mode // documentation at the bottom of this README for more information on how exec // mode operates and the caveats of this mode. exec { // This is the command to exec as a child process. There can be only one // command per Consul Template process. command = "/usr/bin/app" // This is a random splay to wait before killing the command. The default // value is 0 (no wait), but large clusters should consider setting a splay // value to prevent all child processes from reloading at the same time when // data changes occur. When this value is set to non-zero, Consul Template // will wait a random period of time up to the splay value before reloading // or killing the child process. This can be used to prevent the thundering // herd problem on applications that do not gracefully reload. splay = "5s" // This defines the signal that will be sent to the child process when a // change occurs in a watched template. The signal will only be sent after // the process is started, and the process will only be started after all // dependent templates have been rendered at least once. The default value // is "" (empty or nil), which tells Consul Template to restart the child // process instead of sending it a signal. This is useful for legacy // applications or applications that cannot properly reload their // configuration without a full reload. reload_signal = "SIGUSR1" // This defines the signal sent to the child process when Consul Template is // gracefully shutting down. The application should begin a graceful cleanup. // If the application does not terminate before the `kill_timeout`, it will // be terminated (effectively "kill -9"). The default value is "SIGTERM". kill_signal = "SIGINT" // This defines the amount of time to wait for the child process to gracefully // terminate when Consul Template exits. After this specified time, the child // process will be force-killed (effectively "kill -9"). The default value is // "30s". kill_timeout = "2s" } // 这部分定义了对模板的配置,和其他配置块不同.这部分可以针对不同模板配置多次.也可以在CLI命令 // 直接进行配置 template { // 这是输入模板的配置文件路径,必选项 source = "/path/on/disk/to/template.ctmpl" // 这是源模板渲染之后存放的路径,如果父目录不存在Consul Template会尝试进行创建 destination = "/path/on/disk/where/template/will/render.txt" // This is the optional command to run when the template is rendered. The // command will only run if the resulting template changes. The command must // return within 30s (configurable), and it must have a successful exit code. // Consul Template is not a replacement for a process monitor or init system. // 这是当模板渲染完成后可选的要执行的命令.这个命令只会在模板发生改变后才会运行.这个命令必须要在30秒 // 内进行返回(可配置),必须返回一个成功的退出码.Consul Template不能替代进程监视或者init 系统 // 的功能 command = "restart service foo" // 这是最大的等待命令返回的时间,默认是30秒 command_timeout = "60s" // 这是渲染后的文件的权限,如果不设置,Consul Template将去匹配之前已经存在的文件的权限. // 如果文件不存在,权限会被设置为 0644 perms = 0600 // 这个选项对渲染之前的文件进行备份.他保持一个备份. // 这个选项在发生意外更高时,有一个回滚策略. backup = true // 模板的分隔符,默认是 "{{"和"}}".但是对于一些模板用其他的分隔符可能更好 // 可以避免与本身的冲突 left_delimiter = "{{" right_delimiter = "}}" // 这是最小和最大等待渲染一个新模板和执行命令的时间.使用 分号 个号.如果忽略最大值,最大 // 值会被设置为最小值的4倍.这个选项没有默认值.这个值相对全局所以的等待时间有最高优先级 wait = "2s:6s" }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
LeaseID - the unique lease identifier LeaseDuration - the number of seconds the lease is valid Renewable - if the secret is renewable Data - the raw data - this is a map[string]interface{}, so it can be queried using Go's templating "dot notation" If the map key has dots "." in it, you need to access the value using the index function: {{index .Data "my.key.with.dots"}} If additional arguments are passed to the function, then the operation is assumed to be a write operation instead of a read operation. The write operation must return data in order to be valid. This is especially useful for the PKI secret backend, for example. {{ with secret "pki/issue/my-domain-dot-com" "common_name=foo.example.com" }} {{ .Data.certificate }} {{ end }} The parameters must be key=value pairs, and each pair must be its own argument to the function: {{ secret "path/" "a=b" "c=d" "e=f" }} Please always consider the security implications of having the contents of a secret in plain-text on disk. If an attacker is able to get access to the file, they will have access to plain-text secrets.12345678910111213
Please note that Vault does not support blocking queries. As a result, Consul Template will not immediately reload in the event a secret is changed as it does with Consul’s key-value store. Consul Template will fetch a new secret at half the lease duration of the original secret. For example, most items in Vault’s generic secret backend have a default 30 day lease. This means Consul Template will renew the secret every 15 days. As such, it is recommended that a smaller lease duration be used when generating the initial secret to force Consul Template to renew more often.
secrets Query Vault to list the secrets at the given path. Please note this requires Vault 0.5+ and the endpoint you want to list secrets must support listing. Not all endpoints support listing. The result is the list of secret names as strings.
1
{{range secrets "secret/"}}{{.}}{{end}}1
The trailing slash is optional in the template, but the generated secret dependency will always have a trailing slash in log output.
To iterate and list over every secret in the generic secret backend in Vault, for example, you would need to do something like this:
You should probably never do this. Please also note that Vault does not support blocking queries. To understand the implications, please read the note at the end of the secret function.
#!/bin/sh set -e consul maint -enable -service web -reason "Consul Template updated" service nginx reload consul maint -disable -service web12345
另外如果你没有安装Consul agent,你可以直接调用API请求:
1 2 3 4 5
#!/bin/sh set -e curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=true&reason=Consul+Template+Updated" service nginx reload curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=false"12345