23.06.15
DEVOTEE를 활성화 시키면
지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.
버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.
| 컨텐츠 유형 | 제목 | 저장일 | 삭제 |
|---|
본인인증 로그인에 실패하였습니다.
회원이 아니시거나 본인인증 등록이
완료되지 않은 사용자입니다.
현대사회에서 대부분의 유저들은 휴대폰이나 컴퓨터 화면을 통해 쉽고 편한 GUI(Graphic User Interface)를 선호합니다.
그러나 GUI로는 채우기 힘든 여전히 CLI(Command Line Interface)를 선호하는 분야도 많습니다. 특히 CI/CD 파이프라인,
정기적인 스케쥴링 Job, GUI로는 하기 힘든 자동화 작업의 경우 여전히 CLI가 막강한 힘을 발휘합니다.
이 글에서는 팀에서 쿠버네티스 서비스(TKS)의 CLI를 만들면서 사용한 Cobra에 대해 소개하고, 사용방법에 대해 알아보려합니다.
Cobra는 golang의 CLI 라이브러리 중 하나로 상당히 많은 레퍼런스를 갖고 있습니다. 그 중에는 쿠버네티스를 사용할 때 항상
실행하는 kubectl도 있습니다. 명령어 밑에 서브 명령어를 포함하는 형태를 지원하기 때문에 하나의 CLI에서 많은 기능을 포함할
경우 유용합니다. 아래는 cobra의 특징입니다.
아래처럼 cobra패키지를 다운받으면, cobra CLI와 라이브러리를 사용할 수 있습니다.
$ go get -u github.com/spf13/cobra
import "github.com/spf13/cobra"
Cobra를 설치하면 cobra cli를 실행할 수 있습니다.
$ cobra
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
cobra [command]
Available Commands:
add Add a command to a Cobra Application
completion generate the autocompletion script for the specified shell
help Help about any command
init Initialize a Cobra Application
Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml)
-h, --help help for cobra
-l, --license string name of license for the project
--viper use Viper for configuration (default true)
Use "cobra [command] --help" for more information about a command.
이 CLI에서 제공하는 init과 add 명령어를 통해 간단하게 CLI를 만들 수 있습니다.
cobra init은 처음 CLI를 만들 때 필요한 패키지 이름과 라이센스를 지정합니다.
$ cobra init -h
Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.
* If a name is provided, a directory with that name will be created in the current directory;
* If no name is provided, the current directory will be assumed;
Usage:
cobra init [name] [flags]
Aliases:
init, initialize, initialise, create
Flags:
-h, --help help for init
--pkg-name string fully qualified pkg name
Global Flags:
-a, --author string author name for copyright attribution (default "YOUR NAME")
--config string config file (default is $HOME/.cobra.yaml)
-l, --license string name of license for the project
--viper use Viper for configuration (default true)
pkg-name은 cli의 패키지 이름으로 웹으로 접근 가능한 주소를 사용합니다. (ex: github.com/openinfradev/tks-client)
author와 license를 사용해 command 소스코드에 자동으로 라이센스와 제작자를 추가할 수 있습니다,
아래는 MIT라이센스에 제작자를 추가한 예시입니다.
$ cobra init tks --pkg-name github.com/openinfradev/tks-client -a "SK Telecom" -l MIT
Your Cobra application is ready at
/home/centos/workspace/Jaesang/tks
init에 사용한 license와 author정보는 앞으로 계속 적용이 될 것 같지만, 맨 처음 만들어지는 파일에만 적용될 뿐 새로 추가되는
명령어에는 적용되지 않습니다. 모든 명령어를 추가할 때마다 동일한 라이센스, 제작자를 추가하기 위해 yaml config를 사용할 수
있습니다. 다음과 같이 ~/.cobra.yaml 파일을 만들면, 모든 명령어에 동일한 라이센스와 제작자 정보가 추가됩니다. (지원하는 라이센스는
https://github.com/spf13/cobra/tree/master/cobra/cmd의 라이센스 파일을 참고)
author: SK Telecom
license: MIT
cobra init으로 패키지를 생성하면 아래아 같은 파일이 생깁니다.
$ cd tks
$ tree
.
├── LICENSE
├── cmd
│ └── root.go
└── main.go
1 directory, 3 files
모든 파일에는 init 때 사용한 MIT라이센스와 제작자 이름인 'SK Telecom'이 포함되어 있습니다.
$ cat main.go
/*
Copyright © 2021 SK Telecom
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package main
import "github.com/openinfradev/tks-client/cmd"
func main() {
cmd.Execute()
}
init을 하였으니, 이제 cobra add를 통해 명령어를 추가합니다.
cobra add는 cli에 명령어를 추가합니다. -p 옵션을 통해 서브 명령어도 쉽게 생성할 수 있습니다. -p 옵션의 인자에는 부모 명령어
뒤에 Cmd를 붙여줘야 제대로 인식합니다.(ex: testCmd)
아래 예제는 tks-client cli에 test 명령어를 생성하고, test 명령어의 서브 명령어로 list를 추가하는 방법을 보여주고 있습니다.
$ cobra add test
test created at /home/centos/workspace/Jaesang/tks
$ cobra add list -p testCmd
list created at /home/centos/workspace/Jaesang/tks
새로 추가된 명령어는 cmd 폴더에 소스코드로 확인할 수 있습니다.
├── LICENSE
├── cmd
│ ├── list.go
│ ├── root.go
│ └── test.go
└── main.go
이제 실행파일을 빌드하여 테스트를 할 수 있습니다. cobra add는 go.mod, go.sum파일을 만들어주진 않기 때문에, 따로 해당파일을 만들어줍니다.
$ go mod init github.com/openinfradev/tks-client
$ go mod tidy
$ go build
소스폴더에 tks-client 바이너리가 생성되었습니다.
├── LICENSE
├── cmd
│ ├── list.go
│ ├── root.go
│ └── test.go
├── go.mod
├── go.sum
├── main.go
└── tks-client
tks-client를 실행하면, 명령어 소개, 지원 명령어, 옵션 등이 표시됩니다.
$ ./tks-client
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
tks-client [command]
Available Commands:
completion generate the autocompletion script for the specified shell
help Help about any command
test A brief description of your command
Flags:
--config string config file (default is $HOME/.tks-client.yaml)
-h, --help help for tks-client
-t, --toggle Help message for toggle
Use "tks-client [command] --help" for more information about a command.
출력되는 형태가 cobra CLI와 매우 흡사합니다. CLI의 기본소개, 사용방법, 지원 명령어, 옵션 등의 순서로 표현이 됩니다. 여기서 사용되는 문구들은 모두 소스코드에서 확인할 수 있습니다. 이 의미는 이제부터 소스코드를 수정하여 원하는 cli를 만들면 된다는 것입니다. 소개문구를 변경하고, 필요한 옵션들을 추가하면서 CLI를 풍성하게 완성할 수 있습니다. cobra는 자동으로 생성되는 소스코드에 CLI에 필요한 추가 옵션, 도움말 부분, 코드 실행부분등을 상세히 설명하고 있기 때문에 어떤 부분을 어떻게 수정해야 할지 쉽게 파악할 수 있습니다.
cmd 폴더 밑에 한 파일을 열어보면 다음과 같습니다. &cobra.Command에서 명령어에 대한 소개, 실제 수행 코드부분을 작성하고, init()에서 지원할 옵션을 추가합니다.
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// showCmd represents the show command
var showCmd = &cobra.Command{
Use: "show",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("show called")
},
}
func init() {
testCmd.AddCommand(showCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// showCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// showCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
cobra를 사용해 cli를 만드는 것은 이것이 전부입니다. 템플릿을 자동 생성해주기 때문에 개발자는 CLI에 전체적인 구조를
생각한 뒤 그에 따라 cobra add만 해주면됩니다. 서브 명령어를 지원하기 때문에 무한한 확장이 가능합니다. 환경파일을
사용해 모든 명령어에 적용되는 전역변수를 만들 수도 있습니다. Man페이지, MarkDown파일 등 CLI의 도움말 파일도 생성할
수 있습니다. golang으로 프로젝트를 진행할 때 CLI에 대한 부분은 cobra로 쉽게 해결하시기 바랍니다. cobra에서 지원하는
더 다양한 기능은 유저가이드에서 확인하실 수 있습니다.
추천글:
DEVOTEE를 활성화 시키면
지금 작성한 댓글에 AI가 댓글을 달아줍니다.