Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

switch to tflogs #154

Merged
merged 1 commit into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions internal/command/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import (
"bytes"
"context"
"io"
"log"
"os/exec"

"github.com/hashicorp/terraform-plugin-log/tflog"
)

type NewFn func(binary string, args ...string) Command
Expand Down Expand Up @@ -44,9 +45,10 @@ func (c *command) WithStdin(dir string) Command {
}

func (c *command) Run(ctx context.Context) ([]byte, error) {
log.Printf("[DEBUG] Running command '%v'\n", c.args)
var stdOut, stdErr bytes.Buffer
ctx = tflog.SetField(ctx, "command", c.args)
tflog.Debug(ctx, "Running command")

var stdOut, stdErr bytes.Buffer
cmd := exec.CommandContext(ctx, c.binary, c.args...)
cmd.Env = c.env
cmd.Stdin = c.stdin
Expand All @@ -55,13 +57,12 @@ func (c *command) Run(ctx context.Context) ([]byte, error) {

err := cmd.Run()
if err != nil {
log.Printf("[ERROR] Command '%v' finished with error: %v\n", c.args, err)
log.Printf("[ERROR] Stdout: %v\n", stdOut.String())
log.Printf("[ERROR] Stderr: %v\n", stdErr.String())

tflog.Error(ctx, "Command finished with error", map[string]interface{}{"error": err})
tflog.Trace(ctx, "Command outputs", map[string]interface{}{"stdout": stdOut.String(), "stderr": stdErr.String()})
return nil, NewError(err, c.args, stdOut.String(), stdErr.String())
}
log.Printf("[DEBUG] Command '%v' finished with success\n", c.args)
tflog.Debug(ctx, "Command finished with success")
tflog.Trace(ctx, "Command outputs", map[string]interface{}{"stdout": stdOut.String(), "stderr": stdErr.String()})

return stdOut.Bytes(), nil
}
5 changes: 3 additions & 2 deletions internal/command/cmd_retryable.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package command

import (
"context"
"log"
"time"

"github.com/hashicorp/terraform-plugin-log/tflog"
)

type RetryHandler interface {
Expand Down Expand Up @@ -43,6 +44,6 @@ func (c *retryableCommand) Run(ctx context.Context) ([]byte, error) {
return out, err
}
c.retryHandler.Backoff(attempts)
log.Printf("[ERROR] Retrying command after error: %v\n", err)
tflog.Error(ctx, "Retrying command after error", map[string]interface{}{"error": err})
}
}
42 changes: 22 additions & 20 deletions internal/provider/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"context"
"errors"
"fmt"
"log"

"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/maxlaverse/terraform-provider-bitwarden/internal/bitwarden/bw"
Expand Down Expand Up @@ -66,10 +66,12 @@ func objectSearch(ctx context.Context, d *schema.ResourceData, meta interface{})
if len(objs) == 0 {
return fmt.Errorf("no object found matching the filter")
} else if len(objs) > 1 {
log.Print("[WARN] Too many objects found:")
objects := []string{}
for _, obj := range objs {
log.Printf("[WARN] * %s (%s)", obj.Name, obj.ID)
objects = append(objects, fmt.Sprintf("%s (%s)", obj.Name, obj.ID))
}
tflog.Warn(ctx, "Too many objects found", map[string]interface{}{"objects": objects})

return fmt.Errorf("too many objects found")
}

Expand All @@ -81,7 +83,7 @@ func objectSearch(ctx context.Context, d *schema.ResourceData, meta interface{})
return errors.New("object is soft deleted")
}

return objectDataFromStruct(d, &obj)
return objectDataFromStruct(ctx, d, &obj)
}

func listOptionsFromData(d *schema.ResourceData) []bw.ListObjectsOption {
Expand Down Expand Up @@ -116,13 +118,13 @@ func objectReadIgnoreMissing(ctx context.Context, d *schema.ResourceData, meta i

if errors.Is(err, bw.ErrObjectNotFound) {
d.SetId("")
log.Print("[WARN] Object not found, removing from state")
tflog.Warn(ctx, "Object not found, removing from state")
return diag.Diagnostics{}
}

if _, exists := d.GetOk(attributeDeletedDate); exists {
d.SetId("")
log.Print("[WARN] Object was soft deleted, removing from state")
tflog.Warn(ctx, "Object was soft deleted, removing from state")
return diag.Diagnostics{}
}

Expand All @@ -140,15 +142,15 @@ func objectDelete(ctx context.Context, d *schema.ResourceData, meta interface{})
}

func objectOperation(ctx context.Context, d *schema.ResourceData, operation func(ctx context.Context, secret bw.Object) (*bw.Object, error)) error {
obj, err := operation(ctx, objectStructFromData(d))
obj, err := operation(ctx, objectStructFromData(ctx, d))
if err != nil {
return err
}

return objectDataFromStruct(d, obj)
return objectDataFromStruct(ctx, d, obj)
}

func objectDataFromStruct(d *schema.ResourceData, obj *bw.Object) error {
func objectDataFromStruct(ctx context.Context, d *schema.ResourceData, obj *bw.Object) error {
if obj == nil {
// Object has been deleted
return nil
Expand Down Expand Up @@ -257,7 +259,7 @@ func objectDataFromStruct(d *schema.ResourceData, obj *bw.Object) error {
return err
}

err = d.Set(attributeLoginURIs, objectLoginURIsFromStruct(obj.Login.URIs))
err = d.Set(attributeLoginURIs, objectLoginURIsFromStruct(ctx, obj.Login.URIs))
if err != nil {
return err
}
Expand All @@ -267,7 +269,7 @@ func objectDataFromStruct(d *schema.ResourceData, obj *bw.Object) error {
return nil
}

func objectStructFromData(d *schema.ResourceData) bw.Object {
func objectStructFromData(ctx context.Context, d *schema.ResourceData) bw.Object {
var obj bw.Object

obj.ID = d.Id()
Expand Down Expand Up @@ -339,7 +341,7 @@ func objectStructFromData(d *schema.ResourceData) bw.Object {
obj.Login.Username = v
}
if vList, ok := d.Get(attributeLoginURIs).([]interface{}); ok {
obj.Login.URIs = objectLoginURIsFromData(vList)
obj.Login.URIs = objectLoginURIsFromData(ctx, vList)
}
}
}
Expand Down Expand Up @@ -424,30 +426,30 @@ func objectFieldStructFromData(vList []interface{}) []bw.Field {
return fields
}

func objectLoginURIsFromData(vList []interface{}) []bw.LoginURI {
func objectLoginURIsFromData(ctx context.Context, vList []interface{}) []bw.LoginURI {
uris := make([]bw.LoginURI, len(vList))
for k, v := range vList {
vc := v.(map[string]interface{})
uris[k] = bw.LoginURI{
Match: strMatchToInt(vc[attributeLoginURIsMatch].(string)),
Match: strMatchToInt(ctx, vc[attributeLoginURIsMatch].(string)),
URI: vc[attributeLoginURIsValue].(string),
}
}
return uris
}

func objectLoginURIsFromStruct(objUris []bw.LoginURI) []interface{} {
func objectLoginURIsFromStruct(ctx context.Context, objUris []bw.LoginURI) []interface{} {
uris := make([]interface{}, len(objUris))
for k, f := range objUris {
uris[k] = map[string]interface{}{
attributeLoginURIsMatch: intMatchToStr(f.Match),
attributeLoginURIsMatch: intMatchToStr(ctx, f.Match),
attributeLoginURIsValue: f.URI,
}
}
return uris
}

func intMatchToStr(match *bw.URIMatch) URIMatchStr {
func intMatchToStr(ctx context.Context, match *bw.URIMatch) URIMatchStr {
if match == nil {
return URIMatchDefault
}
Expand All @@ -466,12 +468,12 @@ func intMatchToStr(match *bw.URIMatch) URIMatchStr {
case bw.URIMatchNever:
return URIMatchNever
default:
log.Printf("unsupported integer value for URI match: '%d'. Falling back to default\n", *match)
tflog.Warn(ctx, "unsupported integer value for URI match - Falling back to default", map[string]interface{}{"match": *match})
return URIMatchDefault
}
}

func strMatchToInt(match string) *bw.URIMatch {
func strMatchToInt(ctx context.Context, match string) *bw.URIMatch {
var v bw.URIMatch
switch match {
case string(URIMatchDefault):
Expand All @@ -489,7 +491,7 @@ func strMatchToInt(match string) *bw.URIMatch {
case string(URIMatchNever):
v = bw.URIMatchNever
default:
log.Printf("unsupported string value for URI match: '%s'. Falling back to default\n", match)
tflog.Warn(ctx, "unsupported string value for URI match - Falling back to default", map[string]interface{}{"match": match})
return nil
}
return &v
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package provider
import (
"context"
"fmt"
"log"
"os/exec"
"path/filepath"

"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/maxlaverse/terraform-provider-bitwarden/internal/bitwarden/bw"
Expand Down Expand Up @@ -215,7 +215,7 @@ func logoutIfIdentityChanged(ctx context.Context, d *schema.ResourceData, bwClie
if (status.Status == bw.StatusLocked || status.Status == bw.StatusUnlocked) && (!status.VaultOfUser(email) || !status.VaultFromServer(serverURL)) {
status.Status = bw.StatusUnauthenticated

log.Printf("Logging out as the local Vault belongs to a different identity (vault: '%v' on '%s', provider: '%v' on '%s')\n", status.UserEmail, status.ServerURL, email, status.ServerURL)
tflog.Warn(ctx, "Logging out as the local Vault belongs to a different identity", map[string]interface{}{"vault_email": status.UserEmail, "vault_server": status.ServerURL, "provider_email": email, "provider_server": serverURL})
err := bwClient.Logout(ctx)
if err != nil {
return err
Expand Down
17 changes: 0 additions & 17 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package main

import (
"context"
"flag"
"log"

"github.com/hashicorp/terraform-plugin-sdk/v2/plugin"
"github.com/maxlaverse/terraform-provider-bitwarden/internal/provider"
)
Expand All @@ -24,20 +20,7 @@ var (
)

func main() {
var debugMode bool

flag.BoolVar(&debugMode, "debug", false, "set to true to run the provider with support for debuggers like delve")
flag.Parse()

opts := &plugin.ServeOpts{ProviderFunc: provider.New(version)}

if debugMode {
err := plugin.Debug(context.Background(), providerAddr, opts)
if err != nil {
log.Fatal(err.Error())
}
return
}

plugin.Serve(opts)
}
Loading