Skip to content

Commit

Permalink
remove lib and bump go version
Browse files Browse the repository at this point in the history
  • Loading branch information
jason-jackson committed May 9, 2024
1 parent e651346 commit 03ad57e
Show file tree
Hide file tree
Showing 35 changed files with 879 additions and 1,587 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
go-version: 1.22

- name: Build
run: go build -v ./...
Expand Down
29 changes: 23 additions & 6 deletions lib/organization.go → cmd/client.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2018-2022 SIL International
// Copyright © 2018-2024 SIL International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -12,10 +12,27 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package lib
package cmd

// OrganizationExists returns whether an organization with the given name exists
func OrganizationExists(organization string) (bool, error) {
org, err := client.Organizations.Read(ctx, organization)
return org != nil, err
import (
"context"

"github.com/hashicorp/go-tfe"
)

var (
client *tfe.Client
ctx = context.Background()
)

func NewClient(t string) error {
cfg := tfe.DefaultConfig()
if t == "" {
t = token
}
cfg.Token = t

var err error
client, err = tfe.NewClient(cfg)
return err
}
40 changes: 20 additions & 20 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2018-2022 SIL International
// Copyright © 2018-2024 SIL International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -16,22 +16,23 @@ package cmd

import (
"fmt"
"log"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/silinternational/tfc-ops/v3/lib"
)

const requiredPrefix = "required - "
const (
requiredPrefix = "required - "
atlasToken = "ATLAS_TOKEN"
)

var (
cfgFile string
token string
organization string
readOnlyMode bool
errLog *log.Logger
debug bool
)

// rootCmd represents the base command when called without any subcommands
Expand All @@ -53,30 +54,28 @@ func Execute() {

func init() {
cobra.OnInitialize(initConfig)

errLog = log.New(os.Stderr, "", 0)
}

func initRoot(cmd *cobra.Command, args []string) {
// Get Tokens from env vars
atlasToken := os.Getenv("ATLAS_TOKEN")
if atlasToken == "" {
errLog.Fatalln("Error: Environment variable for ATLAS_TOKEN is required to execute plan and migration")
// Skip for version command
if cmd.UseLine() == versionCmd.UseLine() {
return
}
lib.SetToken(atlasToken)

debugStr := os.Getenv("TFC_OPS_DEBUG")
if debugStr == "TRUE" || debugStr == "true" {
lib.EnableDebug()
// Get Tokens from env vars
token = viper.GetString(atlasToken)
if token == "" {
err := fmt.Errorf("environment variable for %s is required to execute plan and migration", atlasToken)
cobra.CheckErr(err)
}

debug = viper.GetBool("TFC_OPS_DEBUG")

if readOnlyMode {
lib.EnableReadOnlyMode()
fmt.Println("###### READ ONLY MODE ENABLED ######")
}

if err := lib.NewClient(""); err != nil {
errLog.Fatalln(err)
}
cobra.CheckErr(NewClient(""))
}

// initConfig reads in config file and ENV variables if set.
Expand All @@ -95,6 +94,7 @@ func initConfig() {
}

viper.AutomaticEnv() // read in environment variables that match
viper.SetDefault("TFC_OPS_DEBUG", false)

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/variables.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2018-2022 SIL International
// Copyright © 2018-2024 SIL International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
79 changes: 32 additions & 47 deletions cmd/variablesAdd.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2018-2022 SIL International
// Copyright © 2018-2024 SIL International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -17,76 +17,61 @@ package cmd
import (
"fmt"

"github.com/hashicorp/go-tfe"
"github.com/spf13/cobra"

"github.com/silinternational/tfc-ops/v3/lib"
)

var variablesAddCmd = &cobra.Command{
Use: "add",
Short: "Add new variable (if not already present)",
Long: `Add variable in matching workspace. Will not update existing variable.`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
runVariablesAdd()
},
Run: runVariablesAdd,
}

func init() {
variablesCmd.AddCommand(variablesAddCmd)
variablesAddCmd.Flags().StringVarP(&key, "key", "k", "",
requiredPrefix+"Terraform variable key")
if err := variablesAddCmd.MarkFlagRequired("key"); err != nil {
errLog.Fatalln("failed to mark 'key' as a required flag on variablesAddCmd")
}
variablesAddCmd.Flags().StringVarP(&value, "value", "v", "",
requiredPrefix+"Terraform variable value")
if err := variablesAddCmd.MarkFlagRequired("value"); err != nil {
errLog.Fatalln("failed to mark 'value' as a required flag on variablesAddCmd")
}
}

func runVariablesAdd() {
if readOnlyMode {
fmt.Println("Read only mode enabled. No variables will be added.")
}
cobra.CheckErr(variablesAddCmd.MarkFlagRequired("key"))
cobra.CheckErr(variablesAddCmd.MarkFlagRequired("value"))
}

func runVariablesAdd(cmd *cobra.Command, args []string) {
var ws []*tfe.Workspace
if workspace != "" {
addWorkspaceVar(organization, workspace, key, value)
return
}
w, err := client.Workspaces.Read(ctx, organization, workspace)
cobra.CheckErr(err)

fmt.Printf("Adding variables with key '%s' and value '%s' to all workspaces...\n", key, value)
allWorkspaces, err := lib.GetAllWorkspaces(organization)
if err != nil {
println(err.Error())
return
}
ws = append(ws, w)
} else {
var err error
list, err := client.Workspaces.List(ctx, organization, nil)
cobra.CheckErr(err)

for _, w := range allWorkspaces {
addWorkspaceVar(organization, w.Name, key, value)
workspace = "all workspaces"
ws = list.Items
}
}
fmt.Printf("Adding variables with key '%s' and value '%s' to %s...\n", key, value, workspace)

func addWorkspaceVar(org, ws, key, value string) {
if v, err := lib.GetWorkspaceVar(org, ws, key); err != nil {
errLog.Fatalf("failure checking for existence of variable '%s' in workspace '%s', %s\n", key, ws, err)
} else if v != nil {
errLog.Fatalf("'%s' already exists in '%s'. Use 'variable update' command to change the value.\n", key, ws)
}
for _, w := range ws {
for _, v := range w.Variables {
if v.Key == key {
err := fmt.Errorf("'%s' already exists in '%s'. Use 'variable update' command to change the value", key, w.Name)
cobra.CheckErr(err)
}
}

fmt.Printf("Workspace %s: Adding variable %s = %s\n", ws, key, value)
if !readOnlyMode {
if _, err := lib.AddOrUpdateVariable(lib.UpdateConfig{
Organization: organization,
Workspace: ws,
SearchString: key,
NewValue: value,
AddKeyIfNotFound: true,
SearchOnVariableValue: false,
SensitiveVariable: false,
}); err != nil {
errLog.Fatalf("failed to add variable '%s' in workspace '%s', %s\n", key, ws, err)
fmt.Printf("Workspace %s: Adding variable %s = %s\n", w.Name, key, value)
if !readOnlyMode {
_, err := client.Variables.Create(ctx, w.ID, tfe.VariableCreateOptions{
Key: &key,
Value: &value,
})
cobra.CheckErr(err)
}
}
}
50 changes: 15 additions & 35 deletions cmd/variablesDelete.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2018-2022 SIL International
// Copyright © 2018-2024 SIL International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -18,8 +18,6 @@ import (
"fmt"

"github.com/spf13/cobra"

"github.com/silinternational/tfc-ops/v3/lib"
)

var key string
Expand All @@ -29,54 +27,36 @@ var variablesDeleteCmd = &cobra.Command{
Short: "Delete variable",
Long: `Delete variable in matching workspace having the specified key`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
runVariablesDelete()
},
Run: runVariablesDelete,
}

func init() {
variablesCmd.AddCommand(variablesDeleteCmd)
variablesDeleteCmd.Flags().StringVarP(&key, "key", "k", "",
requiredPrefix+"Terraform variable key to delete, must match exactly")
if err := variablesDeleteCmd.MarkFlagRequired("key"); err != nil {
errLog.Fatalln("failed to mark 'key' as a required flag on variablesDeleteCmd: " + err.Error())
}
cobra.CheckErr(variablesDeleteCmd.MarkFlagRequired("key"))
}

func runVariablesDelete() {
if readOnlyMode {
fmt.Println("Read only mode enabled. No variables will be deleted.")
}

func runVariablesDelete(cmd *cobra.Command, args []string) {
if workspace == "" {
errLog.Fatal("No workspace specified")
}

found := deleteWorkspaceVar(organization, workspace, key)
if !found {
errLog.Fatalf("Variable %s not found in workspace %s\n", key, workspace)
cobra.CheckErr("no workspace specified")
}
}

func deleteWorkspaceVar(org, ws, key string) bool {
workspace, err := lib.GetWorkspaceByName(org, ws)
if err != nil {
println(err.Error())
return false
}
w, err := client.Workspaces.Read(ctx, organization, workspace)
cobra.CheckErr(err)

for _, v := range workspace.Variables {
for _, v := range w.Variables {
if v.Key == key {
fmt.Printf("Deleting variable %s from workspace %s\n", v.Key, ws)
fmt.Printf("Deleting variable %s from workspace %s\n", v.Key, workspace)

if !readOnlyMode {
if err := lib.DeleteVariable(workspace.ID, v.ID); err != nil {
println(err.Error())
}
err := client.Variables.Delete(ctx, w.ID, v.ID)
cobra.CheckErr(err)
}

return err == nil
return
}
}
return false

err = fmt.Errorf("variable %s not found in workspace %s", key, workspace)
cobra.CheckErr(err)
}
Loading

0 comments on commit 03ad57e

Please sign in to comment.