Skip to content

Commit

Permalink
swap to tflog from Printf
Browse files Browse the repository at this point in the history
updates logging output to use tflog over Printf to adopt better practices and
logging control for the provider.
  • Loading branch information
jacobbednarz committed May 23, 2022
1 parent a05cd97 commit 2b27e0d
Show file tree
Hide file tree
Showing 82 changed files with 500 additions and 462 deletions.
69 changes: 36 additions & 33 deletions docs/debugging-with-delve.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
# Debugging with Delve

In the past, the only way to know what was happening in Terraform was to drop
In the past, the only way to know what was happening in Terraform was to drop
something like this around your code.

```
log.Println("[DEBUG] Something happened!")
log.Printf("[DEBUG] broken thing: %#v", thing)
// or
tflog.Debug(ctx, fmt.Sprintf("broken thing: %#v", thing))
```

This is incredibly tedious, and you end up wasting time going back and forth on
This is incredibly tedious, and you end up wasting time going back and forth on
what you want to inspect and in what states.

Since we've finally upgraded to `terraform-plugin-sdk` v2, we're able to advance
from log based debugging with Terraform to using a debugger. My choice for
from log based debugging with Terraform to using a debugger. My choice for
Golang is [Delve] however some Gophers will favour [gdb] instead.

Below, I'm using VS Code as my editor however should be able to sub in your
Below, I'm using VS Code as my editor however should be able to sub in your
editor equivalent and follow along.

- Drop into a terminal session
- Clone the git repository into your Go directory
```
$ git clone git@github.com:cloudflare/terraform-provider-cloudflare.git /Users/jacob/go/src/github.com/cloudflare/
```
- Build the development version of the provider binary. It is important to use
the development version to disable compiler optimisations and inlining; without
- Build the development version of the provider binary. It is important to use
the development version to disable compiler optimisations and inlining; without
these compile flags some parts of Delve just won't work.
```
$ make build-dev
Expand All @@ -34,8 +35,8 @@ editor equivalent and follow along.
$ file terraform-provider-cloudflare_99.0.0
terraform-provider-cloudflare_99.0.0: Mach-O 64-bit executable x86_64
```
- Now that the binary is created, you can execute Delve in headless mode. I use
a static listen address here to make the debugging configuration consistent but
- Now that the binary is created, you can execute Delve in headless mode. I use
a static listen address here to make the debugging configuration consistent but
you can also use the ephemeral port assigned if you'd rather do that.
```
$ dlv exec --headless ./terraform-provider-cloudflare_99.0.0 --listen 127.0.0.1:44444 -- --debug
Expand All @@ -44,33 +45,34 @@ editor equivalent and follow along.
for x86_64.
Got a connection, launched process ./terraform-provider-cloudflare_99.0.0 (pid = 92684).
```
Be sure to leave this window/tab open. It will soon have an environment
Be sure to leave this window/tab open. It will soon have an environment
variable configuration for you to prefix your Terraform commands with.
- In VS Code, create a new `launch.json` for debugging. Drop in the following snippet.
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Terraform delve debugger",
"type": "go",
"request": "attach",
"mode": "remote",
"remotePath": "${workspaceFolder}",
"port": 44444,
"host": "127.0.0.1",
"apiVersion": 1.0,
}
]
}
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Terraform delve debugger",
"type": "go",
"request": "attach",
"mode": "remote",
"remotePath": "${workspaceFolder}",
"port": 44444,
"host": "127.0.0.1",
"apiVersion": 1.0
}
]
}
```
- You can now hit the "start debugger" button in VS code.

![GdrJ0Q5l-CYg5yyH6-jwJ1Oeee](https://user-images.githubusercontent.com/283234/134456154-55f06831-5016-46b1-ae7f-563baf5ddc36.png)
- If you've done everything correct up until this point, you should now be able
to pop back to the Delve terminal session and see it has now output a

- If you've done everything correct up until this point, you should now be able
to pop back to the Delve terminal session and see it has now output a
`TF_REATTACH_PROVIDERS` configuration below your `dlv exec` command.

```
{"@level":"debug","@message":"plugin address","@timestamp":"2021-09-23T13:56:14.703121+10:00","address":"/var/folders/36/zlscnhfn27n1yxx52cr1kdmr0000gp/T/plugin1090848880","network":"unix"}
Provider started, to attach Terraform set the TF_REATTACH_PROVIDERS env var:
Expand All @@ -80,12 +82,13 @@ editor equivalent and follow along.
{"@level":"debug","@message":"stdio EOF, exiting copy loop","@timestamp":"2021-09-23T13:58:24.698711+10:00"}
{"@level":"debug","@message":"stdio EOF, exiting copy loop","@timestamp":"2021-09-23T13:58:24.698712+10:00"}
```
- Now, it is just a matter of prefixing your Terraform commands (apply/plan,
go tests) with this environment variable and it will hit the breakpoints
you've set. You can also export this into the environment if you'd rather

- Now, it is just a matter of prefixing your Terraform commands (apply/plan,
go tests) with this environment variable and it will hit the breakpoints
you've set. You can also export this into the environment if you'd rather
instead of prefixing all commands.
```
$ TF_REATTACH_PROVIDERS='{"registry.terraform.io/cloudflare/cloudflare":{"Protocol":"grpc","ProtocolVersion":5,"Pid":92684,"Test":true,"Addr":{"Network":"unix","String":"/var/folders/36/zlscnhfn27n1yxx52cr1kdmr0000gp/T/plugin1090848880"}}}' \
$ TF_REATTACH_PROVIDERS='{"registry.terraform.io/cloudflare/cloudflare":{"Protocol":"grpc","ProtocolVersion":5,"Pid":92684,"Test":true,"Addr":{"Network":"unix","String":"/var/folders/36/zlscnhfn27n1yxx52cr1kdmr0000gp/T/plugin1090848880"}}}' \
CLOUDFLARE_EMAIL="..." CLOUDFLARE_API_KEY="..." terraform apply
```

Expand Down
8 changes: 5 additions & 3 deletions internal/provider/config.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package provider

import (
"context"
"fmt"
"log"

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

type Config struct {
Expand All @@ -19,20 +20,21 @@ type Config struct {
func (c *Config) Client() (*cloudflare.API, error) {
var err error
var client *cloudflare.API
ctx := context.Background()

if c.APIToken != "" {
client, err = cloudflare.NewWithAPIToken(c.APIToken, c.Options...)
} else {
client, err = cloudflare.New(c.APIKey, c.Email, c.Options...)
}
if err != nil {
return nil, fmt.Errorf("Error creating new Cloudflare client: %w", err)
return nil, fmt.Errorf("error creating new Cloudflare client: %w", err)
}

if c.APIUserServiceKey != "" {
client.APIUserServiceKey = c.APIUserServiceKey
}

log.Printf("[INFO] Cloudflare Client configured for user: %s", c.Email)
tflog.Info(ctx, fmt.Sprintf("cloudflare Client configured for user: %s", c.Email))
return client, nil
}
4 changes: 2 additions & 2 deletions internal/provider/data_source_account_roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package provider
import (
"context"
"fmt"
"log"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -48,7 +48,7 @@ func dataSourceCloudflareAccountRolesRead(ctx context.Context, d *schema.Resourc
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)

log.Printf("[DEBUG] Reading Account Roles")
tflog.Debug(ctx, fmt.Sprintf("Reading Account Roles"))
roles, err := client.AccountRoles(ctx, accountID)
if err != nil {
return diag.FromErr(fmt.Errorf("error listing Account Roles: %w", err))
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/data_source_api_token_permission_groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package provider
import (
"context"
"fmt"
"log"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand All @@ -24,7 +24,7 @@ func dataSourceCloudflareApiTokenPermissionGroups() *schema.Resource {
}

func dataSourceCloudflareApiTokenPermissionGroupsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[DEBUG] Reading API Token Permission Groups")
tflog.Debug(ctx, fmt.Sprintf("Reading API Token Permission Groups"))
client := meta.(*cloudflare.API)

permissions, err := client.ListAPITokensPermissionGroups(ctx)
Expand Down
6 changes: 3 additions & 3 deletions internal/provider/data_source_waf_groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package provider
import (
"context"
"fmt"
"log"
"regexp"

cloudflare "github.com/cloudflare/cloudflare-go"
"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/hashicorp/terraform-plugin-sdk/v2/helper/validation"
Expand Down Expand Up @@ -101,7 +101,7 @@ func dataSourceCloudflareWAFGroupsRead(ctx context.Context, d *schema.ResourceDa
var pkgList []cloudflare.WAFPackage
if packageID == "" {
var err error
log.Printf("[DEBUG] Reading WAF Packages")
tflog.Debug(ctx, fmt.Sprintf("Reading WAF Packages"))
pkgList, err = client.ListWAFPackages(ctx, zoneID)
if err != nil {
return diag.FromErr(err)
Expand All @@ -110,7 +110,7 @@ func dataSourceCloudflareWAFGroupsRead(ctx context.Context, d *schema.ResourceDa
pkgList = append(pkgList, cloudflare.WAFPackage{ID: packageID})
}

log.Printf("[DEBUG] Reading WAF Groups")
tflog.Debug(ctx, fmt.Sprintf("Reading WAF Groups"))
groupIds := make([]string, 0)
groupDetails := make([]interface{}, 0)
for _, pkg := range pkgList {
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/data_source_waf_packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package provider
import (
"context"
"fmt"
"log"
"regexp"

cloudflare "github.com/cloudflare/cloudflare-go"
"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/hashicorp/terraform-plugin-sdk/v2/helper/validation"
Expand Down Expand Up @@ -96,7 +96,7 @@ func dataSourceCloudflareWAFPackagesRead(ctx context.Context, d *schema.Resource
return diag.FromErr(err)
}

log.Printf("[DEBUG] Reading WAF Packages")
tflog.Debug(ctx, fmt.Sprintf("Reading WAF Packages"))
packageIds := make([]string, 0)
packageDetails := make([]interface{}, 0)
pkgList, err := client.ListWAFPackages(ctx, zoneID)
Expand Down
6 changes: 3 additions & 3 deletions internal/provider/data_source_waf_rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package provider
import (
"context"
"fmt"
"log"
"regexp"

cloudflare "github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -114,7 +114,7 @@ func dataSourceCloudflareWAFRulesRead(ctx context.Context, d *schema.ResourceDat
var pkgList []cloudflare.WAFPackage
if packageID == "" {
var err error
log.Printf("[DEBUG] Reading WAF Packages")
tflog.Debug(ctx, fmt.Sprintf("Reading WAF Packages"))
pkgList, err = client.ListWAFPackages(ctx, zoneID)
if err != nil {
return diag.FromErr(err)
Expand All @@ -123,7 +123,7 @@ func dataSourceCloudflareWAFRulesRead(ctx context.Context, d *schema.ResourceDat
pkgList = append(pkgList, cloudflare.WAFPackage{ID: packageID})
}

log.Printf("[DEBUG] Reading WAF Rules")
tflog.Debug(ctx, fmt.Sprintf("Reading WAF Rules"))
ruleIds := make([]string, 0)
ruleDetails := make([]interface{}, 0)
for _, pkg := range pkgList {
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/data_source_zone.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package provider
import (
"context"
"fmt"
"log"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -63,7 +63,7 @@ func dataSourceCloudflareZone() *schema.Resource {
}

func dataSourceCloudflareZoneRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[DEBUG] Reading Zones")
tflog.Debug(ctx, fmt.Sprintf("Reading Zones"))
client := meta.(*cloudflare.API)
zoneID := d.Get("zone_id").(string)
name := d.Get("name").(string)
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/data_source_zone_dnssec.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package provider
import (
"context"
"fmt"
"log"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -68,7 +68,7 @@ func dataSourceCloudflareZoneDNSSECRead(ctx context.Context, d *schema.ResourceD

zoneID := d.Get("zone_id").(string)

log.Printf("[DEBUG] Reading Zone DNSSEC %s", zoneID)
tflog.Debug(ctx, fmt.Sprintf("Reading Zone DNSSEC %s", zoneID))

dnssec, err := client.ZoneDNSSECSetting(ctx, zoneID)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/data_source_zones.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package provider
import (
"context"
"fmt"
"log"
"regexp"

"github.com/cloudflare/cloudflare-go"
"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/hashicorp/terraform-plugin-sdk/v2/helper/validation"
Expand Down Expand Up @@ -74,7 +74,7 @@ func dataSourceCloudflareZones() *schema.Resource {
}

func dataSourceCloudflareZonesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[DEBUG] Reading Zones")
tflog.Debug(ctx, fmt.Sprintf("Reading Zones"))
client := meta.(*cloudflare.API)
filter, err := expandFilter(d.Get("filter"))
if err != nil {
Expand Down
6 changes: 4 additions & 2 deletions internal/provider/data_source_zones_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/pkg/errors"

Expand All @@ -23,9 +24,10 @@ func init() {
}

func testSweepCloudflareZones(r string) error {
ctx := context.Background()
client, clientErr := sharedClient()
if clientErr != nil {
log.Printf("[ERROR] Failed to create Cloudflare client: %s", clientErr)
tflog.Error(ctx, fmt.Sprintf("Failed to create Cloudflare client: %s", clientErr))
}

accountID := os.Getenv("CLOUDFLARE_ACCOUNT_ID")
Expand All @@ -35,7 +37,7 @@ func testSweepCloudflareZones(r string) error {
zoneFilter := cloudflare.WithZoneFilters("", accountID, "")
zones, zoneErr := client.ListZonesContext(context.TODO(), zoneFilter)
if zoneErr != nil {
log.Printf("[ERROR] Failed to fetch Cloudflare zones: %s", zoneErr)
tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare zones: %s", zoneErr))
}

if len(zones.Result) == 0 {
Expand Down
Loading

0 comments on commit 2b27e0d

Please sign in to comment.