Skip to content

Commit

Permalink
feat: support secret output for generate config
Browse files Browse the repository at this point in the history
  • Loading branch information
wtrocki committed Apr 26, 2022
1 parent bc159a9 commit f433b20
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 30 deletions.
5 changes: 3 additions & 2 deletions docs/commands/rhoas_generate-config.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -635,8 +635,6 @@ github.com/redhat-developer/app-services-sdk-go v0.10.0 h1:zI0X5FR0NOj6IwBWk3y1T
github.com/redhat-developer/app-services-sdk-go v0.10.0/go.mod h1:enn8Zz6IT0HZYzS6LSttiME2apwnvfVWZnGRS81A4rk=
github.com/redhat-developer/app-services-sdk-go/accountmgmt v0.1.0 h1:MOljVN8AKTM72Yed8ioAwhdW0KdWEhBZjjam3lY2lyY=
github.com/redhat-developer/app-services-sdk-go/accountmgmt v0.1.0/go.mod h1:0LX7ZCEmMKAbncO05/zRYsV0K5wsds7AGPpOFC7KWGo=
github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.4.1 h1:BuzYhAhO/jHi1R3eOpVoH7tSLvrlWR2s6lb/3m3pqZY=
github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.4.1/go.mod h1:nQK2LFPPaTR+R6dZKBqSpaLCHBOWWDIewhzFZcfUfrg=
github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.5.0 h1:cf+K96kW8o6v6JSzaGpQI5amEzSJuGrd5on3V+SmKhg=
github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.5.0/go.mod h1:JAedrXf/qLHd7lpOS+bOFh8nrOpp2j0sg4/VG/1um6c=
github.com/redhat-developer/app-services-sdk-go/kafkainstance v0.6.0 h1:ExEHQaihnPNxN2nKXB0q5nrmSv4p8b3Idzt7TChxv+Q=
Expand Down
10 changes: 7 additions & 3 deletions pkg/cmd/generate/build-configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ type configValues struct {
ClientID string
ClientSecret string
TokenURL string

// Optional
Name string
}

func createServiceAccount(opts *options, shortDescription string) (*kafkamgmtclient.ServiceAccount, error) {
Expand Down Expand Up @@ -92,8 +95,8 @@ func BuildConfiguration(svcConfig *servicecontext.ServiceConfig, opts *options)
if !serviceAvailable {
return opts.localizer.MustLocalizeError("generate.log.info.noSevices")
}

serviceAccount, err := createServiceAccount(opts, fmt.Sprintf("%s-%v", opts.name, time.Now().Unix()))
configInstanceName := fmt.Sprintf("%s-%v", opts.name, time.Now().Unix())
serviceAccount, err := createServiceAccount(opts, configInstanceName)
if err != nil {
return err
}
Expand All @@ -106,8 +109,9 @@ func BuildConfiguration(svcConfig *servicecontext.ServiceConfig, opts *options)
configurations.ClientID = serviceAccount.GetClientId()
configurations.ClientSecret = serviceAccount.GetClientSecret()
configurations.TokenURL = cfg.MasAuthURL + "/protocol/openid-connect/token"
configurations.Name = configInstanceName

if err = WriteConfig(opts.configType, configurations); err != nil {
if err = WriteConfig(opts.configType, opts.fileName, configurations); err != nil {
return err
}

Expand Down
21 changes: 14 additions & 7 deletions pkg/cmd/generate/configurations.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,21 @@ const (
envFormat = "env"
jsonFormat = "json"
propertiesFormat = "properties"
secretFormat = "secret"
)

var configurationTypes = []string{envFormat, jsonFormat, propertiesFormat}
var configurationTypes = []string{envFormat, jsonFormat, propertiesFormat, secretFormat}

var (
envConfig = template.Must(template.New(envFormat).Parse(templateEnv))
jsonConfig = template.Must(template.New(jsonFormat).Parse(templateJSON))
propertiesConfig = template.Must(template.New(propertiesFormat).Parse(templateProperties))
envConfig = template.Must(template.New(envFormat).Parse(templateEnv))
jsonConfig = template.Must(template.New(jsonFormat).Parse(templateJSON))
propertiesConfig = template.Must(template.New(propertiesFormat).Parse(templateProperties))
secretTemplateConfig = template.Must(template.New(secretFormat).Parse(templateSecret))
)

// WriteConfig saves the configurations to a file
// in the specified output format
func WriteConfig(configType string, config *configValues) error {
func WriteConfig(configType string, filePath string, config *configValues) error {

var fileBody bytes.Buffer
fileTemplate := getFileFormat(configType)
Expand All @@ -35,7 +37,9 @@ func WriteConfig(configType string, config *configValues) error {
}

fileData := []byte(fileBody.String())
filePath := getDefaultPath(configType)
if filePath == "" {
filePath = getDefaultPath(configType)
}

return ioutil.WriteFile(filePath, fileData, 0o600)
}
Expand All @@ -49,6 +53,8 @@ func getDefaultPath(configType string) (filePath string) {
filePath = "rhoas.properties"
case jsonFormat:
filePath = "rhoas.json"
case secretFormat:
filePath = "rhoas-services-secret.yaml"
}

pwd, err := os.Getwd()
Expand All @@ -62,14 +68,15 @@ func getDefaultPath(configType string) (filePath string) {
}

func getFileFormat(configType string) (template *template.Template) {

switch configType {
case envFormat:
template = envConfig
case propertiesFormat:
template = propertiesConfig
case jsonFormat:
template = jsonConfig
case secretFormat:
template = secretTemplateConfig
}

return template
Expand Down
3 changes: 2 additions & 1 deletion pkg/cmd/generate/generate-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type options struct {
ServiceContext servicecontext.IContext

name string
fileName string
configType string
}

Expand All @@ -47,7 +48,6 @@ func NewGenerateCommand(f *factory.Factory) *cobra.Command {
Example: f.Localizer.MustLocalize("generate.cmd.example"),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {

// check that a valid type is provided
validType := flagutil.IsValidInput(opts.configType, configurationTypes...)
if !validType {
Expand All @@ -61,6 +61,7 @@ func NewGenerateCommand(f *factory.Factory) *cobra.Command {
flags := contextcmdutil.NewFlagSet(cmd, f)
flags.AddContextName(&opts.name)
flags.StringVar(&opts.configType, "type", "", opts.localizer.MustLocalize("generate.flag.type"))
cmd.Flags().StringVar(&opts.fileName, "output-file", "", opts.localizer.MustLocalize("generate.common.flag.fileLocation.description"))
_ = cmd.MarkFlagRequired("type")

flagutil.EnableStaticFlagCompletion(cmd, "type", configurationTypes)
Expand Down
50 changes: 42 additions & 8 deletions pkg/cmd/generate/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@ package generate

import (
"github.com/MakeNowJust/heredoc"
"github.com/redhat-developer/app-services-cli/pkg/cmd/registry/registrycmdutil"
)

var (
templateEnv = heredoc.Doc(`
## Generated by rhoas generate-config
{{if .KafkaHost}}KAFKA_HOST={{.KafkaHost}}
{{end}}{{if .RegistryURL}}SERVICE_REGISTRY_URL={{.RegistryURL}}
{{end}}RHOAS_CLIENT_ID={{.ClientID}}
## Generated by rhoas cli
{{if .KafkaHost}}## Kafka Configuration
KAFKA_HOST={{.KafkaHost}}
{{end}}{{if .RegistryURL}}## Service Registry Configuration
SERVICE_REGISTRY_URL={{.RegistryURL}}
SERVICE_REGISTRY_CORE_PATH=` + registrycmdutil.REGISTRY_CORE_PATH + `
SERVICE_REGISTRY_COMPAT_PATH=` + registrycmdutil.REGISTRY_COMPAT_PATH + `
{{end}}
## Authentication Configuration
RHOAS_CLIENT_ID={{.ClientID}}
RHOAS_CLIENT_SECRET={{.ClientSecret}}
RHOAS_OAUTH_TOKEN_URL={{.TokenURL}}
`)
Expand All @@ -18,18 +25,45 @@ var (
{
{{if .KafkaHost}}"kafkaHost":"{{.KafkaHost}}",
{{end}}{{if .RegistryURL}}"serviceRegistryUrl":"{{.RegistryURL}}",
"serviceRegistryCorePath":"` + registrycmdutil.REGISTRY_CORE_PATH + `",
"serviceRegistryCompatPath":"` + registrycmdutil.REGISTRY_COMPAT_PATH + `",
{{end}}"rhoasClientID":"{{.ClientID}}",
"rhoasClientSecret":"{{.ClientSecret}}",
"rhoasOauthTokenUrl":"{{.TokenURL}}"
}
`)

templateProperties = heredoc.Doc(`
## Generated by rhoas generate-config
{{if .KafkaHost}}kafkaHost={{.KafkaHost}}
{{end}}{{if .RegistryURL}}serviceRegistryUrl={{.RegistryURL}}
{{end}}rhoasClientID={{.ClientID}}
## Generated by rhoas cli
{{if .KafkaHost}}## Kafka Configuration
kafkaHost={{.KafkaHost}}
{{end}}{{if .RegistryURL}} ## Service Registry Configuration
serviceRegistryUrl={{.RegistryURL}}
serviceRegistryCorePath=` + registrycmdutil.REGISTRY_CORE_PATH + `
serviceRegistryCompatPath=` + registrycmdutil.REGISTRY_COMPAT_PATH + `
{{end}}
## Authentication Configuration
rhoasClientID={{.ClientID}}
rhoasClientSecret={{.ClientSecret}}
rhoasOauthTokenUrl={{.TokenURL}}
`)

templateSecret = heredoc.Doc(`
apiVersion: v1
kind: Secret
metadata:
name: {{.Name}}
type: Opaque
stringData:
{{if .KafkaHost}}## Kafka Configuration
KAFKA_HOST: {{.KafkaHost}}{{end}}
{{if .RegistryURL}}## Service Registry Configuration
SERVICE_REGISTRY_URL: {{.RegistryURL}}
SERVICE_REGISTRY_CORE_PATH: ` + registrycmdutil.REGISTRY_CORE_PATH + `
SERVICE_REGISTRY_COMPAT_PATH: ` + registrycmdutil.REGISTRY_COMPAT_PATH + `
{{end}}
## Authentication Configuration
RHOAS_CLIENT_ID: {{.ClientID}}
RHOAS_CLIENT_SECRET: {{.ClientSecret}}
RHOAS_OAUTH_TOKEN_URL: {{.TokenURL}}`)
)
18 changes: 11 additions & 7 deletions pkg/cmd/registry/registrycmdutil/registry_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@ import (

var validNameRegexp = regexp.MustCompile(`^[a-z]([-a-z0-9]*[a-z0-9])?$`)

type compatibilityEndpoints struct {
// CompatibilityEndpoints - Service Registry API paths for various clients
type CompatibilityEndpoints struct {
CoreRegistry string `json:"coreRegistryAPI"`
SchemaRegistry string `json:"schemaRegistryCompatAPI"`
CncfSchemaRegistry string `json:"cncfSchemaRegistryAPI"`
}

const REGISTRY_CORE_PATH = "/apis/registry/v2"
const REGISTRY_COMPAT_PATH = "/apis/ccompat/v6"
const REGISTRY_CNCF_PATH = "/apis/cncf/v0"

// ValidateName validates the proposed name of a Kafka instance
func ValidateName(val interface{}) error {
name, ok := val.(string)
Expand All @@ -37,12 +42,11 @@ func ValidateName(val interface{}) error {
}

// GetCompatibilityEndpoints returns the compatible API endpoints
func GetCompatibilityEndpoints(url string) *compatibilityEndpoints {

endpoints := &compatibilityEndpoints{
CoreRegistry: url + "/apis/registry/v2",
SchemaRegistry: url + "/apis/ccompat/v6",
CncfSchemaRegistry: url + "/apis/cncf/v0",
func GetCompatibilityEndpoints(url string) *CompatibilityEndpoints {
endpoints := &CompatibilityEndpoints{
CoreRegistry: url + REGISTRY_CORE_PATH,
SchemaRegistry: url + REGISTRY_COMPAT_PATH,
CncfSchemaRegistry: url + REGISTRY_CNCF_PATH,
}

return endpoints
Expand Down
5 changes: 5 additions & 0 deletions pkg/core/localize/locales/en/cmd/generate_config.en.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ $ rhoas generate-config --type json
[generate.flag.type]
one='Type of configuration file to be generated'

[generate.common.flag.fileLocation.description]
description = 'Description for --output-file flag'
one = 'Sets a custom file location to save the credentials'


[generate.log.info.noSevices]
one='No services available to generate configurations'

Expand Down

0 comments on commit f433b20

Please sign in to comment.