registry

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2022 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const AUTO_GENERATED_MSG string = `` /* 414-byte string literal not displayed */

Variables

View Source
var AddCommand = cli.Command{
	Name:        "add",
	Description: "Add a Profile Registry that you want to sync with aws config file",
	Usage:       "Provide git repository you want to sync with aws config file",
	ArgsUsage:   "<repository url> ...",
	Action: func(c *cli.Context) error {

		if c.Args().Len() < 1 {
			clio.Error("Repository argument is required. Try 'granted registry add <https://github.com/your-org/your-registry.git>'")
		}

		var repoURLs []string

		n := 0
		for n < c.Args().Len() {
			repoURLs = append(repoURLs, c.Args().Get(n))
			n++
		}

		gConf, err := grantedConfig.Load()
		if err != nil {
			return err
		}

		for index, repoURL := range repoURLs {
			clio.Debugf("parsing the provided url to get host, organization and repo name for %s", repoURL)
			url, err := parseGitURL(repoURL)
			if err != nil {
				return err
			}

			if URLExists(gConf.ProfileRegistryURLS, url) {
				clio.Warnf("Already subscribed to '%s'. Skipping adding this registry. Use 'granted registry sync' cmd instead to sync the config files.", repoURL)

				continue
			}

			repoDirPath, err := getRegistryLocation(url)
			if err != nil {
				return err
			}

			if _, err = os.Stat(repoDirPath); err != nil {

				if os.IsNotExist(err) {
					err = gitClone(url.GetURL(), repoDirPath)
					if err != nil {
						return err
					}

				} else {

					return err
				}
			} else {

				clio.Debugf("%s already exists; pulling instead of cloning. ", url.GetURL())
				if err = gitPull(repoDirPath, false); err != nil {
					return err
				}
			}

			if err = parseClonedRepo(repoDirPath, url); err != nil {
				return err
			}

			isFirstSection := false
			if len(gConf.ProfileRegistryURLS) == 0 {
				if index == 0 {
					isFirstSection = true
				}
			}

			var r Registry
			_, err = r.Parse(repoDirPath, url)
			if err != nil {
				return err
			}

			awsConfigPath, err := getDefaultAWSConfigLocation()
			if err != nil {
				return err
			}

			if _, err := os.Stat(awsConfigPath); os.IsNotExist(err) {
				clio.Debugf("%s file does not exist. Creating an empty file\n", awsConfigPath)
				_, err := os.Create(awsConfigPath)
				if err != nil {
					return fmt.Errorf("unable to create : %s", err)
				}
			}

			if err := Sync(r, repoURL, repoDirPath, isFirstSection); err != nil {
				return err
			}

			gConf.ProfileRegistryURLS = append(gConf.ProfileRegistryURLS, repoURL)
			if err := gConf.Save(); err != nil {
				return err
			}
		}

		return nil
	},
}
View Source
var ProfileRegistry = cli.Command{
	Name:        "registry",
	Usage:       "Manage Profile Registries",
	Description: "Profile Registries allow you to easily share AWS profile configuration in a team.",
	Subcommands: []*cli.Command{&SetupCommand, &AddCommand, &SyncCommand, &RemoveCommand},
	Action: func(c *cli.Context) error {
		gConf, err := grantedConfig.Load()
		if err != nil {
			return err
		}

		if len(gConf.ProfileRegistryURLS) == 0 {
			clio.Warn("You haven't connected any Profile Registries yet.")
			clio.Info("Connect to a Profile Registry by running 'granted registry add <your_repo>'")
			return nil
		}

		clio.Info("Granted is currently synced with following registries:")
		for i, url := range gConf.ProfileRegistryURLS {
			clio.Logf("\t %d: %s", (i + 1), url)
		}
		clio.NewLine()

		clio.Info("To add new registry use 'granted registry add <your_repo>'")
		clio.Info("To remove a registry use 'granted registry remove' and select from the options")
		clio.Info("To sync a registry use 'granted registry sync'")

		return nil
	},
}
View Source
var RemoveCommand = cli.Command{
	Name:        "remove",
	Description: "Unsubscribe from a Profile Registry",
	Usage:       "Unsubscribe from a Profile Registry",

	Action: func(c *cli.Context) error {

		gConf, err := grantedConfig.Load()
		if err != nil {
			return err
		}

		if len(gConf.ProfileRegistryURLS) <= 0 {
			clio.Error("There are no profile registries configured currently.\n Please use 'granted registry add <https://github.com/your-org/your-registry.git>' to add a new registry")

			return nil
		}

		in := survey.Select{Message: "Please select the git repository you would like to unsubscribe:", Options: gConf.ProfileRegistryURLS}
		var out string
		err = testable.AskOne(&in, &out)
		if err != nil {
			return err
		}

		index := -1
		for i, v := range gConf.ProfileRegistryURLS {
			if out == v {
				index = i
				break
			}
		}

		if index != -1 {
			u, err := parseGitURL(out)
			if err != nil {
				return err
			}

			repoDir, err := getRegistryLocation(u)
			if err != nil {
				return err
			}

			err = RemoveAutogeneratedProfileByRegistryURL(out)
			if err != nil {
				return err
			}

			err = os.RemoveAll(repoDir)
			if err != nil {
				return err
			}

			gConf.ProfileRegistryURLS = remove(gConf.ProfileRegistryURLS, index)

			if err := gConf.Save(); err != nil {
				return err
			}
		}

		clio.Successf("Successfully unsubscribed from %s", out)

		return nil
	},
}
View Source
var SetupCommand = cli.Command{
	Name:        "setup",
	Usage:       "Setup a Profile Registry repository",
	Description: "Setup a granted registry repository",
	Subcommands: []*cli.Command{},
	Flags:       []cli.Flag{&cli.PathFlag{Name: "dir", Aliases: []string{"d"}, Usage: "Directory to setup the Profile Registry", Value: "granted-registry"}},
	Action: func(c *cli.Context) error {
		dir := c.Path("dir")

		err := ensureConfigDoesntExist(c, dir)
		if err != nil {
			return err
		}

		err = os.Mkdir(dir, 0755)
		if err != nil {
			return err
		}

		configFile, err := loadAWSConfigFile()
		if err != nil {
			return err
		}

		var confirm bool
		s := &survey.Confirm{
			Message: "Are you sure you want to copy all of the profiles from your AWS config file?",
			Default: true,
		}
		err = survey.AskOne(s, &confirm)
		if err != nil {
			return err
		}
		if !confirm {
			clio.Info("Cancelled registry setup")
			return nil
		}

		err = configFile.SaveTo(path.Join(dir, "config"))
		if err != nil {
			return err
		}

		f, err := os.Create(path.Join(dir, "granted.yml"))
		if err != nil {
			return err
		}
		defer f.Close()

		err = gitInit(dir)
		if err != nil {
			return err
		}

		_, err = f.WriteString(`awsConfig:
    - ./config`)
		if err != nil {
			return err
		}
		clio.Infof("Successfully created valid profile registry 'granted-registry' in %s.", dir)
		clio.Info("Now push this repository to remote origin so that your team-members can sync to it.")
		return nil
	},
}
View Source
var SyncCommand = cli.Command{
	Name:        "sync",
	Usage:       "Pull the latest change from remote origin and sync aws profiles in aws config files",
	Description: "Pull the latest change from remote origin and sync aws profiles in aws config files",
	Action: func(c *cli.Context) error {
		if err := SyncProfileRegistries(false); err != nil {
			return err
		}

		return nil
	},
}

Functions

func CheckoutRef

func CheckoutRef(ref string, repoDirPath string) error

WIP/TODO: set the path of the repo before checking out if a specific ref is passed we will checkout that ref can be a git hash, tag, or branch name. In that order

func Contains

func Contains(arr []string, s string) bool

func GetAutogeneratedTemplate

func GetAutogeneratedTemplate() string

func IsSameGitURL

func IsSameGitURL(a GitURL, b GitURL) bool

compares if Host, Organization and Repo name is same for both passed URL. if there is subfolder and filename then compare if they are same or not.

func RemoveAutogeneratedProfileByRegistryURL

func RemoveAutogeneratedProfileByRegistryURL(repoURL string) error

func Sync

func Sync(r Registry, repoURL string, repoDirPath string, isFirstSection bool) error

Sync function will load all the configs provided in the clonedFile. and generated a new section in the ~/.aws/profile file.

func SyncProfileRegistries

func SyncProfileRegistries(shouldSilentLog bool) error

Wrapper around sync func. Check if profile registry is configured, pull the latest changes and call sync func.

func URLExists

func URLExists(arr []string, url GitURL) bool

Types

type GitURL

type GitURL struct {
	ProvidedURL string
	Host        string
	Org         string
	Repo        string
	Subpath     string
	Filename    string
}

func (*GitURL) GetURL

func (g *GitURL) GetURL() string

type Registry

type Registry struct {
	AwsConfigPaths []string `yaml:"awsConfig"`
	Url            GitURL
}

func (*Registry) Parse

func (c *Registry) Parse(folderpath string, url GitURL) (*Registry, error)

Parse the config file if provided or 'granted.yml' file by default.

Jump to

Keyboard shortcuts

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