当前位置:网站首页>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
边栏推荐
- 数据库超话(四)
- 大厂们终于无法忍受“加一秒”了,微软谷歌Meta等公司提议废除闰秒
- Kubernetes第七篇:使用kubernetes部署prometheus+grafana监控系统(Kubernetes工作实践类)
- MySQL: 函数
- 密集光流提取dense_flow理解
- Design details of hidden iframe and form elements used by SAP ui5 fileuploader
- 后台管理系统 权限设置大致流程
- 小于n的最大数
- 技术实践干货 | 从工作流到工作流
- Coca Cola's primary challenge is not vitality forest
猜你喜欢

Xcode releases test package testflight

Following the example of IE, is the decline of Firefox inevitable?

神经网络实现手写数字分类matlab

一文理解分布式开发中的服务治理

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细

Understand the basic properties of BOM and DOM

20 years ago, he was Ma Yun's biggest enemy

About paths mapping in SAP ui5 application ui5.yaml

微软默默给 curl 捐赠一万美元,半年后才通知

Shell programming specifications and variables
随机推荐
High cost, difficult to implement, slow to take effect, what about open source security?
选择体育场馆的LED显示屏时应该注重哪些方面
奇瑞欧萌达也太像长安UNI-T了,但长得像,产品力就像吗?
密集光流提取dense_flow理解
WebView basic use
Swift QQ授权登录 坑集
Hegong sky team vision training Day8 - vision, target recognition
Understand the basic properties of BOM and DOM
SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细
Hidden iframe design details of SAP ui5 fileuploader
动作捕捉系统用于柔性机械臂的末端定位控制
Reference of meta data placeholder
helm安装kubevela完整Makefile脚本内容
Gradient ring progress bar
写好技术原创文章的一点建议
URL return nil and urlhash processing
Lichuang EDA - PCB layout (IV)
(2)融合cbam的two-stream项目搭建----数据准备
详解二叉树之堆
Select structure