📗
smiley book
  • Smiley Books
  • AI
    • Readme
    • openai-whisper
      • 샘플 실행해보기
      • GPU 서버 준비하기
      • API로 whisper를 외부에 오픈하기
      • 프롬프트 지원
      • 실시간 message chat
      • 화면 이쁘게 만들기와 로그인
      • 파이썬 가상환경
      • 실시간 voice chat
      • fine tunning(미세 조정) 으로 성능 올리기
      • app에서 api를 호출하여 실시간으로 텍스트로 바꿔보기
    • ollama - llm을 쉽게 내컴에서 실행
      • ollama webui
      • ollama docker
    • stable diffusion
      • SDXL - text to image
      • SD-webui
    • ChatGPT
      • 답변이 끊길때
      • 역할을 정하자
      • 구체적인 질문
      • 결과형태를 지정
      • 프롬프트를 여러줄로 사용하자.
      • 마틴 파울러 글 번역본
    • Prompt Engineering
    • Auto-GPT
    • Gemini
      • google ai studio
      • gemini-api
      • embedding guide
    • Huggingface
      • huggingface 사용법
      • huggingface nlp 공부중
    • kaggle
      • download dataset
    • langchain
      • langchain을 공부하며 정리
      • basic
      • slackbot
      • rag
      • document-loader
      • website-loader
      • confluence
      • memory
      • function-call
      • langsmith
      • agent-toolkit
  • Ansible
    • templates vs files and jinja2
    • dynamic inventory
    • limit 옵션 강제하기
    • limit 사용후 gather_fact 문제
  • AWS
    • AWS CLI
    • EKS
      • cluster manage
      • ALB Controller
      • external-dns
      • fargate
    • ECR
    • S3
    • Certificate Manager
  • Azure
    • Azure AD OAuth Client Flow
  • Container
    • Registry
    • 빌드시에 env값 설정하기
  • DB
    • PXC
      • Operator
      • PMM
      • 삭제
      • GTID
      • Cross Site Replication
    • Mssql
    • Mysql
  • dotnet
    • Thread Pool
    • Connection Pool
    • Thread Pool2
  • Devops
    • Recommendation
  • GIT
    • Basic
    • Submodule
  • GitHub
    • Repository
    • GitHub Action
    • GitHub PR
    • Self Hosted Runner
    • GitHub Webhook
  • GitLab
    • CI/CD
    • CI/CD Advance
    • Ssl renew
    • CI/CD Pass env to other job
  • Go Lang
    • 개발 환경 구축
    • multi os binary build
    • kubectl같은 cli만들기
    • azure ad cli
    • embed static file
    • go study
      • pointer
      • module and package
      • string
      • struct
      • goroutine
  • Kubernetes
    • Kubernetes는 무엇인가
    • Tools
    • Install with kubespray
    • Kubernetes hardening guidance
    • 11 ways not to get hacked
    • ArgoCD
      • Install
      • CLI
      • Repository
      • Apps
      • AWS ALB 사용
      • Notification slack
      • Backup / DR
      • Ingress
      • 2021-11-16 Github error
      • Server Config
      • auth0 인증 추가(oauth,OIDC)
    • Extension
      • Longhorn pvc
      • External dns
      • Ingress nginx
      • Cert Manager
      • Kube prometheus
    • Helm
      • Subchart
      • Tip
    • Loki
    • Persistent Volume
    • TIP
      • Job
      • Pod
      • Log
  • KAFKA
    • raft
  • KVM
    • kvm cpu model
  • Linux
    • DNS Bind9
      • Cert-Manager
      • Certbot
      • Dynamic Update
      • Log
    • Export and variable
    • Grep 사용법
  • Modeling
    • C4 model introduce
    • Mermaid
    • reference
  • Monitoring
    • Readme
    • 0. What is Monitoring
    • 1. install prometheus and grafana
    • 2. grafana provisioning
    • 3. grafana dashboard
    • 4. grafana portable dashboard
    • 5. prometheus ui
    • 6. prometheus oauth2
    • Prometheus
      • Metric type
      • basic
      • rate vs irate
      • k8s-prometheus
    • Grafana
      • Expolorer
    • Node Exporter
      • advance
      • textfile collector
  • Motivation
    • 3 Simple Rule
  • OPENNEBULA
    • Install(ansible)
    • Install
    • Tip
    • Windows vm
  • Reading
    • comfort zone
    • 배려
    • elon musk 6 rule for insane productivity
    • Feynman Technique
    • how to interview - elon musk
    • 경청
    • Readme
  • Redis
    • Install
    • Master-slave Architecture
    • Sentinel
    • Redis Cluster
    • Client programming c#
  • SEO
    • Readme
  • Security
    • criminalip.io
      • criminalip.io
  • Stock
    • robinhood-python
  • Terraform
    • moved block
    • output
  • vault
    • Readme
  • VS Code
    • dev container
    • dev container on remote server
  • Old fashione trend
    • curity
    • MAAS
      • Install maas
      • Manage maas
      • Tip
Powered by GitBook
On this page
  • github
  • 사용 패키지
  • cobra
  • viper
  • use cobra
  • cli 명령어 스타일
  • add resource issue
  • 아규먼트 받기, 아규먼트 필수 처리
  • config
  • username/password를 프로젝트 바깥에 저장
  • 환경 변수를 이용해서 처리
  • 주의
  • todo

Was this helpful?

  1. Go Lang

kubectl같은 cli만들기

Previousmulti os binary buildNextazure ad cli

Last updated 1 year ago

Was this helpful?

github

사용 패키지

cobra

cli만드는데 사용

viper

설정을 저장하는데 사용

use cobra

go install github.com/spf13/cobra-cli@latest
mkdir ~/Desktop/mycli
cd ~/Desktop/mycli

cobra-cli init -h

cobra-cli init --viper

cobra-cli add ping

cli 명령어 스타일

이렇게 만들면 다음처럼 생성이 된다.

mycli ping

그런데 kubectl edit xxx 스타일로 만들고 싶다.

cobra-cli add create
cobra-cli add get
cobra-cli add edit
cobra-cli add delete

폴더를 생성하자.

package name change

package create
package get
package edit
package delete

update root.go

import

import (
 "fmt"
 "mycli/cmd/create"
 "mycli/cmd/delete"
 "mycli/cmd/edit"
 "mycli/cmd/get"
)

update createCmd to CreateCmd (소문자는 private 대문자는 public)

rootCmd.AddCommand(create.CreateCmd)
rootCmd.AddCommand(get.GetCmd)
rootCmd.AddCommand(edit.EditCmd)
rootCmd.AddCommand(delete.DeleteCmd)

실행

go build
./mycli
./mycli create

add resource issue

다음을 crud에 추가한다.

cmd.Help()
fmt.Println("create called")
cobra-cli add issue

move file under get folder and update package name to get

update code

// fmt.Println("issue called")
fmt.Println("get issue called")

// rootCmd.AddCommand(issueCmd)
GetCmd.AddCommand(issueCmd)

나머지 3개 파일도 복사해서 넣자.

테스트

아규먼트 받기, 아규먼트 필수 처리

create-issue에 다음을 추가

var (
 Summary     string
 Description string
)

func init() {
 CreateCmd.AddCommand(issueCmd)

 CreateCmd.Flags().StringVarP(&Summary, "summary", "s", "", "a summary of ticket")
 CreateCmd.Flags().StringVarP(&Description, "description", "d", "", "a description of ticket")

 if err := CreateCmd.MarkFlagRequired("summary"); err != nil {
  fmt.Println(err)
 }
 if err := CreateCmd.MarkFlagRequired("description"); err != nil {
  fmt.Println(err)
 }
}

config

username/password를 프로젝트 바깥에 저장

viper를 사용한다.

// initConfig reads in config file and ENV variables if set.
func initConfig() {
 if cfgFile != "" {
  // Use config file from the flag.
  viper.SetConfigFile(cfgFile)
 } else {
  // Find home directory.
  home, err := os.UserHomeDir()
  cobra.CheckErr(err)

  // Search config in home directory with name ".mycli" (without extension).
  viper.AddConfigPath(home)
  viper.SetConfigType("yaml")
  viper.SetConfigName(".mycli")
 }
  viper.AutomaticEnv() // read in environment variables that match

 // If a config file is found, read it in.
 if err := viper.ReadInConfig(); err == nil {
  fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
 }

이 코드가 벌써 root.go에 들어가 있다.

루트 디렉토리에서 .mycli.yaml 파일을 찾아서 읽어온다.

일단 저장을 해보자.

cobra-cli add configure

configure폴더를 만든후 파일을 이동해준다.

패키지 이름 configure 로 수정하고 아규컨트 추가 한다.

var (
 JIRA_USERNAME string
 JIRA_TOKEN    string
)

// ConfigureCmd represents the configure command
var ConfigureCmd = &cobra.Command{
 Use:   "configure",
 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("configure called")

  viper.Set("JIRA_USERNAME", JIRA_USERNAME)
  viper.Set("JIRA_TOKEN", JIRA_TOKEN)

  error := viper.SafeWriteConfig()
  if error != nil {
   fmt.Println(error)
  }

 },
}

func init() {
 ConfigureCmd.Flags().StringVarP(&JIRA_USERNAME, "jira-username", "u", "", "jira username")
 ConfigureCmd.Flags().StringVarP(&JIRA_TOKEN, "jira-token", "t", "", "jira token")
 if err := ConfigureCmd.MarkFlagRequired("jira-username"); err != nil {
  fmt.Println(err)
 }
 if err := ConfigureCmd.MarkFlagRequired("jira-token"); err != nil {
  fmt.Println(err)
 }
}

ConfigureCmd 로 대문자로 수정

아규먼트를 받아서 viper에 set하면 끝 그리고 SafeWriteConfig로 저장한다.

argument를 위해서 init함수를 수정하였다.

실행하고 설정을 저장해보자.

myctl configure --jira-username aaa --jira-token xxxx

# cat ~/.mycli.env
JIRA_USERNAME=xxx
JIRA_TOKEN=xxx

이제 읽어와서 사용해보자.

cmd/get/issue.go 에서 수정한다.

Run: func(cmd *cobra.Command, args []string) {
 cmd.Help()
 fmt.Println("get issue called")
 // add
 fmt.Println(viper.GetString("JIRA_USERNAME"))
 fmt.Println(viper.GetString("JIRA_TOKEN"))
},

두줄을 추가하고 실행해보자.

go run main.go get issue

> get issue called
> aaa
> xxx

환경 변수를 이용해서 처리

설정파일이 아니고 환경 변수를 이용해서 처리해보자.

일단 설정파일을 지운다.

rm ~/.mycli.env
cat ~/.mycli.env
> cat: /Users/ragon/.mycli.env: No such file or directory

테스트 하자.

go run main.go get issue
#아무것도 출력되지 않는다.

환경변수를 설정한다.

export JIRA_USERNAME=aaa
export JIRA_TOKEN=xxxx

실행해보자.

go run main.go get issue

출력됨을 알수 있다.

주의

환경변수를 사용할때 소문자를 키값으로 사용하면 동작하지 않는다.

# 동작
export JIRA_USERNAME=aaa
export JIRA_TOKEN=xxxx
# 동작 안됨
export jira_username=aaa
export jira_token=xxxx

왜 이러는지 아시는분....

todo

  • resource file(json 또는 이미지 또는 다른 파일)을 읽어와서 처리하는 방법을 알아보자.

  • resource file을 배포할때 어떻게 해야하는지 모르겟다.

https://github.com/teamsmiley/go-cobra-viper-boilerplate
https://github.com/spf13/cobra
https://github.com/spf13/viper