other

package
v1.0.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2025 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AliasCmd = &cobra.Command{
	Use:   "alias",
	Short: "Manage command aliases",
	Long:  `Manage aliases for frequently used commands.`,
}

AliasCmd represents the alias command

View Source
var ApiResourcesCmd = &cobra.Command{
	Use:   "api_resources",
	Short: "Displays supported API resources",
	Example: `  # List all API resources for all services
  $ cfctl api_resources

  # List API resources for a specific service
  $ cfctl api_resources -s identity

  # List API resources for multiple services
  $ cfctl api_resources -s identity,inventory,repository`,
	Run: func(cmd *cobra.Command, args []string) {
		home, err := os.UserHomeDir()
		if err != nil {
			log.Fatalf("Unable to find home directory: %v", err)
		}

		settingPath := filepath.Join(home, ".cfctl", "setting.yaml")

		mainV := viper.New()
		mainV.SetConfigFile(settingPath)
		mainV.SetConfigType("yaml")
		mainConfigErr := mainV.ReadInConfig()

		var currentEnv string
		var envConfig map[string]interface{}

		if mainConfigErr == nil {
			currentEnv = mainV.GetString("environment")
			if currentEnv != "" {
				envConfig = mainV.GetStringMap(fmt.Sprintf("environments.%s", currentEnv))
			}
		}

		if envConfig == nil {
			return
		}

		endpointsMap, err := loadEndpointsFromCache(currentEnv)
		if err != nil {

			endpointName, ok := envConfig["endpoint"].(string)
			if !ok || endpointName == "" {
				return
			}

			endpointsMap, err = configs.FetchEndpointsMap(endpointName)
			if err != nil {
				log.Fatalf("Failed to fetch endpointsMap from '%s': %v", endpointName, err)
			}
		}

		shortNamesFile := filepath.Join(home, ".cfctl", "short_names.yaml")
		shortNamesMap := make(map[string]string)
		if _, err := os.Stat(shortNamesFile); err == nil {
			file, err := os.Open(shortNamesFile)
			if err != nil {
				log.Fatalf("Failed to open short_names.yaml file: %v", err)
			}
			defer file.Close()

			err = yaml.NewDecoder(file).Decode(&shortNamesMap)
			if err != nil {
				log.Fatalf("Failed to decode short_names.yaml: %v", err)
			}
		}

		if endpoints != "" {
			selectedEndpoints := strings.Split(endpoints, ",")
			for i := range selectedEndpoints {
				selectedEndpoints[i] = strings.TrimSpace(selectedEndpoints[i])
			}
			var allData [][]string

			for _, endpointName := range selectedEndpoints {
				serviceEndpoint, ok := endpointsMap[endpointName]
				if !ok {
					log.Printf("No endpoint found for %s", endpointName)
					continue
				}

				result, err := format.FetchServiceResources(endpointName, serviceEndpoint, shortNamesMap)
				if err != nil {
					log.Printf("Error processing service %s: %v", endpointName, err)
					continue
				}

				allData = append(allData, result...)
			}

			sort.Slice(allData, func(i, j int) bool {
				return allData[i][0] < allData[j][0]
			})

			renderTable(allData)
			return
		}

		// If no specific endpoints are provided, list all services
		var wg sync.WaitGroup
		dataChan := make(chan [][]string, len(endpointsMap))
		errorChan := make(chan error, len(endpointsMap))

		for service, endpoint := range endpointsMap {
			wg.Add(1)
			go func(service, endpoint string) {
				defer wg.Done()
				result, err := format.FetchServiceResources(service, endpoint, shortNamesMap)
				if err != nil {
					errorChan <- fmt.Errorf("Error processing service %s: %v", service, err)
					return
				}
				dataChan <- result
			}(service, endpoint)
		}

		wg.Wait()
		close(dataChan)
		close(errorChan)

		if len(errorChan) > 0 {
			for err := range errorChan {
				log.Println(err)
			}
		}

		var allData [][]string
		for data := range dataChan {
			allData = append(allData, data...)
		}

		sort.Slice(allData, func(i, j int) bool {
			return allData[i][0] < allData[j][0]
		})

		renderTable(allData)
	},
}
View Source
var ApplyCmd = &cobra.Command{
	Use:   "apply",
	Short: "Apply a configuration to a resource using a file",
	Long:  `Apply the configuration in the YAML file to create or update a resource`,
	Example: `  # 01. Create a test.yaml file with service-verb-resource-spec format
  service: identity
  verb: create
  resource: WorkspaceGroup
  spec:
    name: Test Workspace Group
  ---
  service: identity
  verb: add_users
  resource: WorkspaceGroup
  spec:
    workspace_group_id: wg-12345
    users:
      - user_id: u-123
        role_id: role-123
      - user_id: u-456
        role_id: role-456

  # 02. Apply the configuration
  cfctl apply -f test.yaml`,
	RunE: func(cmd *cobra.Command, args []string) error {
		filename, _ := cmd.Flags().GetString("filename")
		if filename == "" {
			return fmt.Errorf("filename is required (-f flag)")
		}

		data, err := os.ReadFile(filename)
		if err != nil {
			return fmt.Errorf("failed to read file: %v", err)
		}

		resources, err := parseResourceSpecs(data)
		if err != nil {
			return err
		}

		// Process each resource sequentially
		var lastResponse map[string]interface{}
		for i, resource := range resources {
			pterm.Info.Printf("Applying resource %d/%d: %s/%s\n",
				i+1, len(resources), resource.Service, resource.Resource)

			parameters := convertSpecToParameters(resource.Spec, lastResponse)

			options := &transport.FetchOptions{
				Parameters: parameters,
			}

			response, err := transport.FetchService(resource.Service, resource.Verb, resource.Resource, options)
			if err != nil {
				pterm.Error.Printf("Failed to apply resource %d/%d: %v\n", i+1, len(resources), err)
				return err
			}

			lastResponse = response
			pterm.Success.Printf("Resource %d/%d applied successfully\n", i+1, len(resources))
		}

		return nil
	},
}

ApplyCmd represents the apply command

View Source
var LoginCmd = &cobra.Command{
	Use:   "login",
	Short: "Login to SpaceONE",
	Long: `A command that allows you to login to SpaceONE.
It will prompt you for your User ID, Password, and fetch the Domain ID automatically, then fetch the token.`,
	Run: executeLogin,
}

LoginCmd represents the login command

View Source
var SettingCmd = &cobra.Command{
	Use:   "setting",
	Short: "Manage cfctl setting file",
	Long: `Manage setting file for cfctl. 
You can initialize, switch environments, and display the current configuration.`,
}

SettingCmd represents the setting command

Functions

func GetIdentityEndpoint added in v1.0.11

func GetIdentityEndpoint(apiEndpoint string) (string, bool, error)

GetIdentityEndpoint fetches the identity service endpoint from the API endpoint

func GetSettingDir added in v1.0.0

func GetSettingDir() string

GetSettingDir returns the directory where setting file are stored

func WriteConfigPreservingKeyOrder added in v1.0.16

func WriteConfigPreservingKeyOrder(v *viper.Viper, path string) error

Types

type ResourceSpec added in v1.0.13

type ResourceSpec struct {
	Service  string                 `yaml:"service"`
	Verb     string                 `yaml:"verb"`
	Resource string                 `yaml:"resource"`
	Spec     map[string]interface{} `yaml:"spec"`
}

type ServiceEndpoint added in v1.0.11

type ServiceEndpoint struct {
	Name     string `json:"name"`
	Service  string `json:"service"`
	Endpoint string `json:"endpoint"`
}

type TokenInfo added in v0.0.7

type TokenInfo struct {
	Token string `yaml:"token"`
}

type UserCredentials added in v0.0.7

type UserCredentials struct {
	UserID   string `yaml:"userid"`
	Password string `yaml:"password"`
	Token    string `yaml:"token"`
}

Define a struct for user credentials

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL