当前位置:网站首页>Introduction to cue language foundation: cue is a language born for configuration
Introduction to cue language foundation: cue is a language born for configuration
2022-07-27 17:37:00 【Learn programming notes】
Basic introduction
Start with this part , We will introduce KubeVela How is it based on CUE To realize abstract and extended . This section will mainly introduce some CUE Basic knowledge of , If you are right about KubeVela Of The core concept It doesn't matter if you don't understand , For those who want to know quickly CUE And do some practical readers , This section also applies .
summary
KubeVela take CUE As the core dependency and extension mode of application delivery, the reasons are as follows ::
- CUE It is designed for large-scale configuration . CUE Be able to perceive very complex configuration files , And it can safely change the values of thousands of objects in the modifiable configuration . It's very consistent KubeVela The goal of , That is, in a programmable way , To define and deliver production level applications .
- CUE Support first-class code generation and Automation . CUE Native support integrates with existing tools and workflows , In contrast, other tools need to customize complex solutions to achieve . for example , It needs to be used manually Go Code generation OpenAPI Pattern .KubeVela Is also dependent on CUE This feature builds development tools and GUI Interface .
- CUE And Go Perfect integration . KubeVela image Kubernetes Most projects in the system use the same GO Development .CUE Already in Go And provides rich API.KubeVela With CUE For the core implementation Kubernetes controller . With the help of CUE,KubeVela Data constraints can be easily handled .
See more details The Configuration Complexity Curse as well as The Logic of CUE Two articles .
Premise
Please make sure that the following command line is installed in your environment :
cuev0.2.2 at present KubeVela Only for now CUE v0.2.2 edition , Support for new... Will be upgraded in subsequent iterations CUE edition .vela>= v1.1.0.
Study CUE Command line
CUE yes JSON Superset , We can use it like JSON The use of CUE, And has the following characteristics :
- C Notes on language style
- Field names can be enclosed in double quotation marks , Note that the field name cannot contain special characters
- Whether there is a comma at the end of the optional field
- Allow comma at the end of the last element in the array
- Outer braces are optional
Please copy the following information first , Save as a first.cue file :
a: 1.5
a: float
b: 1
b: int
d: [1, 2, 3]
g: {
h: "abc"
}
e: string
Next , Let's take the above file as an example , To learn CUE Command line related instructions :
How to format CUE file .( If you use Goland Or something like that JetBrains IDE, You can refer to this article to configure the automatic formatting plug-in Use Goland Set up cuelang Automatic formatting of .)
This command can not only format CUE file , It can also prompt the wrong model , Quite easy to use commands .
cue fmt first.cueHow to verify the model . except
cue fmt, You can still use itcue vetTo verify the model .$ cue vet first.cue some instances are incomplete; use the -c flag to show errors or suppress this message $ cue vet first.cue -c e: incomplete value stringPrompt us : In this document e This variable , There are data types
stringBut there is no assignment .How to calculate / Render the result .
cue evalYou can calculate CUE File and render the final result . We see that the final result does not includea: floatandb: int, This is because these two variables have been calculated and filled . amonge: stringNot explicitly assigned , Therefore, it remains unchanged .$ cue eval first.cue a: 1.5 b: 1 d: [1, 2, 3] g: { h: "abc" } e: stringHow to specify the result of rendering . for example , We just want to know in the document
bThe rendering result of , You can use this parameter-e.$ cue eval -e b first.cue 1How to export rendering results .
cue exportYou can export the final rendering results . If some variables are not defined, executing this command will report an error .$ cue export first.cue e: incomplete value stringLet's update
first.cuefile , toeassignment :a: 1.5 a: float b: 1 b: int d: [1, 2, 3] g: { h: "abc" } e: string e: "abc"then , This command can work normally . By default , The rendered result will be formatted as JSON Format .
$ cue export first.cue { "a": 1.5, "b": 1, "d": [ 1, 2, 3 ], "g": { "h": "abc" }, "e": "abc" }How to export YAML Render results in format .
$ cue export first.cue --out yaml a: 1.5 b: 1 d: - 1 - 2 - 3 g: h: abc e: abcHow to export the results of specified variables .
$ cue export -e g first.cue { "h": "abc" }
above , You have learned all the commonly used CUE Command line instructions .
Study CUE Language
After getting familiar with common CUE After the command line instruction , Let's learn more CUE Language .
First understand CUE Data type of . The following are its basic data types :
// float
a: 1.5
// int
b: 1
// string
c: "blahblahblah"
// array
d: [1, 2, 3, 1, 2, 3, 1, 2, 3]
// bool
e: true
// struct
f: {
a: 1.5
b: 1
d: [1, 2, 3, 1, 2, 3, 1, 2, 3]
g: {
h: "abc"
}
}
// null
j: null
How to customize CUE type ? Use # Symbols to specify some representations CUE Variable of type .
#abc: string
We save the above content to second.cue file . perform cue export Not to report #abc Is a value with incomplete type .
$ cue export second.cue
{
}
You can also define more complex custom structures , such as :
#abc: {
x: int
y: string
z: {
a: float
b: bool
}
}
Custom structure in KubeVela Is widely used in module definition (X-Definitions) And verify .
Define a CUE Templates
below , We began to try to use the knowledge we just learned , To define CUE Template .
- Define structure variables
parameter.
parameter: {
name: string
image: string
}
Save the above variables to a file deployment.cue.
- Define more complex structural variables
templateAlso reference variablesparameter.
template: {
apiVersion: "apps/v1"
kind: "Deployment"
spec: {
selector: matchLabels: {
"app.oam.dev/component": parameter.name
}
template: {
metadata: labels: {
"app.oam.dev/component": parameter.name
}
spec: {
containers: [{
name: parameter.name
image: parameter.image
}]
}}}
}
be familiar with Kubernetes You may already know , This is a Kubernetes Deployment The template of . parameter Is the parameter part of the template .
Add the above content to the file deployment.cue.
- And then , We complete the variable assignment by updating the following :
parameter:{
name: "mytest"
image: "nginx:v1"
}
- Last , The export rendering result is YAML Format :
$ cue export deployment.cue -e template --out yaml
apiVersion: apps/v1
kind: Deployment
spec:
selector:
matchLabels:
app.oam.dev/component: mytest
template:
metadata:
labels:
app.oam.dev/component: mytest
spec:
containers:
- name: mytest
image: nginx:v1
above , You get a Kubernetes Deployment Template of type .
CUE More use of
Design open structures and arrays . If used in arrays or structures
..., It means that the object is open .Array objects
[...string], It indicates that the object can accommodate multiple string elements . If you do not add..., This object[string]Note the array can only hold one typestringThe elements of .The structure description shown below can contain unknown fields .
{ abc: string ... }
Use the operator
|To represent two types of values . As shown below , VariableaThe representation type can be string or integer .
a: string | int
- Using symbols
*Define the default value of the variable . Usually it is associated with symbols|In combination with , Represents a certain type of default value . As shown below , VariableaThe type isint, The default value is1.
a: *1 | int
- Let some variables be filled . In some cases , Some variables are not necessarily used , These variables are optional variables , We can use
?:Define such variables . As shown below ,aIs an optional variable , Customize#myIn the objectxandzIs an optional variable , andyIs a required field .
a ?: int
#my: {
x ?: string
y : int
z ?:float
}
Optional variables can be skipped , This is often used in conjunction with conditional judgment logic . say concretely , If some fields do not exist , be CUE The grammar is if _variable_!= _ | _ , As shown below :
parameter: {
name: string
image: string
config?: [...#Config]
}
output: {
...
spec: {
containers: [{
name: parameter.name
image: parameter.image
if parameter.config != _|_ {
config: parameter.config
}
}]
}
...
}
- Use the operator
&To operate on two variables .
a: *1 | int
b: 3
c: a & b
Save the above contents to third.cue file .
You can use cue eval To verify the results :
$ cue eval third.cue
a: 1
b: 3
c: 3
- You need to perform conditional judgment . When you perform some cascading operations , Different values will affect different results , Conditional judgment is very useful . therefore , You can execute in the template
if..elseThe logic of .
price: number
feel: *"good" | string
// Feel bad if price is too high
if price > 100 {
feel: "bad"
}
price: 200
Save the above contents to fourth.cue file .
You can use cue eval To verify the results :
$ cue eval fourth.cue
price: 200
feel: "bad"
Another example is taking Boolean types as parameters .
parameter: {
name: string
image: string
useENV: bool
}
output: {
...
spec: {
containers: [{
name: parameter.name
image: parameter.image
if parameter.useENV == true {
env: [{name: "my-env", value: "my-value"}]
}
}]
}
...
}
Use For loop . In order to avoid duplication of code , Often used For loop .
Map traversal .
parameter: { name: string image: string env: [string]: string } output: { spec: { containers: [{ name: parameter.name image: parameter.image env: [ for k, v in parameter.env { name: k value: v }, ] }] } }Type traversal .
#a: { "hello": "Barcelona" "nihao": "Shanghai" } for k, v in #a { "\(k)": { nameLen: len(v) value: v } }Slice traversal .
parameter: { name: string image: string env: [...{name:string,value:string}] } output: { ... spec: { containers: [{ name: parameter.name image: parameter.image env: [ for _, v in parameter.env { name: v.name value: v.value }, ] }] } }- Use condition judgment in the cycle
parameter: [ { name: "empty" }, { name: "xx1" }, ] dataFrom: [ for _, v in parameter { if v.name != "empty" { name: v.name } }]The result is :
cue eval ../blog/a.cue -e dataFrom [{}, { name: "xx1" }]- Take the condition judgment as the condition of the cycle
parameter: [ { name: "empty" }, { name: "xx1" }, ]
dataFrom: [ for _, v in parameter if v.name != “empty” { name: v.name }]
The result is :cue eval …/blog/a.cue -e dataFrom [{ name: “xx1” }]
in addition , have access to "\( _my-statement_ )" Perform string internal calculation , For example, in the above type loop example , Get the length of the value and other operations .
Import CUE Interior Package
CUE There's a lot of internal packages Can be KubeVela Use , This can meet more development needs .
such as , Use strings.Join Method to splice a string array into a string .
import ("strings")
parameter: {
outputs: [{ip: "1.1.1.1", hostname: "xxx.com"}, {ip: "2.2.2.2", hostname: "yyy.com"}]
}
output: {
spec: {
if len(parameter.outputs) > 0 {
_x: [ for _, v in parameter.outputs {
"\(v.ip) \(v.hostname)"
}]
message: "Visiting URL: " + strings.Join(_x, "")
}
}
}
thus , You have learned the basics CUE knowledge , If you want to know more CUE Practical details , You can refer to its Official documents .
In the following chapters of this part , We will begin to introduce KubeVela How to use CUE Connect different resources like glue , Please make sure you are right KubeVela Of The core concept Know something about .
Reference link :
http://static.kubevela.net/zh/docs/platform-engineers/cue/basic
边栏推荐
- Three table joint query 1
- Reference of meta data placeholder
- 数据库超话(四)
- App crash collection and analysis
- High precision timer
- 二舅的外甥和他的学生们
- About paths mapping in SAP ui5 application ui5.yaml
- Oracle-Linux-7.9是否能支持Oracle-19c的ACFS文件系统?
- Start from scratch blazor server (1) -- project construction
- The chess robot broke the finger of a 7-year-old boy. Netizen: it violated the first law of robots
猜你喜欢

Global string object (function type) +math object

【obs】NewSocketLoopEnable 网络优化

Kubernetes第七篇:使用kubernetes部署prometheus+grafana监控系统(Kubernetes工作实践类)

Explain the idempotence of distributed system in detail

Smart fish tank design based on stm32

Chery omenda is also too similar to Chang'an uni-t, but does it look like it? Is the product power like it?

动作捕捉系统用于柔性机械臂的末端定位控制

20年前,他是马云最大的敌人

Coca Cola's primary challenge is not vitality forest

The 7-year-old boy broke his finger by AI robot just because he played chess too fast?
随机推荐
Two table joint query 1
Built in object (bottom)
交换机和路由器技术-03-交换机基本配置
立创EDA——原理图的布局与检查(三)
Redis: 配置AOF不起作用
Kubernetes Chapter 8: deploy NFS system with kubernetes to complete database persistence (kubernetes work practice class)
国产新冠口服药为什么是治艾滋病的药
$attrs and $listeners components transfer values
Maximum number less than n
这种精度高,消耗资源少的大模型稀疏训练方法被阿里云科学家找到了!已被收录到IJCAI
What are VO, do, dto and Po
Bit band operation of semaphore protection
大厂们终于无法忍受“加一秒”了,微软谷歌Meta等公司提议废除闰秒
2021-06-18 automatic assembly error in SSM project
第7天总结&作业
腾讯云上传使用
动作捕捉系统用于柔性机械臂的末端定位控制
Gods at dusk, "cat trembles" bid farewell to the big V Era
With the arrival of large displacement hard core products, can the tank brand break through the ceiling of its own brand?
Tencent cloud upload