From 2b27e0dbdc8d182016ec1871a374bb39bd0e9d90 Mon Sep 17 00:00:00 2001 From: Jacob Bednarz Date: Mon, 23 May 2022 13:38:16 +1000 Subject: [PATCH] swap to tflog from Printf updates logging output to use tflog over Printf to adopt better practices and logging control for the provider. --- docs/debugging-with-delve.md | 69 ++++++++++--------- internal/provider/config.go | 8 ++- .../provider/data_source_account_roles.go | 4 +- ...data_source_api_token_permission_groups.go | 4 +- internal/provider/data_source_waf_groups.go | 6 +- internal/provider/data_source_waf_packages.go | 4 +- internal/provider/data_source_waf_rules.go | 6 +- internal/provider/data_source_zone.go | 4 +- internal/provider/data_source_zone_dnssec.go | 4 +- internal/provider/data_source_zones.go | 4 +- internal/provider/data_source_zones_test.go | 6 +- internal/provider/provider.go | 6 +- .../resource_cloudflare_access_application.go | 12 ++-- .../resource_cloudflare_access_bookmark.go | 12 ++-- ...source_cloudflare_access_ca_certificate.go | 8 +-- .../resource_cloudflare_access_group.go | 22 +++--- .../resource_cloudflare_access_group_test.go | 13 ++-- ...rce_cloudflare_access_identity_provider.go | 14 ++-- ...loudflare_access_identity_provider_test.go | 10 +-- ...ce_cloudflare_access_keys_configuration.go | 4 +- ...loudflare_access_mutual_tls_certificate.go | 12 ++-- ...lare_access_mutual_tls_certificate_test.go | 14 ++-- .../resource_cloudflare_access_policy.go | 18 ++--- .../resource_cloudflare_access_rule.go | 14 ++-- .../resource_cloudflare_account_member.go | 8 +-- .../provider/resource_cloudflare_api_token.go | 12 ++-- internal/provider/resource_cloudflare_argo.go | 10 +-- ..._authenticated_origin_pulls_certificate.go | 6 +- ...enticated_origin_pulls_certificate_test.go | 8 ++- .../resource_cloudflare_certificate_pack.go | 4 +- ...source_cloudflare_certificate_pack_test.go | 8 ++- .../resource_cloudflare_custom_hostname.go | 4 +- ...udflare_custom_hostname_fallback_origin.go | 4 +- ...esource_cloudflare_custom_hostname_test.go | 11 +-- .../resource_cloudflare_custom_ssl.go | 46 ++++++------- .../resource_cloudflare_device_policy.go | 6 +- ...e_cloudflare_device_posture_integration.go | 12 ++-- ...resource_cloudflare_device_posture_rule.go | 12 ++-- .../provider/resource_cloudflare_filter.go | 22 +++--- .../resource_cloudflare_filter_test.go | 9 +-- .../resource_cloudflare_firewall_rule.go | 20 +++--- .../resource_cloudflare_firewall_rule_test.go | 9 +-- .../resource_cloudflare_gre_tunnel.go | 6 +- .../resource_cloudflare_healthcheck.go | 6 +- .../provider/resource_cloudflare_ip_list.go | 4 +- .../resource_cloudflare_ipsec_tunnel.go | 6 +- .../resource_cloudflare_load_balancer.go | 18 ++--- ...source_cloudflare_load_balancer_monitor.go | 20 +++--- .../resource_cloudflare_load_balancer_pool.go | 22 +++--- .../resource_cloudflare_logpull_retention.go | 4 +- .../resource_cloudflare_logpush_job.go | 16 ++--- ...ource_cloudflare_magic_firewall_ruleset.go | 4 +- ...source_cloudflare_origin_ca_certificate.go | 12 ++-- .../provider/resource_cloudflare_page_rule.go | 19 ++--- .../resource_cloudflare_page_rule_test.go | 6 +- .../resource_cloudflare_rate_limit.go | 32 ++++----- .../provider/resource_cloudflare_record.go | 22 +++--- .../resource_cloudflare_record_test.go | 8 ++- .../resource_cloudflare_ruleset_test.go | 12 ++-- ...esource_cloudflare_spectrum_application.go | 24 +++---- ...ce_cloudflare_spectrum_application_test.go | 12 ++-- .../resource_cloudflare_static_route.go | 6 +- .../resource_cloudflare_teams_accounts.go | 6 +- .../resource_cloudflare_teams_list.go | 12 ++-- .../resource_cloudflare_teams_location.go | 12 ++-- ...source_cloudflare_teams_proxy_endpoints.go | 12 ++-- .../resource_cloudflare_teams_rules.go | 12 ++-- .../resource_cloudflare_tunnel_route.go | 4 +- .../resource_cloudflare_tunnel_route_test.go | 8 ++- .../resource_cloudflare_waf_override.go | 6 +- .../resource_cloudflare_waiting_room.go | 4 +- .../resource_cloudflare_waiting_room_event.go | 4 +- .../provider/resource_cloudflare_worker_kv.go | 6 +- .../resource_cloudflare_worker_route.go | 5 +- .../resource_cloudflare_worker_script.go | 8 +-- ...esource_cloudflare_workers_kv_namespace.go | 10 +-- internal/provider/resource_cloudflare_zone.go | 9 +-- ...resource_cloudflare_zone_cache_variants.go | 10 +-- ...rce_cloudflare_zone_cache_variants_test.go | 7 +- .../resource_cloudflare_zone_dnssec.go | 8 +-- .../resource_cloudflare_zone_lockdown.go | 30 ++++---- ...ource_cloudflare_zone_settings_override.go | 41 +++++------ 82 files changed, 500 insertions(+), 462 deletions(-) diff --git a/docs/debugging-with-delve.md b/docs/debugging-with-delve.md index 4f99efc0693..680519d1d71 100644 --- a/docs/debugging-with-delve.md +++ b/docs/debugging-with-delve.md @@ -1,21 +1,22 @@ # 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 @@ -23,8 +24,8 @@ editor equivalent and follow along. ``` $ 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 @@ -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 @@ -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: @@ -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 ``` diff --git a/internal/provider/config.go b/internal/provider/config.go index 731ffac758d..123e8218656 100644 --- a/internal/provider/config.go +++ b/internal/provider/config.go @@ -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 { @@ -19,6 +20,7 @@ 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...) @@ -26,13 +28,13 @@ func (c *Config) Client() (*cloudflare.API, error) { 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 } diff --git a/internal/provider/data_source_account_roles.go b/internal/provider/data_source_account_roles.go index bb2c7b31dd1..e2821c3e4e0 100644 --- a/internal/provider/data_source_account_roles.go +++ b/internal/provider/data_source_account_roles.go @@ -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" ) @@ -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)) diff --git a/internal/provider/data_source_api_token_permission_groups.go b/internal/provider/data_source_api_token_permission_groups.go index 9dc8a3889f3..5945e19c48b 100644 --- a/internal/provider/data_source_api_token_permission_groups.go +++ b/internal/provider/data_source_api_token_permission_groups.go @@ -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" ) @@ -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) diff --git a/internal/provider/data_source_waf_groups.go b/internal/provider/data_source_waf_groups.go index 9965f4e5b24..1a491b107e6 100644 --- a/internal/provider/data_source_waf_groups.go +++ b/internal/provider/data_source_waf_groups.go @@ -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" @@ -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) @@ -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 { diff --git a/internal/provider/data_source_waf_packages.go b/internal/provider/data_source_waf_packages.go index dc9b1161ee8..854ea28ebf6 100644 --- a/internal/provider/data_source_waf_packages.go +++ b/internal/provider/data_source_waf_packages.go @@ -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" @@ -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) diff --git a/internal/provider/data_source_waf_rules.go b/internal/provider/data_source_waf_rules.go index bacb0e243e6..f813029aaf1 100644 --- a/internal/provider/data_source_waf_rules.go +++ b/internal/provider/data_source_waf_rules.go @@ -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" ) @@ -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) @@ -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 { diff --git a/internal/provider/data_source_zone.go b/internal/provider/data_source_zone.go index c32d6c717d3..fae06598011 100644 --- a/internal/provider/data_source_zone.go +++ b/internal/provider/data_source_zone.go @@ -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" ) @@ -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) diff --git a/internal/provider/data_source_zone_dnssec.go b/internal/provider/data_source_zone_dnssec.go index 542a2ec8310..0cd57677909 100644 --- a/internal/provider/data_source_zone_dnssec.go +++ b/internal/provider/data_source_zone_dnssec.go @@ -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" ) @@ -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 { diff --git a/internal/provider/data_source_zones.go b/internal/provider/data_source_zones.go index f4b9a184277..2f347592d9d 100644 --- a/internal/provider/data_source_zones.go +++ b/internal/provider/data_source_zones.go @@ -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" @@ -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 { diff --git a/internal/provider/data_source_zones_test.go b/internal/provider/data_source_zones_test.go index 6275fbd5cc0..19164c876c0 100644 --- a/internal/provider/data_source_zones_test.go +++ b/internal/provider/data_source_zones_test.go @@ -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" @@ -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") @@ -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 { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index be8b807927b..f27aaf8a549 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -9,6 +9,7 @@ import ( cloudflare "github.com/cloudflare/cloudflare-go" cleanhttp "github.com/hashicorp/go-cleanhttp" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -17,8 +18,6 @@ import ( ) func init() { - // Set descriptions to support markdown syntax, this will be used in document generation - // and the language server. schema.DescriptionKind = schema.StringMarkdown } @@ -210,6 +209,7 @@ func New(version string) func() *schema.Provider { } func configure(version string, p *schema.Provider) func(context.Context, *schema.ResourceData) (interface{}, diag.Diagnostics) { + return func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { var diags diag.Diagnostics @@ -265,7 +265,7 @@ func configure(version string, p *schema.Provider) func(context.Context, *schema } if accountID, ok := d.GetOk("account_id"); ok { - log.Printf("[INFO] Using specified account id %s in Cloudflare provider", accountID.(string)) + tflog.Info(ctx, fmt.Sprintf("using specified account id %s in Cloudflare provider", accountID.(string))) options = append(options, cloudflare.UsingAccount(accountID.(string))) } else { return client, diag.FromErr(err) diff --git a/internal/provider/resource_cloudflare_access_application.go b/internal/provider/resource_cloudflare_access_application.go index 16ed4b32327..ca1bbcfc832 100644 --- a/internal/provider/resource_cloudflare_access_application.go +++ b/internal/provider/resource_cloudflare_access_application.go @@ -4,10 +4,10 @@ import ( "context" "errors" "fmt" - "log" "strings" 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" ) @@ -64,7 +64,7 @@ func resourceCloudflareAccessApplicationCreate(ctx context.Context, d *schema.Re newAccessApplication.CorsHeaders = CORSConfig } - log.Printf("[DEBUG] Creating Cloudflare Access Application from struct: %+v", newAccessApplication) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Access Application from struct: %+v", newAccessApplication)) identifier, err := initIdentifier(d) if err != nil { @@ -104,7 +104,7 @@ func resourceCloudflareAccessApplicationRead(ctx context.Context, d *schema.Reso if err != nil { var notFoundError *cloudflare.NotFoundError if errors.As(err, ¬FoundError) { - log.Printf("[INFO] Access Application %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Application %s no longer exists", d.Id())) d.SetId("") return nil } @@ -172,7 +172,7 @@ func resourceCloudflareAccessApplicationUpdate(ctx context.Context, d *schema.Re updatedAccessApplication.CorsHeaders = CORSConfig } - log.Printf("[DEBUG] Updating Cloudflare Access Application from struct: %+v", updatedAccessApplication) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Access Application from struct: %+v", updatedAccessApplication)) identifier, err := initIdentifier(d) if err != nil { @@ -200,7 +200,7 @@ func resourceCloudflareAccessApplicationDelete(ctx context.Context, d *schema.Re client := meta.(*cloudflare.API) appID := d.Id() - log.Printf("[DEBUG] Deleting Cloudflare Access Application using ID: %s", appID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Access Application using ID: %s", appID)) identifier, err := initIdentifier(d) if err != nil { @@ -233,7 +233,7 @@ func resourceCloudflareAccessApplicationImport(ctx context.Context, d *schema.Re accountID, accessApplicationID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Access Application: id %s for account %s", accessApplicationID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access Application: id %s for account %s", accessApplicationID, accountID)) d.Set("account_id", accountID) d.SetId(accessApplicationID) diff --git a/internal/provider/resource_cloudflare_access_bookmark.go b/internal/provider/resource_cloudflare_access_bookmark.go index 07fe2574747..29c060786a6 100644 --- a/internal/provider/resource_cloudflare_access_bookmark.go +++ b/internal/provider/resource_cloudflare_access_bookmark.go @@ -4,10 +4,10 @@ import ( "context" "errors" "fmt" - "log" "strings" 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" ) @@ -35,7 +35,7 @@ func resourceCloudflareAccessBookmarkCreate(ctx context.Context, d *schema.Resou AppLauncherVisible: d.Get("app_launcher_visible").(bool), } - log.Printf("[DEBUG] Creating Cloudflare Access Bookmark from struct: %+v", newAccessBookmark) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Access Bookmark from struct: %+v", newAccessBookmark)) identifier, err := initIdentifier(d) if err != nil { @@ -74,7 +74,7 @@ func resourceCloudflareAccessBookmarkRead(ctx context.Context, d *schema.Resourc if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access Bookmark %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Bookmark %s no longer exists", d.Id())) d.SetId("") return nil } @@ -100,7 +100,7 @@ func resourceCloudflareAccessBookmarkUpdate(ctx context.Context, d *schema.Resou AppLauncherVisible: d.Get("app_launcher_visible").(bool), } - log.Printf("[DEBUG] Updating Cloudflare Access Bookmark from struct: %+v", updatedAccessBookmark) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Access Bookmark from struct: %+v", updatedAccessBookmark)) identifier, err := initIdentifier(d) if err != nil { @@ -128,7 +128,7 @@ func resourceCloudflareAccessBookmarkDelete(ctx context.Context, d *schema.Resou client := meta.(*cloudflare.API) bookmarkID := d.Id() - log.Printf("[DEBUG] Deleting Cloudflare Access Bookmark using ID: %s", bookmarkID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Access Bookmark using ID: %s", bookmarkID)) identifier, err := initIdentifier(d) if err != nil { @@ -161,7 +161,7 @@ func resourceCloudflareAccessBookmarkImport(ctx context.Context, d *schema.Resou accountID, accessBookmarkID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Access Bookmark: id %s for account %s", accessBookmarkID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access Bookmark: id %s for account %s", accessBookmarkID, accountID)) d.Set("account_id", accountID) d.SetId(accessBookmarkID) diff --git a/internal/provider/resource_cloudflare_access_ca_certificate.go b/internal/provider/resource_cloudflare_access_ca_certificate.go index 76f8ff8facf..ef1c8a26885 100644 --- a/internal/provider/resource_cloudflare_access_ca_certificate.go +++ b/internal/provider/resource_cloudflare_access_ca_certificate.go @@ -4,10 +4,10 @@ import ( "context" "errors" "fmt" - "log" "strings" 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" ) @@ -65,7 +65,7 @@ func resourceCloudflareAccessCACertificateRead(ctx context.Context, d *schema.Re if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access CA Certificate %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access CA Certificate %s no longer exists", d.Id())) d.SetId("") return nil } @@ -86,7 +86,7 @@ func resourceCloudflareAccessCACertificateDelete(ctx context.Context, d *schema. client := meta.(*cloudflare.API) applicationID := d.Get("application_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare CA Certificate using ID: %s", d.Id()) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare CA Certificate using ID: %s", d.Id())) identifier, err := initIdentifier(d) if err != nil { @@ -121,7 +121,7 @@ func resourceCloudflareAccessCACertificateImport(ctx context.Context, d *schema. return nil, fmt.Errorf("invalid id (\"%s\") specified, should be in format \"account/accountID/accessCACertificateID\" or \"zone/zoneID/accessCACertificateID\"", d.Id()) } - log.Printf("[DEBUG] Importing Cloudflare Access CA Certificate: id %s for %s %s", accessCACertificateID, identifierType, identifierID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access CA Certificate: id %s for %s %s", accessCACertificateID, identifierType, identifierID)) //lintignore:R001 d.Set(fmt.Sprintf("%s_id", identifierType), identifierID) diff --git a/internal/provider/resource_cloudflare_access_group.go b/internal/provider/resource_cloudflare_access_group.go index 7f46754afec..e3543555d2f 100644 --- a/internal/provider/resource_cloudflare_access_group.go +++ b/internal/provider/resource_cloudflare_access_group.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -41,7 +41,7 @@ func resourceCloudflareAccessGroupRead(ctx context.Context, d *schema.ResourceDa if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access Group %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Group %s no longer exists", d.Id())) d.SetId("") return nil } @@ -50,15 +50,15 @@ func resourceCloudflareAccessGroupRead(ctx context.Context, d *schema.ResourceDa d.Set("name", accessGroup.Name) - if err := d.Set("require", TransformAccessGroupForSchema(accessGroup.Require)); err != nil { + if err := d.Set("require", TransformAccessGroupForSchema(ctx, accessGroup.Require)); err != nil { return diag.FromErr(fmt.Errorf("failed to set require attribute: %w", err)) } - if err := d.Set("exclude", TransformAccessGroupForSchema(accessGroup.Exclude)); err != nil { + if err := d.Set("exclude", TransformAccessGroupForSchema(ctx, accessGroup.Exclude)); err != nil { return diag.FromErr(fmt.Errorf("failed to set exclude attribute: %w", err)) } - if err := d.Set("include", TransformAccessGroupForSchema(accessGroup.Include)); err != nil { + if err := d.Set("include", TransformAccessGroupForSchema(ctx, accessGroup.Include)); err != nil { return diag.FromErr(fmt.Errorf("failed to set include attribute: %w", err)) } @@ -73,7 +73,7 @@ func resourceCloudflareAccessGroupCreate(ctx context.Context, d *schema.Resource newAccessGroup = appendConditionalAccessGroupFields(newAccessGroup, d) - log.Printf("[DEBUG] Creating Cloudflare Access Group from struct: %+v", newAccessGroup) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Access Group from struct: %+v", newAccessGroup)) identifier, err := initIdentifier(d) if err != nil { @@ -103,7 +103,7 @@ func resourceCloudflareAccessGroupUpdate(ctx context.Context, d *schema.Resource updatedAccessGroup = appendConditionalAccessGroupFields(updatedAccessGroup, d) - log.Printf("[DEBUG] Updating Cloudflare Access Group from struct: %+v", updatedAccessGroup) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Access Group from struct: %+v", updatedAccessGroup)) identifier, err := initIdentifier(d) if err != nil { @@ -130,7 +130,7 @@ func resourceCloudflareAccessGroupUpdate(ctx context.Context, d *schema.Resource func resourceCloudflareAccessGroupDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[DEBUG] Deleting Cloudflare Access Group using ID: %s", d.Id()) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Access Group using ID: %s", d.Id())) identifier, err := initIdentifier(d) if err != nil { @@ -160,7 +160,7 @@ func resourceCloudflareAccessGroupImport(ctx context.Context, d *schema.Resource accountID, accessGroupID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Access Group: accountID %q, accessGroupID %q", accountID, accessGroupID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access Group: accountID %q, accessGroupID %q", accountID, accessGroupID)) d.Set("account_id", accountID) d.SetId(accessGroupID) @@ -354,7 +354,7 @@ func BuildAccessGroupCondition(options map[string]interface{}) []interface{} { // TransformAccessGroupForSchema takes the incoming `accessGroup` from the API // response and converts it to a usable schema for the conditions. -func TransformAccessGroupForSchema(accessGroup []interface{}) []map[string]interface{} { +func TransformAccessGroupForSchema(ctx context.Context, accessGroup []interface{}) []map[string]interface{} { data := []map[string]interface{}{} emails := []string{} emailDomains := []string{} @@ -449,7 +449,7 @@ func TransformAccessGroupForSchema(accessGroup []interface{}) []map[string]inter devicePostureRuleIDs = append(devicePostureRuleIDs, dprID.(string)) } default: - log.Printf("[DEBUG] Access Group key %q not transformed", groupKey) + tflog.Debug(ctx, fmt.Sprintf("Access Group key %q not transformed", groupKey)) } } } diff --git a/internal/provider/resource_cloudflare_access_group_test.go b/internal/provider/resource_cloudflare_access_group_test.go index d87cc71452c..2134fa5d7d5 100644 --- a/internal/provider/resource_cloudflare_access_group_test.go +++ b/internal/provider/resource_cloudflare_access_group_test.go @@ -8,6 +8,7 @@ import ( "testing" cloudflare "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -20,16 +21,18 @@ func init() { } func testSweepCloudflareAccessGroups(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)) } // Zone level Access Groups zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") zoneAccessGroups, _, err := client.ZoneLevelAccessGroups(context.Background(), zoneID, cloudflare.PaginationOptions{}) if err != nil { - log.Printf("[ERROR] Failed to fetch zone level Access Groups: %s", err) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch zone level Access Groups: %s", err)) } if len(zoneAccessGroups) == 0 { @@ -39,7 +42,7 @@ func testSweepCloudflareAccessGroups(r string) error { for _, accessGroup := range zoneAccessGroups { if err := client.DeleteZoneLevelAccessGroup(context.Background(), zoneID, accessGroup.ID); err != nil { - log.Printf("[ERROR] Failed to delete zone level Access Group %s", accessGroup.ID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete zone level Access Group %s", accessGroup.ID)) } } @@ -47,7 +50,7 @@ func testSweepCloudflareAccessGroups(r string) error { accountID := os.Getenv("CLOUDFLARE_ACCOUNT_ID") accountAccessGroups, _, err := client.AccessGroups(context.Background(), accountID, cloudflare.PaginationOptions{}) if err != nil { - log.Printf("[ERROR] Failed to fetch account level Access Groups: %s", err) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch account level Access Groups: %s", err)) } if len(accountAccessGroups) == 0 { @@ -57,7 +60,7 @@ func testSweepCloudflareAccessGroups(r string) error { for _, accessGroup := range accountAccessGroups { if err := client.DeleteAccessGroup(context.Background(), accountID, accessGroup.ID); err != nil { - log.Printf("[ERROR] Failed to delete account level Access Group %s", accessGroup.ID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete account level Access Group %s", accessGroup.ID)) } } diff --git a/internal/provider/resource_cloudflare_access_identity_provider.go b/internal/provider/resource_cloudflare_access_identity_provider.go index c38adb87a20..b08b665486d 100644 --- a/internal/provider/resource_cloudflare_access_identity_provider.go +++ b/internal/provider/resource_cloudflare_access_identity_provider.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -42,7 +42,7 @@ func resourceCloudflareAccessIdentityProviderRead(ctx context.Context, d *schema } if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access Identity Provider %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Identity Provider %s no longer exists", d.Id())) d.SetId("") return nil } @@ -72,7 +72,7 @@ func resourceCloudflareAccessIdentityProviderCreate(ctx context.Context, d *sche Config: IDPConfig, } - log.Printf("[DEBUG] Creating Cloudflare Access Identity Provider from struct: %+v", identityProvider) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Access Identity Provider from struct: %+v", identityProvider)) identifier, err := initIdentifier(d) if err != nil { @@ -102,14 +102,14 @@ func resourceCloudflareAccessIdentityProviderUpdate(ctx context.Context, d *sche return diag.FromErr(fmt.Errorf("failed to convert schema into struct: %w", conversionErr)) } - log.Printf("[DEBUG] updatedConfig: %+v", IDPConfig) + tflog.Debug(ctx, fmt.Sprintf("updatedConfig: %+v", IDPConfig)) updatedAccessIdentityProvider := cloudflare.AccessIdentityProvider{ Name: d.Get("name").(string), Type: d.Get("type").(string), Config: IDPConfig, } - log.Printf("[DEBUG] Updating Cloudflare Access Identity Provider from struct: %+v", updatedAccessIdentityProvider) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Access Identity Provider from struct: %+v", updatedAccessIdentityProvider)) identifier, err := initIdentifier(d) if err != nil { @@ -136,7 +136,7 @@ func resourceCloudflareAccessIdentityProviderUpdate(ctx context.Context, d *sche func resourceCloudflareAccessIdentityProviderDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[DEBUG] Deleting Cloudflare Access Identity Provider using ID: %s", d.Id()) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Access Identity Provider using ID: %s", d.Id())) identifier, err := initIdentifier(d) if err != nil { @@ -166,7 +166,7 @@ func resourceCloudflareAccessIdentityProviderImport(ctx context.Context, d *sche accountID, accessIdentityProviderID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Access Identity Provider: accountID=%s accessIdentityProviderID=%s", accountID, accessIdentityProviderID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access Identity Provider: accountID=%s accessIdentityProviderID=%s", accountID, accessIdentityProviderID)) d.Set("account_id", accountID) d.SetId(accessIdentityProviderID) diff --git a/internal/provider/resource_cloudflare_access_identity_provider_test.go b/internal/provider/resource_cloudflare_access_identity_provider_test.go index 88e9d3fc78a..80a61537ec1 100644 --- a/internal/provider/resource_cloudflare_access_identity_provider_test.go +++ b/internal/provider/resource_cloudflare_access_identity_provider_test.go @@ -7,6 +7,7 @@ import ( "os" "testing" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -18,15 +19,16 @@ func init() { } func testSweepCloudflareAccessIdentityProviders(r string) error { + ctx := context.Background() accountID := os.Getenv("CLOUDFLARE_ACCOUNT_ID") 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)) } accessIDPs, accessIDPsErr := client.AccessIdentityProviders(context.Background(), accountID) if accessIDPsErr != nil { - log.Printf("[ERROR] Failed to fetch Access Identity Providers: %s", accessIDPsErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Access Identity Providers: %s", accessIDPsErr)) } if len(accessIDPs) == 0 { @@ -35,11 +37,11 @@ func testSweepCloudflareAccessIdentityProviders(r string) error { } for _, idp := range accessIDPs { - log.Printf("[INFO] Deleting Access Identity Provider ID: %s", idp.ID) + tflog.Info(ctx, fmt.Sprintf("Deleting Access Identity Provider ID: %s", idp.ID)) _, err := client.DeleteAccessIdentityProvider(context.Background(), accountID, idp.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Access Identity Provider (%s): %s", idp.ID, err) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Access Identity Provider (%s): %s", idp.ID, err)) } } diff --git a/internal/provider/resource_cloudflare_access_keys_configuration.go b/internal/provider/resource_cloudflare_access_keys_configuration.go index 5616f739d45..4c725d0804b 100644 --- a/internal/provider/resource_cloudflare_access_keys_configuration.go +++ b/internal/provider/resource_cloudflare_access_keys_configuration.go @@ -4,9 +4,9 @@ import ( "context" "errors" "fmt" - "log" 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" ) @@ -33,7 +33,7 @@ func resourceCloudflareAccessKeysConfigurationRead(ctx context.Context, d *schem var requestError *cloudflare.RequestError if errors.As(err, &requestError) { if sliceContainsInt(requestError.ErrorCodes(), 12109) { - log.Printf("[INFO] Access Keys Configuration not enabled for account %s", accountID) + tflog.Info(ctx, fmt.Sprintf("Access Keys Configuration not enabled for account %s", accountID)) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_access_mutual_tls_certificate.go b/internal/provider/resource_cloudflare_access_mutual_tls_certificate.go index 20bf6bb86c9..503a2a1f7de 100644 --- a/internal/provider/resource_cloudflare_access_mutual_tls_certificate.go +++ b/internal/provider/resource_cloudflare_access_mutual_tls_certificate.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -34,7 +34,7 @@ func resourceCloudflareAccessMutualTLSCertificateCreate(ctx context.Context, d * } newAccessMutualTLSCertificate.AssociatedHostnames = expandInterfaceToStringList(d.Get("associated_hostnames")) - log.Printf("[DEBUG] Creating Cloudflare Access Mutual TLS certificate from struct: %+v", newAccessMutualTLSCertificate) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Access Mutual TLS certificate from struct: %+v", newAccessMutualTLSCertificate)) identifier, err := initIdentifier(d) if err != nil { @@ -73,7 +73,7 @@ func resourceCloudflareAccessMutualTLSCertificateRead(ctx context.Context, d *sc if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access Mutal TLS Certificate %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Mutal TLS Certificate %s no longer exists", d.Id())) d.SetId("") return nil } @@ -96,7 +96,7 @@ func resourceCloudflareAccessMutualTLSCertificateUpdate(ctx context.Context, d * } updatedAccessMutualTLSCert.AssociatedHostnames = expandInterfaceToStringList(d.Get("associated_hostnames")) - log.Printf("[DEBUG] Updating Cloudflare Access Mutal TLS Certificate from struct: %+v", updatedAccessMutualTLSCert) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Access Mutal TLS Certificate from struct: %+v", updatedAccessMutualTLSCert)) identifier, err := initIdentifier(d) if err != nil { @@ -119,7 +119,7 @@ func resourceCloudflareAccessMutualTLSCertificateDelete(ctx context.Context, d * client := meta.(*cloudflare.API) certID := d.Id() - log.Printf("[DEBUG] Deleting Cloudflare Access Mutual TLS Certificate using ID: %s", certID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Access Mutual TLS Certificate using ID: %s", certID)) identifier, err := initIdentifier(d) if err != nil { @@ -185,7 +185,7 @@ func resourceCloudflareAccessMutualTLSCertificateImport(ctx context.Context, d * return nil, fmt.Errorf("invalid id (\"%s\") specified, should be in format \"account/accountID/accessMutualTLSCertificateID\" or \"zone/zoneID/accessMutualTLSCertificateID\"", d.Id()) } - log.Printf("[DEBUG] Importing Cloudflare Access Mutual TLS Certificate: id %s for %s %s", accessMutualTLSCertificateID, identifierType, identifierID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access Mutual TLS Certificate: id %s for %s %s", accessMutualTLSCertificateID, identifierType, identifierID)) //lintignore:R001 d.Set(fmt.Sprintf("%s_id", identifierType), identifierID) diff --git a/internal/provider/resource_cloudflare_access_mutual_tls_certificate_test.go b/internal/provider/resource_cloudflare_access_mutual_tls_certificate_test.go index c51e2938622..97593b44fba 100644 --- a/internal/provider/resource_cloudflare_access_mutual_tls_certificate_test.go +++ b/internal/provider/resource_cloudflare_access_mutual_tls_certificate_test.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "os" "testing" "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -20,37 +20,39 @@ func init() { } func testSweepCloudflareAccessMutualTLSCertificate(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") accountCerts, err := client.AccessMutualTLSCertificates(context.Background(), accountID) if err != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare Access Mutual TLS certificates: %s", err) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare Access Mutual TLS certificates: %s", err)) } for _, cert := range accountCerts { err := client.DeleteAccessMutualTLSCertificate(context.Background(), accountID, cert.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare Access Mutual TLS certificate (%s) in account ID: %s", cert.ID, accountID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare Access Mutual TLS certificate (%s) in account ID: %s", cert.ID, accountID)) } } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") zoneCerts, err := client.ZoneAccessMutualTLSCertificates(context.Background(), zoneID) if err != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare Access Mutual TLS certificates: %s", err) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare Access Mutual TLS certificates: %s", err)) } for _, cert := range zoneCerts { err := client.DeleteZoneAccessMutualTLSCertificate(context.Background(), zoneID, cert.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare Access Mutual TLS certificate (%s) in zone ID: %s", cert.ID, zoneID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare Access Mutual TLS certificate (%s) in zone ID: %s", cert.ID, zoneID)) } } diff --git a/internal/provider/resource_cloudflare_access_policy.go b/internal/provider/resource_cloudflare_access_policy.go index bf74dee703b..025773b87f9 100644 --- a/internal/provider/resource_cloudflare_access_policy.go +++ b/internal/provider/resource_cloudflare_access_policy.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" ) @@ -68,7 +68,7 @@ func resourceCloudflareAccessPolicyRead(ctx context.Context, d *schema.ResourceD } if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access Policy %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Policy %s no longer exists", d.Id())) d.SetId("") return nil } @@ -79,15 +79,15 @@ func resourceCloudflareAccessPolicyRead(ctx context.Context, d *schema.ResourceD d.Set("decision", accessPolicy.Decision) d.Set("precedence", accessPolicy.Precedence) - if err := d.Set("require", TransformAccessGroupForSchema(accessPolicy.Require)); err != nil { + if err := d.Set("require", TransformAccessGroupForSchema(ctx, accessPolicy.Require)); err != nil { return diag.FromErr(fmt.Errorf("failed to set require attribute: %w", err)) } - if err := d.Set("exclude", TransformAccessGroupForSchema(accessPolicy.Exclude)); err != nil { + if err := d.Set("exclude", TransformAccessGroupForSchema(ctx, accessPolicy.Exclude)); err != nil { return diag.FromErr(fmt.Errorf("failed to set exclude attribute: %w", err)) } - if err := d.Set("include", TransformAccessGroupForSchema(accessPolicy.Include)); err != nil { + if err := d.Set("include", TransformAccessGroupForSchema(ctx, accessPolicy.Include)); err != nil { return diag.FromErr(fmt.Errorf("failed to set include attribute: %w", err)) } @@ -127,7 +127,7 @@ func resourceCloudflareAccessPolicyCreate(ctx context.Context, d *schema.Resourc newAccessPolicy = appendConditionalAccessPolicyFields(newAccessPolicy, d) - log.Printf("[DEBUG] Creating Cloudflare Access Policy from struct: %+v", newAccessPolicy) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Access Policy from struct: %+v", newAccessPolicy)) identifier, err := initIdentifier(d) if err != nil { @@ -161,7 +161,7 @@ func resourceCloudflareAccessPolicyUpdate(ctx context.Context, d *schema.Resourc updatedAccessPolicy = appendConditionalAccessPolicyFields(updatedAccessPolicy, d) - log.Printf("[DEBUG] Updating Cloudflare Access Policy from struct: %+v", updatedAccessPolicy) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Access Policy from struct: %+v", updatedAccessPolicy)) identifier, err := initIdentifier(d) if err != nil { @@ -189,7 +189,7 @@ func resourceCloudflareAccessPolicyDelete(ctx context.Context, d *schema.Resourc client := meta.(*cloudflare.API) appID := d.Get("application_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare Access Policy using ID: %s", d.Id()) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Access Policy using ID: %s", d.Id())) identifier, err := initIdentifier(d) if err != nil { @@ -224,7 +224,7 @@ func resourceCloudflareAccessPolicyImport(ctx context.Context, d *schema.Resourc identifierType, identifierID, accessAppID, accessPolicyID := attributes[0], attributes[1], attributes[2], attributes[3] - log.Printf("[DEBUG] Importing Cloudflare Access Policy: %s %q, appID %q, accessPolicyID %q", identifierType, identifierID, accessAppID, accessPolicyID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Access Policy: %s %q, appID %q, accessPolicyID %q", identifierType, identifierID, accessAppID, accessPolicyID)) //lintignore:R001 d.Set(fmt.Sprintf("%s_id", identifierType), identifierID) diff --git a/internal/provider/resource_cloudflare_access_rule.go b/internal/provider/resource_cloudflare_access_rule.go index 91ecd0f2147..f37a12c17f3 100644 --- a/internal/provider/resource_cloudflare_access_rule.go +++ b/internal/provider/resource_cloudflare_access_rule.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "net" "strings" 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" ) @@ -96,24 +96,24 @@ func resourceCloudflareAccessRuleRead(ctx context.Context, d *schema.ResourceDat accessRuleResponse, err = client.ZoneAccessRule(ctx, zoneID, d.Id()) } - log.Printf("[DEBUG] accessRuleResponse: %#v", accessRuleResponse) - log.Printf("[DEBUG] accessRuleResponse error: %#v", err) + tflog.Debug(ctx, fmt.Sprintf("accessRuleResponse: %#v", accessRuleResponse)) + tflog.Debug(ctx, fmt.Sprintf("accessRuleResponse error: %#v", err)) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Access Rule %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Access Rule %s no longer exists", d.Id())) d.SetId("") return nil } return diag.FromErr(fmt.Errorf("error finding access rule %q: %w", d.Id(), err)) } - log.Printf("[DEBUG] Cloudflare Access Rule read configuration: %#v", accessRuleResponse) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Access Rule read configuration: %#v", accessRuleResponse)) d.Set("zone_id", zoneID) d.Set("mode", accessRuleResponse.Result.Mode) d.Set("notes", accessRuleResponse.Result.Notes) - log.Printf("[DEBUG] read configuration: %#v", d.Get("configuration")) + tflog.Debug(ctx, fmt.Sprintf("read configuration: %#v", d.Get("configuration"))) configuration := []map[string]interface{}{} configuration = append(configuration, map[string]interface{}{ @@ -168,7 +168,7 @@ func resourceCloudflareAccessRuleDelete(ctx context.Context, d *schema.ResourceD client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Deleting Cloudflare Access Rule: id %s for zone_id %s", d.Id(), zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Access Rule: id %s for zone_id %s", d.Id(), zoneID)) var err error diff --git a/internal/provider/resource_cloudflare_account_member.go b/internal/provider/resource_cloudflare_account_member.go index f9e3d4e4139..effe5ea0c23 100644 --- a/internal/provider/resource_cloudflare_account_member.go +++ b/internal/provider/resource_cloudflare_account_member.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -31,7 +31,7 @@ func resourceCloudflareAccountMemberRead(ctx context.Context, d *schema.Resource if err != nil { if strings.Contains(err.Error(), "Member not found") || strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[WARN] Removing account member from state because it's not present in API") + tflog.Warn(ctx, fmt.Sprintf("Removing account member from state because it's not present in API")) d.SetId("") return nil } @@ -53,7 +53,7 @@ func resourceCloudflareAccountMemberRead(ctx context.Context, d *schema.Resource func resourceCloudflareAccountMemberDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting Cloudflare account member ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare account member ID: %s", d.Id())) err := client.DeleteAccountMember(ctx, client.AccountID, d.Id()) if err != nil { @@ -127,7 +127,7 @@ func resourceCloudflareAccountMemberImport(ctx context.Context, d *schema.Resour return nil, fmt.Errorf("unable to find account member with ID %q: %w", accountMemberID, err) } - log.Printf("[INFO] Found account member: %s", member.User.Email) + tflog.Info(ctx, fmt.Sprintf("Found account member: %s", member.User.Email)) var memberIDs []string for _, role := range member.Roles { diff --git a/internal/provider/resource_cloudflare_api_token.go b/internal/provider/resource_cloudflare_api_token.go index 4e275850cc8..ead18341712 100644 --- a/internal/provider/resource_cloudflare_api_token.go +++ b/internal/provider/resource_cloudflare_api_token.go @@ -4,11 +4,11 @@ import ( "context" "encoding/json" "fmt" - "log" "strings" "time" "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" ) @@ -64,7 +64,7 @@ func resourceCloudflareApiTokenCreate(ctx context.Context, d *schema.ResourceDat name := d.Get("name").(string) - log.Printf("[INFO] Creating Cloudflare API Token: name %s", name) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare API Token: name %s", name)) t := buildAPIToken(d) t, err := client.CreateAPIToken(ctx, t) @@ -124,11 +124,11 @@ func resourceCloudflareApiTokenRead(ctx context.Context, d *schema.ResourceData, t, err := client.GetAPIToken(ctx, tokenID) - log.Printf("[DEBUG] Cloudflare API Token: %+v", t) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare API Token: %+v", t)) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Cloudflare API Token %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare API Token %s no longer exists", d.Id())) d.SetId("") return nil } @@ -186,7 +186,7 @@ func resourceCloudflareApiTokenUpdate(ctx context.Context, d *schema.ResourceDat t := buildAPIToken(d) - log.Printf("[INFO] Updating Cloudflare API Token: name %s", name) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare API Token: name %s", name)) t, err := client.UpdateAPIToken(ctx, tokenID, t) if err != nil { @@ -200,7 +200,7 @@ func resourceCloudflareApiTokenDelete(ctx context.Context, d *schema.ResourceDat client := meta.(*cloudflare.API) tokenID := d.Id() - log.Printf("[INFO] Deleting Cloudflare API Token: id %s", tokenID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare API Token: id %s", tokenID)) err := client.DeleteAPIToken(ctx, tokenID) if err != nil { diff --git a/internal/provider/resource_cloudflare_argo.go b/internal/provider/resource_cloudflare_argo.go index 3d2bdd419c9..6e4fa78192f 100644 --- a/internal/provider/resource_cloudflare_argo.go +++ b/internal/provider/resource_cloudflare_argo.go @@ -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" "github.com/pkg/errors" @@ -30,7 +30,7 @@ func resourceCloudflareArgoRead(ctx context.Context, d *schema.ResourceData, met tieredCaching := d.Get("tiered_caching").(string) smartRouting := d.Get("smart_routing").(string) - log.Printf("[DEBUG] zone ID: %s", zoneID) + tflog.Debug(ctx, fmt.Sprintf("zone ID: %s", zoneID)) checksum := stringChecksum(fmt.Sprintf("%s/argo", zoneID)) d.SetId(checksum) @@ -68,7 +68,7 @@ func resourceCloudflareArgoUpdate(ctx context.Context, d *schema.ResourceData, m if err != nil { return diag.FromErr(errors.Wrap(err, "failed to update smart routing setting")) } - log.Printf("[DEBUG] Argo Smart Routing set to: %s", argoSmartRouting.Value) + tflog.Debug(ctx, fmt.Sprintf("Argo Smart Routing set to: %s", argoSmartRouting.Value)) } if tieredCaching != "" { @@ -76,7 +76,7 @@ func resourceCloudflareArgoUpdate(ctx context.Context, d *schema.ResourceData, m if err != nil { return diag.FromErr(errors.Wrap(err, "failed to update tiered caching setting")) } - log.Printf("[DEBUG] Argo Tiered Caching set to: %s", argoTieredCaching.Value) + tflog.Debug(ctx, fmt.Sprintf("Argo Tiered Caching set to: %s", argoTieredCaching.Value)) } return resourceCloudflareArgoRead(ctx, d, meta) @@ -86,7 +86,7 @@ func resourceCloudflareArgoDelete(ctx context.Context, d *schema.ResourceData, m client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[DEBUG] Resetting Argo values to 'off'") + tflog.Debug(ctx, fmt.Sprintf("Resetting Argo values to 'off'")) _, smartRoutingErr := client.UpdateArgoSmartRouting(ctx, zoneID, "off") if smartRoutingErr != nil { diff --git a/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate.go b/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate.go index 15593970fe0..82400c020d4 100644 --- a/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate.go +++ b/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "strings" "time" "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/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -110,7 +110,7 @@ func resourceCloudflareAuthenticatedOriginPullsCertificateRead(ctx context.Conte record, err := client.GetPerZoneAuthenticatedOriginPullsCertificateDetails(ctx, zoneID, certID) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Per-Zone Authenticated Origin Pull certificate %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Per-Zone Authenticated Origin Pull certificate %s no longer exists", d.Id())) d.SetId("") return nil } @@ -125,7 +125,7 @@ func resourceCloudflareAuthenticatedOriginPullsCertificateRead(ctx context.Conte record, err := client.GetPerHostnameAuthenticatedOriginPullsCertificate(ctx, zoneID, certID) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Per-Hostname Authenticated Origin Pull certificate %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Per-Hostname Authenticated Origin Pull certificate %s no longer exists", d.Id())) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate_test.go b/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate_test.go index 2ab7e3e4ce4..32ae11d56a1 100644 --- a/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate_test.go +++ b/internal/provider/resource_cloudflare_authenticated_origin_pulls_certificate_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -20,16 +21,17 @@ func init() { } func testSweepCloudflareAuthenticatdOriginPullsCertificates(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") perZoneCertificates, certsErr := client.ListPerZoneAuthenticatedOriginPullsCertificates(context.Background(), zoneID) if certsErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare authenticated origin pull certificates: %s", certsErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare authenticated origin pull certificates: %s", certsErr)) } if len(perZoneCertificates) == 0 { @@ -41,7 +43,7 @@ func testSweepCloudflareAuthenticatdOriginPullsCertificates(r string) error { _, err := client.DeletePerZoneAuthenticatedOriginPullsCertificate(context.Background(), zoneID, certificate.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare authenticated origin pull certificate (%s) in zone ID: %s", certificate.ID, zoneID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare authenticated origin pull certificate (%s) in zone ID: %s", certificate.ID, zoneID)) } } diff --git a/internal/provider/resource_cloudflare_certificate_pack.go b/internal/provider/resource_cloudflare_certificate_pack.go index ae7b05afac8..b003ef49caa 100644 --- a/internal/provider/resource_cloudflare_certificate_pack.go +++ b/internal/provider/resource_cloudflare_certificate_pack.go @@ -3,12 +3,12 @@ package provider import ( "context" "fmt" - "log" "reflect" "strings" "time" 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/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -154,7 +154,7 @@ func resourceCloudflareCertificatePackImport(ctx context.Context, d *schema.Reso zoneID, certificatePackID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Certificate Pack: id %s for zone %s", certificatePackID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Certificate Pack: id %s for zone %s", certificatePackID, zoneID)) d.Set("zone_id", zoneID) d.SetId(certificatePackID) diff --git a/internal/provider/resource_cloudflare_certificate_pack_test.go b/internal/provider/resource_cloudflare_certificate_pack_test.go index 46c8d231cc0..367f22ec37b 100644 --- a/internal/provider/resource_cloudflare_certificate_pack_test.go +++ b/internal/provider/resource_cloudflare_certificate_pack_test.go @@ -7,6 +7,7 @@ import ( "os" "testing" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -18,15 +19,16 @@ func init() { } func testSweepCloudflareCertificatePack(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") certificates, certErr := client.ListCertificatePacks(context.Background(), zoneID) if certErr != nil { - log.Printf("[ERROR] Failed to fetch certificate packs: %s", clientErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch certificate packs: %s", clientErr)) } if len(certificates) == 0 { @@ -36,7 +38,7 @@ func testSweepCloudflareCertificatePack(r string) error { for _, certificate := range certificates { if err := client.DeleteCertificatePack(context.Background(), zoneID, certificate.ID); err != nil { - log.Printf("[ERROR] Failed to delete certificate pack %s", certificate.ID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete certificate pack %s", certificate.ID)) } } diff --git a/internal/provider/resource_cloudflare_custom_hostname.go b/internal/provider/resource_cloudflare_custom_hostname.go index caa801451f8..d8558aeff5d 100644 --- a/internal/provider/resource_cloudflare_custom_hostname.go +++ b/internal/provider/resource_cloudflare_custom_hostname.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "reflect" "strings" "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/pkg/errors" @@ -160,7 +160,7 @@ func resourceCloudflareCustomHostnameImport(ctx context.Context, d *schema.Resou zoneID, hostnameID := idAttr[0], idAttr[1] - log.Printf("[DEBUG] Importing Cloudflare Custom Hostname: id %s for zone %s", hostnameID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Custom Hostname: id %s for zone %s", hostnameID, zoneID)) d.Set("zone_id", zoneID) d.SetId(hostnameID) diff --git a/internal/provider/resource_cloudflare_custom_hostname_fallback_origin.go b/internal/provider/resource_cloudflare_custom_hostname_fallback_origin.go index 5c84f5989a8..314b3aca900 100644 --- a/internal/provider/resource_cloudflare_custom_hostname_fallback_origin.go +++ b/internal/provider/resource_cloudflare_custom_hostname_fallback_origin.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -139,7 +139,7 @@ func resourceCloudflareCustomHostnameFallbackOriginImport(ctx context.Context, d zoneID, origin := idAttr[0], idAttr[1] - log.Printf("[DEBUG] Importing Cloudflare Custom Hostname Fallback Origin: origin %s for zone %s", origin, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Custom Hostname Fallback Origin: origin %s for zone %s", origin, zoneID)) d.Set("zone_id", zoneID) d.Set("origin", origin) diff --git a/internal/provider/resource_cloudflare_custom_hostname_test.go b/internal/provider/resource_cloudflare_custom_hostname_test.go index 8da46b9ff87..e6f93657012 100644 --- a/internal/provider/resource_cloudflare_custom_hostname_test.go +++ b/internal/provider/resource_cloudflare_custom_hostname_test.go @@ -8,6 +8,7 @@ import ( "testing" cloudflare "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/pkg/errors" @@ -21,9 +22,11 @@ func init() { } func testSweepCloudflareCustomHostnames(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") @@ -33,7 +36,7 @@ func testSweepCloudflareCustomHostnames(r string) error { hostnames, _, hostnamesErr := client.CustomHostnames(context.Background(), zoneID, 1, cloudflare.CustomHostname{}) if hostnamesErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare custom hostnames: %s", hostnamesErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare custom hostnames: %s", hostnamesErr)) } if len(hostnames) == 0 { @@ -42,11 +45,11 @@ func testSweepCloudflareCustomHostnames(r string) error { } for _, hostname := range hostnames { - log.Printf("[INFO] Deleting Cloudflare custom hostname: %s", hostname.ID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare custom hostname: %s", hostname.ID)) err := client.DeleteCustomHostname(context.Background(), zoneID, hostname.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare custom hostname (%s): %s", hostname.Hostname, err) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare custom hostname (%s): %s", hostname.Hostname, err)) } } diff --git a/internal/provider/resource_cloudflare_custom_ssl.go b/internal/provider/resource_cloudflare_custom_ssl.go index 2799a11cc26..197867cc984 100644 --- a/internal/provider/resource_cloudflare_custom_ssl.go +++ b/internal/provider/resource_cloudflare_custom_ssl.go @@ -4,10 +4,10 @@ import ( "context" "encoding/json" "fmt" - "log" "strings" "time" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -43,8 +43,8 @@ func resourceCloudflareCustomSsl() *schema.Resource { func resourceCloudflareCustomSslCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[DEBUG] zone ID: %s", zoneID) - zcso, err := expandToZoneCustomSSLOptions(d) + tflog.Debug(ctx, fmt.Sprintf("zone ID: %s", zoneID)) + zcso, err := expandToZoneCustomSSLOptions(ctx, d) if err != nil { return diag.FromErr(fmt.Errorf("failed to create custom ssl cert: %w", err)) } @@ -89,35 +89,35 @@ func resourceCloudflareCustomSslUpdate(ctx context.Context, d *schema.ResourceDa var reErr error var updateErr = false var reprioritizeErr = false - log.Printf("[DEBUG] zone ID: %s", zoneID) + tflog.Debug(ctx, fmt.Sprintf("zone ID: %s", zoneID)) if d.HasChange("custom_ssl_options") { - zcso, err := expandToZoneCustomSSLOptions(d) + zcso, err := expandToZoneCustomSSLOptions(ctx, d) if err != nil { return diag.FromErr(fmt.Errorf("failed to update custom ssl cert: %w", err)) } res, uErr := client.UpdateSSL(ctx, zoneID, certID, zcso) if uErr != nil { - log.Printf("[DEBUG] Failed to update custom ssl cert: %s", uErr) + tflog.Debug(ctx, fmt.Sprintf("Failed to update custom ssl cert: %s", uErr)) updateErr = true } else { - log.Printf("[DEBUG] Custom SSL set to: %s", res.ID) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL set to: %s", res.ID)) } } if d.HasChange("custom_ssl_priority") { - zcsp, err := expandToZoneCustomSSLPriority(d) + zcsp, err := expandToZoneCustomSSLPriority(ctx, d) if err != nil { - log.Printf("Failed to update custom ssl cert: %s", err) + tflog.Debug(ctx, fmt.Sprintf("Failed to update custom ssl cert: %s", err)) } resList, reErr := client.ReprioritizeSSL(ctx, zoneID, zcsp) if err != nil { - log.Printf("Failed to update / reprioritize custom ssl cert: %s", reErr) + tflog.Debug(ctx, fmt.Sprintf("Failed to update / reprioritize custom ssl cert: %s", reErr)) reprioritizeErr = true } else { - log.Printf("[DEBUG] Custom SSL reprioritized to: %#v", resList) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL reprioritized to: %#v", resList)) } } @@ -136,13 +136,13 @@ func resourceCloudflareCustomSslRead(ctx context.Context, d *schema.ResourceData // update all possible schema attributes with fields from api response record, err := client.SSLDetails(ctx, zoneID, certID) if err != nil { - log.Printf("[WARN] Removing record from state because it's not found in API") + tflog.Warn(ctx, fmt.Sprintf("Removing record from state because it's not found in API")) d.SetId("") return nil } - zcso, err := expandToZoneCustomSSLOptions(d) + zcso, err := expandToZoneCustomSSLOptions(ctx, d) if err != nil { - log.Printf("[WARN] Problem setting zone options not read from state %s", err) + tflog.Warn(ctx, fmt.Sprintf("Problem setting zone options not read from state %s", err)) } zcso.BundleMethod = record.BundleMethod customSslOpts := flattenCustomSSLOptions(zcso) @@ -167,7 +167,7 @@ func resourceCloudflareCustomSslDelete(ctx context.Context, d *schema.ResourceDa zoneID := d.Get("zone_id").(string) certID := d.Id() - log.Printf("[DEBUG] Deleting SSL cert %s for zone %s", certID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Deleting SSL cert %s for zone %s", certID, zoneID)) err := client.DeleteSSL(ctx, zoneID, certID) if err != nil { @@ -185,7 +185,7 @@ func resourceCloudflareCustomSslImport(ctx context.Context, d *schema.ResourceDa zoneID, certID := idAttr[0], idAttr[1] - log.Printf("[DEBUG] Importing Cloudflare Custom SSL Cert: id %s for zone %s", certID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Custom SSL Cert: id %s for zone %s", certID, zoneID)) d.Set("zone_id", zoneID) d.SetId(certID) @@ -195,9 +195,9 @@ func resourceCloudflareCustomSslImport(ctx context.Context, d *schema.ResourceDa return []*schema.ResourceData{d}, nil } -func expandToZoneCustomSSLPriority(d *schema.ResourceData) ([]cloudflare.ZoneCustomSSLPriority, error) { +func expandToZoneCustomSSLPriority(ctx context.Context, d *schema.ResourceData) ([]cloudflare.ZoneCustomSSLPriority, error) { data, dataOk := d.GetOk("custom_ssl_priority") - log.Printf("[DEBUG] Custom SSL priority found in config: %#v", data) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL priority found in config: %#v", data)) var mtSlice []cloudflare.ZoneCustomSSLPriority if dataOk { for _, innerData := range data.([]interface{}) { @@ -225,13 +225,13 @@ func expandToZoneCustomSSLPriority(d *schema.ResourceData) ([]cloudflare.ZoneCus mtSlice = append(mtSlice, zcsp) } } - log.Printf("[DEBUG] Custom SSL priority list creating: %#v", mtSlice) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL priority list creating: %#v", mtSlice)) return mtSlice, nil } -func expandToZoneCustomSSLOptions(d *schema.ResourceData) (cloudflare.ZoneCustomSSLOptions, error) { +func expandToZoneCustomSSLOptions(ctx context.Context, d *schema.ResourceData) (cloudflare.ZoneCustomSSLOptions, error) { data, dataOk := d.GetOk("custom_ssl_options") - log.Printf("[DEBUG] Custom SSL options found in config: %#v", data) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL options found in config: %#v", data)) newData := make(map[string]interface{}) if dataOk { @@ -256,11 +256,11 @@ func expandToZoneCustomSSLOptions(d *schema.ResourceData) (cloudflare.ZoneCustom return zcso, fmt.Errorf("Failed to create custom ssl options: %w", err) } - log.Printf("[DEBUG] Custom SSL JSON: %s", string(zcsoJSON)) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL JSON: %s", string(zcsoJSON))) // map -> json -> struct json.Unmarshal(zcsoJSON, &zcso) - log.Printf("[DEBUG] Custom SSL options creating: %#v", zcso) + tflog.Debug(ctx, fmt.Sprintf("Custom SSL options creating: %#v", zcso)) return zcso, nil } diff --git a/internal/provider/resource_cloudflare_device_policy.go b/internal/provider/resource_cloudflare_device_policy.go index a6ff86b486f..58952a5420c 100644 --- a/internal/provider/resource_cloudflare_device_policy.go +++ b/internal/provider/resource_cloudflare_device_policy.go @@ -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" ) @@ -28,7 +28,7 @@ func resourceCloudflareDevicePolicyCertificateUpdate(ctx context.Context, d *sch zoneID := d.Get("zone_id").(string) enabled := d.Get("enabled").(bool) - log.Printf("[DEBUG] Updating Cloudflare device policy certificate: zoneID=%s enabled=%t", zoneID, enabled) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare device policy certificate: zoneID=%s enabled=%t", zoneID, enabled)) _, err := client.UpdateDeviceClientCertificatesZone(ctx, zoneID, enabled) if err != nil { @@ -56,7 +56,7 @@ func resourceCloudflareDevicePolicyCertificateRead(ctx context.Context, d *schem func resourceCloudflareDevicePolicyCertificateImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { zoneID := d.Id() - log.Printf("[DEBUG] Importing Cloudflare device policy certificate setting: zoneID=%s", zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare device policy certificate setting: zoneID=%s", zoneID)) d.SetId(zoneID) d.Set("zone_id", zoneID) diff --git a/internal/provider/resource_cloudflare_device_posture_integration.go b/internal/provider/resource_cloudflare_device_posture_integration.go index 094e1e09865..602c4509c35 100644 --- a/internal/provider/resource_cloudflare_device_posture_integration.go +++ b/internal/provider/resource_cloudflare_device_posture_integration.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" ) @@ -40,7 +40,7 @@ func resourceCloudflareDevicePostureIntegrationCreate(ctx context.Context, d *sc if err != nil { return diag.FromErr(fmt.Errorf("error creating Device Posture integration with provided config: %w", err)) } - log.Printf("[DEBUG] Creating Cloudflare Device Posture Integration from struct: %+v\n", newDevicePostureIntegration) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Device Posture Integration from struct: %+v\n", newDevicePostureIntegration)) // The API does not return the client_secret so it must be stored in the state func on resource create. savedSecret := newDevicePostureIntegration.Config.ClientSecret @@ -68,7 +68,7 @@ func devicePostureIntegrationReadHelper(ctx context.Context, d *schema.ResourceD devicePostureIntegration, err := client.DevicePostureIntegration(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Device posture integration %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Device posture integration %s no longer exists", d.Id())) d.SetId("") return nil } @@ -100,7 +100,7 @@ func resourceCloudflareDevicePostureIntegrationUpdate(ctx context.Context, d *sc return diag.FromErr(fmt.Errorf("error creating Device Posture Rule with provided match input: %w", err)) } - log.Printf("[DEBUG] Updating Cloudflare device posture integration from struct: %+v", updatedDevicePostureIntegration) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare device posture integration from struct: %+v", updatedDevicePostureIntegration)) devicePostureIntegration, err := client.UpdateDevicePostureIntegration(ctx, accountID, updatedDevicePostureIntegration) if err != nil { @@ -119,7 +119,7 @@ func resourceCloudflareDevicePostureIntegrationDelete(ctx context.Context, d *sc appID := d.Id() accountID := d.Get("account_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare device posture integration using ID: %s", appID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare device posture integration using ID: %s", appID)) err := client.DeleteDevicePostureIntegration(ctx, accountID, appID) if err != nil { @@ -140,7 +140,7 @@ func resourceCloudflareDevicePostureIntegrationImport(ctx context.Context, d *sc accountID, devicePostureIntegrationID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare device posture integration: id %s for account %s", devicePostureIntegrationID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare device posture integration: id %s for account %s", devicePostureIntegrationID, accountID)) d.Set("account_id", accountID) d.SetId(devicePostureIntegrationID) diff --git a/internal/provider/resource_cloudflare_device_posture_rule.go b/internal/provider/resource_cloudflare_device_posture_rule.go index a512404e351..0e70f28e20d 100644 --- a/internal/provider/resource_cloudflare_device_posture_rule.go +++ b/internal/provider/resource_cloudflare_device_posture_rule.go @@ -4,10 +4,10 @@ import ( "context" "encoding/json" "fmt" - "log" "strings" 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" ) @@ -43,7 +43,7 @@ func resourceCloudflareDevicePostureRuleCreate(ctx context.Context, d *schema.Re } setDevicePostureRuleInput(&newDevicePostureRule, d) - log.Printf("[DEBUG] Creating Cloudflare Device Posture Rule from struct: %+v", newDevicePostureRule) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Device Posture Rule from struct: %+v", newDevicePostureRule)) rule, err := client.CreateDevicePostureRule(ctx, accountID, newDevicePostureRule) if err != nil { @@ -62,7 +62,7 @@ func resourceCloudflareDevicePostureRuleRead(ctx context.Context, d *schema.Reso devicePostureRule, err := client.DevicePostureRule(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Device Posture Rule %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Device Posture Rule %s no longer exists", d.Id())) d.SetId("") return nil } @@ -99,7 +99,7 @@ func resourceCloudflareDevicePostureRuleUpdate(ctx context.Context, d *schema.Re } setDevicePostureRuleInput(&updatedDevicePostureRule, d) - log.Printf("[DEBUG] Updating Cloudflare Device Posture Rule from struct: %+v", updatedDevicePostureRule) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Device Posture Rule from struct: %+v", updatedDevicePostureRule)) devicePostureRule, err := client.UpdateDevicePostureRule(ctx, accountID, updatedDevicePostureRule) if err != nil { @@ -118,7 +118,7 @@ func resourceCloudflareDevicePostureRuleDelete(ctx context.Context, d *schema.Re appID := d.Id() accountID := d.Get("account_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare Device Posture Rule using ID: %s", appID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Device Posture Rule using ID: %s", appID)) err := client.DeleteDevicePostureRule(ctx, accountID, appID) if err != nil { @@ -139,7 +139,7 @@ func resourceCloudflareDevicePostureRuleImport(ctx context.Context, d *schema.Re accountID, devicePostureRuleID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Device Posture Rule: id %s for account %s", devicePostureRuleID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Device Posture Rule: id %s for account %s", devicePostureRuleID, accountID)) d.Set("account_id", accountID) d.SetId(devicePostureRuleID) diff --git a/internal/provider/resource_cloudflare_filter.go b/internal/provider/resource_cloudflare_filter.go index 188b36ca231..00ad919bf85 100644 --- a/internal/provider/resource_cloudflare_filter.go +++ b/internal/provider/resource_cloudflare_filter.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -48,7 +48,7 @@ func resourceCloudflareFilterCreate(ctx context.Context, d *schema.ResourceData, newFilter.Ref = ref.(string) } - log.Printf("[DEBUG] Creating Cloudflare Filter from struct: %+v", newFilter) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Filter from struct: %+v", newFilter)) r, err := client.CreateFilters(ctx, zoneID, []cloudflare.Filter{newFilter}) @@ -62,7 +62,7 @@ func resourceCloudflareFilterCreate(ctx context.Context, d *schema.ResourceData, d.SetId(r[0].ID) - log.Printf("[INFO] Cloudflare Filter ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Filter ID: %s", d.Id())) return resourceCloudflareFilterRead(ctx, d, meta) } @@ -71,22 +71,22 @@ func resourceCloudflareFilterRead(ctx context.Context, d *schema.ResourceData, m client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[DEBUG] Getting a Filter record for zone %q, id %s", zoneID, d.Id()) + tflog.Debug(ctx, fmt.Sprintf("Getting a Filter record for zone %q, id %s", zoneID, d.Id())) filter, err := client.Filter(ctx, zoneID, d.Id()) - log.Printf("[DEBUG] filter: %#v", filter) - log.Printf("[DEBUG] filter error: %#v", err) + tflog.Debug(ctx, fmt.Sprintf("filter: %#v", filter)) + tflog.Debug(ctx, fmt.Sprintf("filter error: %#v", err)) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Filter %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Filter %s no longer exists", d.Id())) d.SetId("") return nil } return diag.FromErr(fmt.Errorf("error finding Filter %q: %w", d.Id(), err)) } - log.Printf("[DEBUG] Cloudflare Filter read configuration: %#v", filter) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Filter read configuration: %#v", filter)) d.Set("paused", filter.Paused) d.Set("description", filter.Description) @@ -119,7 +119,7 @@ func resourceCloudflareFilterUpdate(ctx context.Context, d *schema.ResourceData, newFilter.Ref = ref.(string) } - log.Printf("[DEBUG] Updating Cloudflare Filter from struct: %+v", newFilter) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Filter from struct: %+v", newFilter)) r, err := client.UpdateFilter(ctx, zoneID, newFilter) @@ -138,7 +138,7 @@ func resourceCloudflareFilterDelete(ctx context.Context, d *schema.ResourceData, client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Deleting Cloudflare Filter: id %s for zone %s", d.Id(), zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Filter: id %s for zone %s", d.Id(), zoneID)) err := client.DeleteFilter(ctx, zoneID, d.Id()) @@ -159,7 +159,7 @@ func resourceCloudflareFilterImport(ctx context.Context, d *schema.ResourceData, zoneID, filterID := idAttr[0], idAttr[1] - log.Printf("[DEBUG] Importing Cloudflare Filter: id %s for zone %s", filterID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Filter: id %s for zone %s", filterID, zoneID)) d.Set("zone_id", zoneID) d.SetId(filterID) diff --git a/internal/provider/resource_cloudflare_filter_test.go b/internal/provider/resource_cloudflare_filter_test.go index cbb65c1dc68..c64a174c5ff 100644 --- a/internal/provider/resource_cloudflare_filter_test.go +++ b/internal/provider/resource_cloudflare_filter_test.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "os" "testing" "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -19,23 +19,24 @@ func init() { } func testSweepCloudflareFilterSweeper(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") filters, filtersErr := client.Filters(context.Background(), zoneID, cloudflare.PaginationOptions{}) if filtersErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare filters: %s", filtersErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare filters: %s", filtersErr)) } for _, filter := range filters { err := client.DeleteFilter(context.Background(), zoneID, filter.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare filter (%s) in zone ID: %s", filter.ID, zoneID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare filter (%s) in zone ID: %s", filter.ID, zoneID)) } } diff --git a/internal/provider/resource_cloudflare_firewall_rule.go b/internal/provider/resource_cloudflare_firewall_rule.go index 3af3fdc6669..b4ef1693d6c 100644 --- a/internal/provider/resource_cloudflare_firewall_rule.go +++ b/internal/provider/resource_cloudflare_firewall_rule.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -58,7 +58,7 @@ func resourceCloudflareFirewallRuleCreate(ctx context.Context, d *schema.Resourc newFirewallRule.Products = expandInterfaceToStringList(products.(*schema.Set).List()) } - log.Printf("[DEBUG] Creating Cloudflare Firewall Rule from struct: %+v", newFirewallRule) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Firewall Rule from struct: %+v", newFirewallRule)) var r []cloudflare.FirewallRule @@ -74,7 +74,7 @@ func resourceCloudflareFirewallRuleCreate(ctx context.Context, d *schema.Resourc d.SetId(r[0].ID) - log.Printf("[INFO] Cloudflare Firewall Rule ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Firewall Rule ID: %s", d.Id())) return resourceCloudflareFirewallRuleRead(ctx, d, meta) } @@ -85,19 +85,19 @@ func resourceCloudflareFirewallRuleRead(ctx context.Context, d *schema.ResourceD firewallRule, err := client.FirewallRule(ctx, zoneID, d.Id()) - log.Printf("[DEBUG] firewallRule: %#v", firewallRule) - log.Printf("[DEBUG] firewallRule error: %#v", err) + tflog.Debug(ctx, fmt.Sprintf("firewallRule: %#v", firewallRule)) + tflog.Debug(ctx, fmt.Sprintf("firewallRule error: %#v", err)) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Firewall Rule %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Firewall Rule %s no longer exists", d.Id())) d.SetId("") return nil } return diag.FromErr(fmt.Errorf("error finding Firewall Rule %q: %w", d.Id(), err)) } - log.Printf("[DEBUG] Cloudflare Firewall Rule read configuration: %#v", firewallRule) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Firewall Rule read configuration: %#v", firewallRule)) products := expandStringListToSet(firewallRule.Products) d.Set("paused", firewallRule.Paused) @@ -143,7 +143,7 @@ func resourceCloudflareFirewallRuleUpdate(ctx context.Context, d *schema.Resourc newFirewallRule.Products = expandInterfaceToStringList(products.(*schema.Set).List()) } - log.Printf("[DEBUG] Updating Cloudflare Firewall Rule from struct: %+v", newFirewallRule) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Firewall Rule from struct: %+v", newFirewallRule)) r, err := client.UpdateFirewallRule(ctx, zoneID, newFirewallRule) @@ -162,7 +162,7 @@ func resourceCloudflareFirewallRuleDelete(ctx context.Context, d *schema.Resourc client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Deleting Cloudflare Firewall Rule: id %s for zone %s", d.Id(), zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Firewall Rule: id %s for zone %s", d.Id(), zoneID)) err := client.DeleteFirewallRule(ctx, zoneID, d.Id()) @@ -183,7 +183,7 @@ func resourceCloudflareFirewallRuleImport(ctx context.Context, d *schema.Resourc zoneID, ruleID := idAttr[0], idAttr[1] - log.Printf("[DEBUG] Importing Cloudflare Firewall Rule: id %s for zone %s", ruleID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Firewall Rule: id %s for zone %s", ruleID, zoneID)) d.Set("zone_id", zoneID) d.SetId(ruleID) diff --git a/internal/provider/resource_cloudflare_firewall_rule_test.go b/internal/provider/resource_cloudflare_firewall_rule_test.go index c9126805f28..09c621e1c31 100644 --- a/internal/provider/resource_cloudflare_firewall_rule_test.go +++ b/internal/provider/resource_cloudflare_firewall_rule_test.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "os" "testing" cloudflare "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -19,23 +19,24 @@ func init() { } func testSweepCloudflareFirewallRuleSweeper(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") rules, rulesErr := client.FirewallRules(context.Background(), zoneID, cloudflare.PaginationOptions{}) if rulesErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare firewall rules: %s", rulesErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare firewall rules: %s", rulesErr)) } for _, rule := range rules { err := client.DeleteFirewallRule(context.Background(), zoneID, rule.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare firewall rule (%s) in zone ID: %s", rule.ID, zoneID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare firewall rule (%s) in zone ID: %s", rule.ID, zoneID)) } } diff --git a/internal/provider/resource_cloudflare_gre_tunnel.go b/internal/provider/resource_cloudflare_gre_tunnel.go index 884b5d7dd7c..a6571a9ef3a 100644 --- a/internal/provider/resource_cloudflare_gre_tunnel.go +++ b/internal/provider/resource_cloudflare_gre_tunnel.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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/pkg/errors" @@ -68,7 +68,7 @@ func resourceCloudflareGRETunnelRead(ctx context.Context, d *schema.ResourceData tunnel, err := client.GetMagicTransitGRETunnel(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "GRE tunnel not found") { - log.Printf("[INFO] GRE tunnel %s not found", d.Id()) + tflog.Info(ctx, fmt.Sprintf("GRE tunnel %s not found", d.Id())) d.SetId("") return nil } @@ -108,7 +108,7 @@ func resourceCloudflareGRETunnelDelete(ctx context.Context, d *schema.ResourceDa accountID := d.Get("account_id").(string) client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting GRE tunnel: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting GRE tunnel: %s", d.Id())) _, err := client.DeleteMagicTransitGRETunnel(ctx, accountID, d.Id()) if err != nil { diff --git a/internal/provider/resource_cloudflare_healthcheck.go b/internal/provider/resource_cloudflare_healthcheck.go index 871bef7b8c0..f5ed8cb504a 100644 --- a/internal/provider/resource_cloudflare_healthcheck.go +++ b/internal/provider/resource_cloudflare_healthcheck.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "time" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -39,7 +39,7 @@ func resourceCloudflareHealthcheckRead(ctx context.Context, d *schema.ResourceDa healthcheck, err := client.Healthcheck(ctx, zoneID, d.Id()) if err != nil { if strings.Contains(err.Error(), "object does not exist") { - log.Printf("[INFO] Healthcheck %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Healthcheck %s no longer exists", d.Id())) d.SetId("") return nil } @@ -61,7 +61,7 @@ func resourceCloudflareHealthcheckRead(ctx context.Context, d *schema.ResourceDa d.Set("notification_email_addresses", healthcheck.Notification.EmailAddresses) if err := d.Set("header", flattenHealthcheckHeader(healthcheck.HTTPConfig.Header)); err != nil { - log.Printf("[WARN] Error setting header for standalone healthcheck %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting header for standalone healthcheck %q: %s", d.Id(), err)) } } diff --git a/internal/provider/resource_cloudflare_ip_list.go b/internal/provider/resource_cloudflare_ip_list.go index 68c2298cf60..5f40806891f 100644 --- a/internal/provider/resource_cloudflare_ip_list.go +++ b/internal/provider/resource_cloudflare_ip_list.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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/pkg/errors" @@ -70,7 +70,7 @@ func resourceCloudflareIPListRead(ctx context.Context, d *schema.ResourceData, m list, err := client.GetIPList(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "could not find list") { - log.Printf("[INFO] IP List %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("IP List %s no longer exists", d.Id())) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_ipsec_tunnel.go b/internal/provider/resource_cloudflare_ipsec_tunnel.go index f045e889e19..97ec0b5bd6e 100644 --- a/internal/provider/resource_cloudflare_ipsec_tunnel.go +++ b/internal/provider/resource_cloudflare_ipsec_tunnel.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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/pkg/errors" @@ -68,7 +68,7 @@ func resourceCloudflareIPsecTunnelRead(ctx context.Context, d *schema.ResourceDa tunnel, err := client.GetMagicTransitIPsecTunnel(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "IPsec tunnel not found") { - log.Printf("[INFO] IPsec tunnel %s not found", d.Id()) + tflog.Info(ctx, fmt.Sprintf("IPsec tunnel %s not found", d.Id())) d.SetId("") return nil } @@ -103,7 +103,7 @@ func resourceCloudflareIPsecTunnelDelete(ctx context.Context, d *schema.Resource accountID := d.Get("account_id").(string) client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting IPsec tunnel: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting IPsec tunnel: %s", d.Id())) _, err := client.DeleteMagicTransitIPsecTunnel(ctx, accountID, d.Id()) if err != nil { diff --git a/internal/provider/resource_cloudflare_load_balancer.go b/internal/provider/resource_cloudflare_load_balancer.go index 75974081bf2..8d78c5d8194 100644 --- a/internal/provider/resource_cloudflare_load_balancer.go +++ b/internal/provider/resource_cloudflare_load_balancer.go @@ -3,13 +3,13 @@ package provider import ( "context" "fmt" - "log" "strconv" "strings" "time" 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" @@ -273,7 +273,7 @@ func resourceCloudflareLoadBalancerCreate(ctx context.Context, d *schema.Resourc newLoadBalancer.Rules = v } - log.Printf("[INFO] Creating Cloudflare Load Balancer from struct: %+v", newLoadBalancer) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare Load Balancer from struct: %+v", newLoadBalancer)) r, err := client.CreateLoadBalancer(ctx, zoneID, newLoadBalancer) if err != nil { @@ -286,7 +286,7 @@ func resourceCloudflareLoadBalancerCreate(ctx context.Context, d *schema.Resourc d.SetId(r.ID) - log.Printf("[INFO] Cloudflare Load Balancer ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Load Balancer ID: %s", d.Id())) return resourceCloudflareLoadBalancerRead(ctx, d, meta) } @@ -349,7 +349,7 @@ func resourceCloudflareLoadBalancerUpdate(ctx context.Context, d *schema.Resourc loadBalancer.Rules = v } - log.Printf("[INFO] Updating Cloudflare Load Balancer from struct: %+v", loadBalancer) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare Load Balancer from struct: %+v", loadBalancer)) _, err := client.ModifyLoadBalancer(ctx, zoneID, loadBalancer) if err != nil { @@ -383,7 +383,7 @@ func resourceCloudflareLoadBalancerRead(ctx context.Context, d *schema.ResourceD loadBalancer, err := client.LoadBalancerDetails(ctx, zoneID, loadBalancerID) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Load balancer %s in zone %s not found", loadBalancerID, zoneID) + tflog.Info(ctx, fmt.Sprintf("Load balancer %s in zone %s not found", loadBalancerID, zoneID)) d.SetId("") return nil } @@ -420,15 +420,15 @@ func resourceCloudflareLoadBalancerRead(ctx context.Context, d *schema.ResourceD } if err := d.Set("default_pool_ids", loadBalancer.DefaultPools); err != nil { - log.Printf("[WARN] Error setting default_pool_ids on load balancer %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting default_pool_ids on load balancer %q: %s", d.Id(), err)) } if err := d.Set("pop_pools", flattenGeoPools(loadBalancer.PopPools, "pop")); err != nil { - log.Printf("[WARN] Error setting pop_pools on load balancer %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting pop_pools on load balancer %q: %s", d.Id(), err)) } if err := d.Set("region_pools", flattenGeoPools(loadBalancer.RegionPools, "region")); err != nil { - log.Printf("[WARN] Error setting region_pools on load balancer %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting region_pools on load balancer %q: %s", d.Id(), err)) } if loadBalancer.PersistenceTTL != 0 { @@ -463,7 +463,7 @@ func resourceCloudflareLoadBalancerDelete(ctx context.Context, d *schema.Resourc zoneID := d.Get("zone_id").(string) loadBalancerID := d.Id() - log.Printf("[INFO] Deleting Cloudflare Load Balancer: %s in zone: %s", loadBalancerID, zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Load Balancer: %s in zone: %s", loadBalancerID, zoneID)) err := client.DeleteLoadBalancer(ctx, zoneID, loadBalancerID) if err != nil { diff --git a/internal/provider/resource_cloudflare_load_balancer_monitor.go b/internal/provider/resource_cloudflare_load_balancer_monitor.go index 7c6fabdf61a..3b2fc76dc37 100644 --- a/internal/provider/resource_cloudflare_load_balancer_monitor.go +++ b/internal/provider/resource_cloudflare_load_balancer_monitor.go @@ -3,12 +3,12 @@ package provider import ( "context" "fmt" - "log" "strings" "time" "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/pkg/errors" @@ -93,7 +93,7 @@ func resourceCloudflareLoadBalancerPoolMonitorCreate(ctx context.Context, d *sch } } - log.Printf("[DEBUG] Creating Cloudflare Load Balancer Monitor from struct: %+v", loadBalancerMonitor) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Load Balancer Monitor from struct: %+v", loadBalancerMonitor)) r, err := client.CreateLoadBalancerMonitor(ctx, loadBalancerMonitor) if err != nil { @@ -106,7 +106,7 @@ func resourceCloudflareLoadBalancerPoolMonitorCreate(ctx context.Context, d *sch d.SetId(r.ID) - log.Printf("[INFO] New Cloudflare Load Balancer Monitor created with ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("New Cloudflare Load Balancer Monitor created with ID: %s", d.Id())) return resourceCloudflareLoadBalancerPoolMonitorRead(ctx, d, meta) } @@ -181,14 +181,14 @@ func resourceCloudflareLoadBalancerPoolMonitorUpdate(ctx context.Context, d *sch } } - log.Printf("[DEBUG] Update Cloudflare Load Balancer Monitor from struct: %+v", loadBalancerMonitor) + tflog.Debug(ctx, fmt.Sprintf("Update Cloudflare Load Balancer Monitor from struct: %+v", loadBalancerMonitor)) _, err := client.ModifyLoadBalancerMonitor(ctx, loadBalancerMonitor) if err != nil { return diag.FromErr(errors.Wrap(err, "error modifying load balancer monitor")) } - log.Printf("[INFO] Cloudflare Load Balancer Monitor %q was modified", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Load Balancer Monitor %q was modified", d.Id())) return resourceCloudflareLoadBalancerPoolMonitorRead(ctx, d, meta) } @@ -209,7 +209,7 @@ func resourceCloudflareLoadBalancerPoolMonitorRead(ctx context.Context, d *schem loadBalancerMonitor, err := client.LoadBalancerMonitorDetails(ctx, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Load balancer monitor %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Load balancer monitor %s no longer exists", d.Id())) d.SetId("") return nil } else { @@ -217,7 +217,7 @@ func resourceCloudflareLoadBalancerPoolMonitorRead(ctx context.Context, d *schem fmt.Sprintf("Error reading load balancer monitor from API for resource %s ", d.Id()))) } } - log.Printf("[DEBUG] Read Cloudflare Load Balancer Monitor from API as struct: %+v", loadBalancerMonitor) + tflog.Debug(ctx, fmt.Sprintf("Read Cloudflare Load Balancer Monitor from API as struct: %+v", loadBalancerMonitor)) if loadBalancerMonitor.Type == "http" || loadBalancerMonitor.Type == "https" { d.Set("allow_insecure", loadBalancerMonitor.AllowInsecure) @@ -228,7 +228,7 @@ func resourceCloudflareLoadBalancerPoolMonitorRead(ctx context.Context, d *schem d.Set("probe_zone", loadBalancerMonitor.ProbeZone) if err := d.Set("header", flattenLoadBalancerMonitorHeader(loadBalancerMonitor.Header)); err != nil { - log.Printf("[WARN] Error setting header for load balancer monitor %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting header for load balancer monitor %q: %s", d.Id(), err)) } } @@ -260,12 +260,12 @@ func flattenLoadBalancerMonitorHeader(header map[string][]string) *schema.Set { func resourceCloudflareLoadBalancerPoolMonitorDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting Cloudflare Load Balancer Monitor: %s ", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Load Balancer Monitor: %s ", d.Id())) err := client.DeleteLoadBalancerMonitor(ctx, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Load balancer monitor %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Load balancer monitor %s no longer exists", d.Id())) return nil } else { return diag.FromErr(errors.Wrap(err, "error deleting cloudflare load balancer monitor")) diff --git a/internal/provider/resource_cloudflare_load_balancer_pool.go b/internal/provider/resource_cloudflare_load_balancer_pool.go index 0f6dd7a82f7..0b3c248123b 100644 --- a/internal/provider/resource_cloudflare_load_balancer_pool.go +++ b/internal/provider/resource_cloudflare_load_balancer_pool.go @@ -3,13 +3,13 @@ package provider import ( "context" "fmt" - "log" "math" "strings" "time" "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/pkg/errors" @@ -71,7 +71,7 @@ func resourceCloudflareLoadBalancerPoolCreate(ctx context.Context, d *schema.Res loadBalancerPool.NotificationEmail = notificationEmail.(string) } - log.Printf("[DEBUG] Creating Cloudflare Load Balancer Pool from struct: %+v", loadBalancerPool) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Load Balancer Pool from struct: %+v", loadBalancerPool)) r, err := client.CreateLoadBalancerPool(ctx, loadBalancerPool) if err != nil { @@ -84,7 +84,7 @@ func resourceCloudflareLoadBalancerPoolCreate(ctx context.Context, d *schema.Res d.SetId(r.ID) - log.Printf("[INFO] New Cloudflare Load Balancer Pool created with ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("New Cloudflare Load Balancer Pool created with ID: %s", d.Id())) return resourceCloudflareLoadBalancerPoolRead(ctx, d, meta) } @@ -133,7 +133,7 @@ func resourceCloudflareLoadBalancerPoolUpdate(ctx context.Context, d *schema.Res loadBalancerPool.NotificationEmail = notificationEmail.(string) } - log.Printf("[DEBUG] Updating Cloudflare Load Balancer Pool from struct: %+v", loadBalancerPool) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Load Balancer Pool from struct: %+v", loadBalancerPool)) _, err := client.ModifyLoadBalancerPool(ctx, loadBalancerPool) if err != nil { @@ -219,7 +219,7 @@ func resourceCloudflareLoadBalancerPoolRead(ctx context.Context, d *schema.Resou loadBalancerPool, err := client.LoadBalancerPoolDetails(ctx, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Load balancer pool %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Load balancer pool %s no longer exists", d.Id())) d.SetId("") return nil } else { @@ -227,7 +227,7 @@ func resourceCloudflareLoadBalancerPoolRead(ctx context.Context, d *schema.Resou fmt.Sprintf("Error reading load balancer pool from API for resource %s ", d.Id()))) } } - log.Printf("[DEBUG] Read Cloudflare Load Balancer Pool from API as struct: %+v", loadBalancerPool) + tflog.Debug(ctx, fmt.Sprintf("Read Cloudflare Load Balancer Pool from API as struct: %+v", loadBalancerPool)) d.Set("name", loadBalancerPool.Name) d.Set("enabled", loadBalancerPool.Enabled) @@ -248,19 +248,19 @@ func resourceCloudflareLoadBalancerPoolRead(ctx context.Context, d *schema.Resou } if err := d.Set("origins", flattenLoadBalancerOrigins(d, loadBalancerPool.Origins)); err != nil { - log.Printf("[WARN] Error setting origins on load balancer pool %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting origins on load balancer pool %q: %s", d.Id(), err)) } if err := d.Set("load_shedding", flattenLoadBalancerLoadShedding(loadBalancerPool.LoadShedding)); err != nil { - log.Printf("[WARN] Error setting load_shedding on load balancer pool %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting load_shedding on load balancer pool %q: %s", d.Id(), err)) } if err := d.Set("origin_steering", flattenLoadBalancerOriginSteering(loadBalancerPool.OriginSteering)); err != nil { - log.Printf("[WARN] Error setting origin_steering on load balancer pool %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting origin_steering on load balancer pool %q: %s", d.Id(), err)) } if err := d.Set("check_regions", schema.NewSet(schema.HashString, flattenStringList(loadBalancerPool.CheckRegions))); err != nil { - log.Printf("[WARN] Error setting check_regions on load balancer pool %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting check_regions on load balancer pool %q: %s", d.Id(), err)) } return nil @@ -306,7 +306,7 @@ func flattenLoadBalancerOrigins(d *schema.ResourceData, origins []cloudflare.Loa func resourceCloudflareLoadBalancerPoolDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting Cloudflare Load Balancer Pool: %s ", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Load Balancer Pool: %s ", d.Id())) err := client.DeleteLoadBalancerPool(ctx, d.Id()) if err != nil { diff --git a/internal/provider/resource_cloudflare_logpull_retention.go b/internal/provider/resource_cloudflare_logpull_retention.go index 92902b1c4fe..9fe1e1df435 100644 --- a/internal/provider/resource_cloudflare_logpull_retention.go +++ b/internal/provider/resource_cloudflare_logpull_retention.go @@ -3,9 +3,9 @@ package provider import ( "context" "fmt" - "log" 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" ) @@ -69,7 +69,7 @@ func resourceCloudflareLogpullRetentionDelete(ctx context.Context, d *schema.Res func resourceCloudflareLogpullRetentionImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { zoneID := d.Id() - log.Printf("[DEBUG] Importing Cloudflare Logpull Retention option for zone ID: %s", zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Logpull Retention option for zone ID: %s", zoneID)) d.Set("zone_id", zoneID) d.SetId(stringChecksum("logpull-retention/" + zoneID)) diff --git a/internal/provider/resource_cloudflare_logpush_job.go b/internal/provider/resource_cloudflare_logpush_job.go index de994f70e73..c2f0eaf0ccd 100644 --- a/internal/provider/resource_cloudflare_logpush_job.go +++ b/internal/provider/resource_cloudflare_logpush_job.go @@ -3,12 +3,12 @@ package provider import ( "context" "fmt" - "log" "regexp" "strconv" "strings" "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" ) @@ -82,7 +82,7 @@ func resourceCloudflareLogpushJobRead(ctx context.Context, d *schema.ResourceDat } if err != nil { if strings.Contains(err.Error(), "404") { - log.Printf("[INFO] Could not find LogpushJob for %s with id: %q", identifier, jobID) + tflog.Info(ctx, fmt.Sprintf("Could not find LogpushJob for %s with id: %q", identifier, jobID)) d.SetId("") return nil } @@ -112,7 +112,7 @@ func resourceCloudflareLogpushJobCreate(ctx context.Context, d *schema.ResourceD return diag.FromErr(fmt.Errorf("error parsing logpush job from resource: %w", err)) } - log.Printf("[DEBUG] Creating Cloudflare Logpush job for %s from struct: %+v", identifier, job) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Logpush job for %s from struct: %+v", identifier, job)) var j *cloudflare.LogpushJob if identifier.Type == AccountType { @@ -129,7 +129,7 @@ func resourceCloudflareLogpushJobCreate(ctx context.Context, d *schema.ResourceD d.SetId(strconv.Itoa(j.ID)) - log.Printf("[INFO] Created Cloudflare Logpush Job for %s: %s", identifier, d.Id()) + tflog.Info(ctx, fmt.Sprintf("Created Cloudflare Logpush Job for %s: %s", identifier, d.Id())) return resourceCloudflareLogpushJobRead(ctx, d, meta) } @@ -142,7 +142,7 @@ func resourceCloudflareLogpushJobUpdate(ctx context.Context, d *schema.ResourceD return diag.FromErr(fmt.Errorf("error parsing logpush job from resource: %w", err)) } - log.Printf("[INFO] Updating Cloudflare Logpush job for %s from struct: %+v", identifier, job) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare Logpush job for %s from struct: %+v", identifier, job)) if identifier.Type == AccountType { err = client.UpdateAccountLogpushJob(ctx, identifier.Value, job.ID, job) @@ -165,7 +165,7 @@ func resourceCloudflareLogpushJobDelete(ctx context.Context, d *schema.ResourceD return diag.FromErr(fmt.Errorf("error parsing logpush job from resource: %w", err)) } - log.Printf("[DEBUG] Deleting Cloudflare Logpush job for %s with id: %+v", identifier, job.ID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Logpush job for %s with id: %+v", identifier, job.ID)) if identifier.Type == AccountType { err = client.DeleteAccountLogpushJob(ctx, identifier.Value, job.ID) @@ -174,7 +174,7 @@ func resourceCloudflareLogpushJobDelete(ctx context.Context, d *schema.ResourceD } if err != nil { if strings.Contains(err.Error(), "job not found") { - log.Printf("[INFO] Could not find logpush job for %s with id: %q", identifier, job.ID) + tflog.Info(ctx, fmt.Sprintf("Could not find logpush job for %s with id: %q", identifier, job.ID)) d.SetId("") return nil } @@ -200,7 +200,7 @@ func resourceCloudflareLogpushJobImport(ctx context.Context, d *schema.ResourceD } logpushJobID := idAttr[2] - log.Printf("[DEBUG] Importing Cloudflare Logpush Job for %s with id %s", identifier, logpushJobID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Logpush Job for %s with id %s", identifier, logpushJobID)) if identifier.Type == AccountType { if err := d.Set("account_id", identifier.Value); err != nil { diff --git a/internal/provider/resource_cloudflare_magic_firewall_ruleset.go b/internal/provider/resource_cloudflare_magic_firewall_ruleset.go index fa5b128c9eb..d185e962c53 100644 --- a/internal/provider/resource_cloudflare_magic_firewall_ruleset.go +++ b/internal/provider/resource_cloudflare_magic_firewall_ruleset.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" @@ -73,7 +73,7 @@ func resourceCloudflareMagicFirewallRulesetRead(ctx context.Context, d *schema.R ruleset, err := client.GetMagicFirewallRuleset(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "could not find ruleset") { - log.Printf("[INFO] Magic Firewall Ruleset %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Magic Firewall Ruleset %s no longer exists", d.Id())) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_origin_ca_certificate.go b/internal/provider/resource_cloudflare_origin_ca_certificate.go index 85b96a55df0..ffb172cc995 100644 --- a/internal/provider/resource_cloudflare_origin_ca_certificate.go +++ b/internal/provider/resource_cloudflare_origin_ca_certificate.go @@ -5,12 +5,12 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "log" "math" "strings" "time" 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" ) @@ -50,7 +50,7 @@ func resourceCloudflareOriginCACertificateCreate(ctx context.Context, d *schema. certInput.RequestValidity = requestValidity.(int) } - log.Printf("[INFO] Creating Cloudflare OriginCACertificate: %#v", certInput) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare OriginCACertificate: %#v", certInput)) cert, err := client.CreateOriginCertificate(ctx, certInput) if err != nil { @@ -67,11 +67,11 @@ func resourceCloudflareOriginCACertificateRead(ctx context.Context, d *schema.Re certID := d.Id() cert, err := client.OriginCertificate(ctx, certID) - log.Printf("[DEBUG] OriginCACertificate: %#v", cert) + tflog.Debug(ctx, fmt.Sprintf("OriginCACertificate: %#v", cert)) if err != nil { if strings.Contains(err.Error(), "Failed to read certificate from Database") { - log.Printf("[INFO] OriginCACertificate %s does not exist", certID) + tflog.Info(ctx, fmt.Sprintf("OriginCACertificate %s does not exist", certID)) d.SetId("") return nil } @@ -79,7 +79,7 @@ func resourceCloudflareOriginCACertificateRead(ctx context.Context, d *schema.Re } if cert.RevokedAt != (time.Time{}) { - log.Printf("[INFO] OriginCACertificate %s has been revoked", certID) + tflog.Info(ctx, fmt.Sprintf("OriginCACertificate %s has been revoked", certID)) d.SetId("") return nil } @@ -112,7 +112,7 @@ func resourceCloudflareOriginCACertificateDelete(ctx context.Context, d *schema. client := meta.(*cloudflare.API) certID := d.Id() - log.Printf("[INFO] Revoking Cloudflare OriginCACertificate: id %s", certID) + tflog.Info(ctx, fmt.Sprintf("Revoking Cloudflare OriginCACertificate: id %s", certID)) _, err := client.RevokeOriginCertificate(ctx, certID) diff --git a/internal/provider/resource_cloudflare_page_rule.go b/internal/provider/resource_cloudflare_page_rule.go index 17830ecd695..394b0bc5e85 100644 --- a/internal/provider/resource_cloudflare_page_rule.go +++ b/internal/provider/resource_cloudflare_page_rule.go @@ -9,6 +9,7 @@ import ( "strings" 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" ) @@ -54,10 +55,10 @@ func resourceCloudflarePageRuleCreate(ctx context.Context, d *schema.ResourceDat actions := d.Get("actions").([]interface{}) newPageRuleActions := make([]cloudflare.PageRuleAction, 0, len(actions)) - log.Printf("[DEBUG] Actions found in config: %#v", actions) + tflog.Debug(ctx, fmt.Sprintf("Actions found in config: %#v", actions)) for _, action := range actions { for id, value := range action.(map[string]interface{}) { - newPageRuleAction, err := transformToCloudflarePageRuleAction(id, value, d) + newPageRuleAction, err := transformToCloudflarePageRuleAction(ctx, id, value, d) if err != nil { return diag.FromErr(err) } else if newPageRuleAction.Value == nil || newPageRuleAction.Value == "" { @@ -78,7 +79,7 @@ func resourceCloudflarePageRuleCreate(ctx context.Context, d *schema.ResourceDat Status: d.Get("status").(string), } - log.Printf("[DEBUG] Cloudflare Page Rule create configuration: %#v", newPageRule) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Page Rule create configuration: %#v", newPageRule)) r, err := client.CreatePageRule(ctx, zoneID, newPageRule) if err != nil { @@ -110,14 +111,14 @@ func resourceCloudflarePageRuleRead(ctx context.Context, d *schema.ResourceData, if err != nil { if strings.Contains(err.Error(), "Invalid Page Rule identifier") || // api bug - this indicates non-existing resource strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Page Rule %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Page Rule %s no longer exists", d.Id())) d.SetId("") return nil } else { return diag.FromErr(fmt.Errorf("error finding page rule %q: %w", d.Id(), err)) } } - log.Printf("[DEBUG] Cloudflare Page Rule read configuration: %#v", pageRule) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Page Rule read configuration: %#v", pageRule)) // Cloudflare presently only has one target type, and its Operator is always // "matches"; so we can just read the first element's Value. @@ -170,7 +171,7 @@ func resourceCloudflarePageRuleUpdate(ctx context.Context, d *schema.ResourceDat for _, action := range actions { for id, value := range action.(map[string]interface{}) { - newPageRuleAction, err := transformToCloudflarePageRuleAction(id, value, d) + newPageRuleAction, err := transformToCloudflarePageRuleAction(ctx, id, value, d) if err != nil { return diag.FromErr(err) } else if newPageRuleAction.Value == nil { @@ -345,7 +346,7 @@ func transformFromCloudflarePageRuleAction(pageRuleAction *cloudflare.PageRuleAc return } -func transformToCloudflarePageRuleAction(id string, value interface{}, d *schema.ResourceData) (pageRuleAction cloudflare.PageRuleAction, err error) { +func transformToCloudflarePageRuleAction(ctx context.Context, id string, value interface{}, d *schema.ResourceData) (pageRuleAction cloudflare.PageRuleAction, err error) { pageRuleAction.ID = id if strValue, ok := value.(string); ok { @@ -474,7 +475,7 @@ func transformToCloudflarePageRuleAction(id string, value interface{}, d *schema } else if id == "cache_ttl_by_status" { cacheTTLActionSchema := value.(*schema.Set) - log.Printf("[DEBUG] cache_ttl_by_status action to be applied: %#v", cacheTTLActionSchema) + tflog.Debug(ctx, fmt.Sprintf("cache_ttl_by_status action to be applied: %#v", cacheTTLActionSchema)) if cacheTTLActionSchema.Len() != 0 { output := make(map[string]int) @@ -490,7 +491,7 @@ func transformToCloudflarePageRuleAction(id string, value interface{}, d *schema err = fmt.Errorf("Bad value for %s: %s", id, value) } - log.Printf("[DEBUG] Page Rule Action to be applied: %#v", pageRuleAction) + tflog.Debug(ctx, fmt.Sprintf("Page Rule Action to be applied: %#v", pageRuleAction)) return } diff --git a/internal/provider/resource_cloudflare_page_rule_test.go b/internal/provider/resource_cloudflare_page_rule_test.go index a65e3f5b2f8..68a334853fe 100644 --- a/internal/provider/resource_cloudflare_page_rule_test.go +++ b/internal/provider/resource_cloudflare_page_rule_test.go @@ -3,13 +3,13 @@ package provider import ( "context" "fmt" - "log" "os" "reflect" "regexp" "testing" cloudflare "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" @@ -24,9 +24,10 @@ func init() { } func testSweepCloudflarePageRules(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") @@ -357,6 +358,7 @@ func TestTranformForwardingURL(t *testing.T) { // existing Page Rule that didn't have this value set previously. func TestCacheKeyFieldsNilValue(t *testing.T) { pageRuleAction, err := transformToCloudflarePageRuleAction( + context.Background(), "cache_key_fields", []interface{}{ map[string]interface{}{ diff --git a/internal/provider/resource_cloudflare_rate_limit.go b/internal/provider/resource_cloudflare_rate_limit.go index c5e0248a439..3ccaf7457ba 100644 --- a/internal/provider/resource_cloudflare_rate_limit.go +++ b/internal/provider/resource_cloudflare_rate_limit.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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/pkg/errors" @@ -30,7 +30,7 @@ func resourceCloudflareRateLimitCreate(ctx context.Context, d *schema.ResourceDa zoneID := d.Get("zone_id").(string) - rateLimitAction, err := expandRateLimitAction(d) + rateLimitAction, err := expandRateLimitAction(ctx, d) if err != nil { return diag.FromErr(errors.Wrap(err, "error expanding rate limit action")) } @@ -61,13 +61,13 @@ func resourceCloudflareRateLimitCreate(ctx context.Context, d *schema.ResourceDa newRateLimit.Correlate, _ = expandRateLimitCorrelate(d) - newRateLimitAction, err := expandRateLimitAction(d) + newRateLimitAction, err := expandRateLimitAction(ctx, d) if err != nil { return diag.FromErr(err) } newRateLimit.Action = newRateLimitAction - log.Printf("[DEBUG] Creating Cloudflare Rate Limit from struct: %+v", newRateLimit) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Rate Limit from struct: %+v", newRateLimit)) r, err := client.CreateRateLimit(ctx, zoneID, newRateLimit) if err != nil { @@ -80,7 +80,7 @@ func resourceCloudflareRateLimitCreate(ctx context.Context, d *schema.ResourceDa d.SetId(r.ID) - log.Printf("[INFO] Cloudflare Rate Limit ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Rate Limit ID: %s", d.Id())) return resourceCloudflareRateLimitRead(ctx, d, meta) } @@ -91,7 +91,7 @@ func resourceCloudflareRateLimitUpdate(ctx context.Context, d *schema.ResourceDa zoneID := d.Get("zone_id").(string) rateLimitId := d.Id() - rateLimitAction, err := expandRateLimitAction(d) + rateLimitAction, err := expandRateLimitAction(ctx, d) if err != nil { return diag.FromErr(errors.Wrap(err, "error expanding rate limit action")) } @@ -102,7 +102,7 @@ func resourceCloudflareRateLimitUpdate(ctx context.Context, d *schema.ResourceDa Action: rateLimitAction, } - newRateLimitAction, err := expandRateLimitAction(d) + newRateLimitAction, err := expandRateLimitAction(ctx, d) if err != nil { return diag.FromErr(err) } @@ -201,7 +201,7 @@ func expandRateLimitTrafficMatcher(d *schema.ResourceData) (matcher cloudflare.R return } -func expandRateLimitAction(d *schema.ResourceData) (action cloudflare.RateLimitAction, err error) { +func expandRateLimitAction(ctx context.Context, d *schema.ResourceData) (action cloudflare.RateLimitAction, err error) { // dont need to guard for array length because MinItems is set **and** action is required tfAction := d.Get("action").([]interface{})[0].(map[string]interface{}) @@ -220,7 +220,7 @@ func expandRateLimitAction(d *schema.ResourceData) (action cloudflare.RateLimitA action.Timeout = timeout if _, ok := tfAction["response"]; ok && len(tfAction["response"].([]interface{})) > 0 { - log.Printf("[DEBUG] Cloudflare Rate Limit specified action: %+v \n", tfAction) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Rate Limit specified action: %+v \n", tfAction)) tfActionResponse := tfAction["response"].([]interface{})[0].(map[string]interface{}) action.Response = &cloudflare.RateLimitActionResponse{ @@ -265,7 +265,7 @@ func resourceCloudflareRateLimitRead(ctx context.Context, d *schema.ResourceData rateLimit, err := client.RateLimit(ctx, zoneID, rateLimitId) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Resource %s in zone %s no longer exists", rateLimitId, zoneID) + tflog.Info(ctx, fmt.Sprintf("Resource %s in zone %s no longer exists", rateLimitId, zoneID)) d.SetId("") return nil } else { @@ -273,15 +273,15 @@ func resourceCloudflareRateLimitRead(ctx context.Context, d *schema.ResourceData fmt.Sprintf("Error reading rate limit resource from API for resource %s in zone %s", zoneID, rateLimitId))) } } - log.Printf("[DEBUG] Read Cloudflare Rate Limit from API as struct: %+v", rateLimit) + tflog.Debug(ctx, fmt.Sprintf("Read Cloudflare Rate Limit from API as struct: %+v", rateLimit)) d.Set("threshold", rateLimit.Threshold) d.Set("period", rateLimit.Period) if err := d.Set("match", flattenRateLimitTrafficMatcher(rateLimit.Match)); err != nil { - log.Printf("[WARN] Error setting match on rate limit %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting match on rate limit %q: %s", d.Id(), err)) } if err := d.Set("action", flattenRateLimitAction(rateLimit.Action)); err != nil { - log.Printf("[WARN] Error setting action on rate limit %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting action on rate limit %q: %s", d.Id(), err)) } if rateLimit.Correlate != nil { @@ -297,11 +297,11 @@ func resourceCloudflareRateLimitRead(ctx context.Context, d *schema.ResourceData bypassUrlPatterns = append(bypassUrlPatterns, bypassItem.Value) } else { // maybe a new type of bypass was added to api - log.Printf("[WARN] Unknown bypass type found in rate limit for zone %q: %s", d.Id(), bypassItem.Name) + tflog.Warn(ctx, fmt.Sprintf("Unknown bypass type found in rate limit for zone %q: %s", d.Id(), bypassItem.Name)) } } if err := d.Set("bypass_url_patterns", bypassUrlPatterns); err != nil { - log.Printf("[WARN] Error setting bypass_url_patterns on rate limit %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting bypass_url_patterns on rate limit %q: %s", d.Id(), err)) } return nil @@ -386,7 +386,7 @@ func resourceCloudflareRateLimitDelete(ctx context.Context, d *schema.ResourceDa zoneID := d.Get("zone_id").(string) rateLimitId := d.Id() - log.Printf("[INFO] Deleting Cloudflare Rate Limit: %s for zone: %s", rateLimitId, zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Rate Limit: %s for zone: %s", rateLimitId, zoneID)) err := client.DeleteRateLimit(ctx, zoneID, rateLimitId) if err != nil { diff --git a/internal/provider/resource_cloudflare_record.go b/internal/provider/resource_cloudflare_record.go index 63ffbc8d880..12b9f984b12 100644 --- a/internal/provider/resource_cloudflare_record.go +++ b/internal/provider/resource_cloudflare_record.go @@ -4,11 +4,11 @@ import ( "context" "errors" "fmt" - "log" "strings" "time" 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/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -60,7 +60,7 @@ func resourceCloudflareRecordCreate(ctx context.Context, d *schema.ResourceData, } data, dataOk := d.GetOk("data") - log.Printf("[DEBUG] Data found in config: %#v", data) + tflog.Debug(ctx, fmt.Sprintf("Data found in config: %#v", data)) newDataMap := make(map[string]interface{}) @@ -115,7 +115,7 @@ func resourceCloudflareRecordCreate(ctx context.Context, d *schema.ResourceData, return diag.FromErr(fmt.Errorf("error validating record type %q: %w", newRecord.Type, err)) } - log.Printf("[DEBUG] Cloudflare Record create configuration: %#v", newRecord) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Record create configuration: %#v", newRecord)) retry := resource.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { r, err := client.CreateDNSRecord(ctx, newRecord.ZoneID, newRecord) @@ -123,7 +123,7 @@ func resourceCloudflareRecordCreate(ctx context.Context, d *schema.ResourceData, if strings.Contains(err.Error(), "already exist") { if d.Get("allow_overwrite").(bool) { var r cloudflare.DNSRecord - log.Printf("[DEBUG] Cloudflare Record already exists however we are overwriting it") + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Record already exists however we are overwriting it")) zone, _ := client.ZoneDetails(ctx, d.Get("zone_id").(string)) if d.Get("name").(string) == "@" || d.Get("name").(string) == zone.Name { r = cloudflare.DNSRecord{ @@ -187,7 +187,7 @@ func resourceCloudflareRecordRead(ctx context.Context, d *schema.ResourceData, m if err != nil { if strings.Contains(err.Error(), "Invalid dns record identifier") || strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[WARN] Removing record from state because it's not found in API") + tflog.Warn(ctx, fmt.Sprintf("Removing record from state because it's not found in API")) d.SetId("") return nil } @@ -195,7 +195,7 @@ func resourceCloudflareRecordRead(ctx context.Context, d *schema.ResourceData, m } data, dataOk := d.GetOk("data") - log.Printf("[DEBUG] Data found in config: %#v", data) + tflog.Debug(ctx, fmt.Sprintf("Data found in config: %#v", data)) readDataMap := make(map[string]interface{}) @@ -226,7 +226,7 @@ func resourceCloudflareRecordRead(ctx context.Context, d *schema.ResourceData, m d.Set("data", record.Data) d.Set("modified_on", record.ModifiedOn.Format(time.RFC3339Nano)) if err := d.Set("metadata", expandStringMap(record.Meta)); err != nil { - log.Printf("[WARN] Error setting metadata: %s", err) + tflog.Warn(ctx, fmt.Sprintf("Error setting metadata: %s", err)) } d.Set("proxiable", record.Proxiable) @@ -252,7 +252,7 @@ func resourceCloudflareRecordUpdate(ctx context.Context, d *schema.ResourceData, } data, dataOk := d.GetOk("data") - log.Printf("[DEBUG] Data found in config: %#v", data) + tflog.Debug(ctx, fmt.Sprintf("Data found in config: %#v", data)) newDataMap := make(map[string]interface{}) @@ -289,7 +289,7 @@ func resourceCloudflareRecordUpdate(ctx context.Context, d *schema.ResourceData, updateRecord.TTL = ttl.(int) } - log.Printf("[DEBUG] Cloudflare Record update configuration: %#v", updateRecord) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Record update configuration: %#v", updateRecord)) retry := resource.RetryContext(ctx, d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { err := client.UpdateDNSRecord(ctx, zoneID, d.Id(), updateRecord) @@ -316,7 +316,7 @@ func resourceCloudflareRecordDelete(ctx context.Context, d *schema.ResourceData, client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Deleting Cloudflare Record: %s, %s", zoneID, d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Record: %s, %s", zoneID, d.Id())) err := client.DeleteDNSRecord(ctx, zoneID, d.Id()) if err != nil { @@ -359,7 +359,7 @@ func resourceCloudflareRecordImport(ctx context.Context, d *schema.ResourceData, return nil, fmt.Errorf("Unable to find record with ID %q: %w", d.Id(), err) } - log.Printf("[INFO] Found record: %s", record.Name) + tflog.Info(ctx, fmt.Sprintf("Found record: %s", record.Name)) name := strings.TrimSuffix(record.Name, "."+record.ZoneName) d.Set("name", name) diff --git a/internal/provider/resource_cloudflare_record_test.go b/internal/provider/resource_cloudflare_record_test.go index 64a2b92f7c3..d7a45fd9b16 100644 --- a/internal/provider/resource_cloudflare_record_test.go +++ b/internal/provider/resource_cloudflare_record_test.go @@ -10,6 +10,7 @@ import ( "time" cloudflare "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/pkg/errors" @@ -23,9 +24,10 @@ func init() { } func testSweepCloudflareRecord(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)) } // Clean up the account level rulesets @@ -36,7 +38,7 @@ func testSweepCloudflareRecord(r string) error { records, err := client.DNSRecords(context.Background(), zoneID, cloudflare.DNSRecord{}) if err != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare DNS records: %s", err) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare DNS records: %s", err)) } if len(records) == 0 { @@ -45,7 +47,7 @@ func testSweepCloudflareRecord(r string) error { } for _, record := range records { - log.Printf("[INFO] Deleting Cloudflare DNS record ID: %s", record.ID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare DNS record ID: %s", record.ID)) //nolint:errcheck client.DeleteDNSRecord(context.Background(), zoneID, record.ID) } diff --git a/internal/provider/resource_cloudflare_ruleset_test.go b/internal/provider/resource_cloudflare_ruleset_test.go index b397ad3fe4b..9d941b88172 100644 --- a/internal/provider/resource_cloudflare_ruleset_test.go +++ b/internal/provider/resource_cloudflare_ruleset_test.go @@ -7,6 +7,7 @@ import ( "os" "testing" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/pkg/errors" ) @@ -19,9 +20,10 @@ func init() { } func testSweepCloudflareRuleset(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)) } // Clean up the account level rulesets @@ -32,7 +34,7 @@ func testSweepCloudflareRuleset(r string) error { accountRulesets, accountRulesetsErr := client.ListAccountRulesets(context.Background(), accountID) if accountRulesetsErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare Account Rulesets: %s", accountRulesetsErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare Account Rulesets: %s", accountRulesetsErr)) } if len(accountRulesets) == 0 { @@ -41,7 +43,7 @@ func testSweepCloudflareRuleset(r string) error { } for _, ruleset := range accountRulesets { - log.Printf("[INFO] Deleting Cloudflare Account Ruleset ID: %s", ruleset.ID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Account Ruleset ID: %s", ruleset.ID)) client.DeleteAccountRuleset(context.Background(), accountID, ruleset.ID) } @@ -53,7 +55,7 @@ func testSweepCloudflareRuleset(r string) error { zoneRulesets, zoneRulesetsErr := client.ListZoneRulesets(context.Background(), zoneID) if zoneRulesetsErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare Zone Rulesets: %s", zoneRulesetsErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare Zone Rulesets: %s", zoneRulesetsErr)) } if len(zoneRulesets) == 0 { @@ -62,7 +64,7 @@ func testSweepCloudflareRuleset(r string) error { } for _, ruleset := range zoneRulesets { - log.Printf("[INFO] Deleting Cloudflare Zone Ruleset ID: %s", ruleset.ID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Zone Ruleset ID: %s", ruleset.ID)) client.DeleteZoneRuleset(context.Background(), zoneID, ruleset.ID) } diff --git a/internal/provider/resource_cloudflare_spectrum_application.go b/internal/provider/resource_cloudflare_spectrum_application.go index 6abd1a2585e..417bfe49fd6 100644 --- a/internal/provider/resource_cloudflare_spectrum_application.go +++ b/internal/provider/resource_cloudflare_spectrum_application.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "net" "strings" "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/pkg/errors" @@ -32,7 +32,7 @@ func resourceCloudflareSpectrumApplicationCreate(ctx context.Context, d *schema. newSpectrumApp := applicationFromResource(d) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Creating Cloudflare Spectrum Application from struct: %+v", newSpectrumApp) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare Spectrum Application from struct: %+v", newSpectrumApp)) r, err := client.CreateSpectrumApplication(ctx, zoneID, newSpectrumApp) if err != nil { @@ -45,7 +45,7 @@ func resourceCloudflareSpectrumApplicationCreate(ctx context.Context, d *schema. d.SetId(r.ID) - log.Printf("[INFO] Cloudflare Spectrum Application ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Spectrum Application ID: %s", d.Id())) return resourceCloudflareSpectrumApplicationRead(ctx, d, meta) } @@ -56,7 +56,7 @@ func resourceCloudflareSpectrumApplicationUpdate(ctx context.Context, d *schema. application := applicationFromResource(d) - log.Printf("[INFO] Updating Cloudflare Spectrum Application from struct: %+v", application) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare Spectrum Application from struct: %+v", application)) _, err := client.UpdateSpectrumApplication(ctx, zoneID, application.ID, application) if err != nil { @@ -74,7 +74,7 @@ func resourceCloudflareSpectrumApplicationRead(ctx context.Context, d *schema.Re application, err := client.SpectrumApplication(ctx, zoneID, applicationID) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Spectrum application %s in zone %s not found", applicationID, zoneID) + tflog.Info(ctx, fmt.Sprintf("Spectrum application %s in zone %s not found", applicationID, zoneID)) d.SetId("") return nil } @@ -85,18 +85,18 @@ func resourceCloudflareSpectrumApplicationRead(ctx context.Context, d *schema.Re d.Set("protocol", application.Protocol) if err := d.Set("dns", flattenDNS(application.DNS)); err != nil { - log.Printf("[WARN] Error setting dns on spectrum application %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting dns on spectrum application %q: %s", d.Id(), err)) } if len(application.OriginDirect) > 0 { if err := d.Set("origin_direct", application.OriginDirect); err != nil { - log.Printf("[WARN] Error setting origin direct on spectrum application %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting origin direct on spectrum application %q: %s", d.Id(), err)) } } if application.OriginDNS != nil { if err := d.Set("origin_dns", flattenOriginDNS(application.OriginDNS)); err != nil { - log.Printf("[WARN] Error setting origin dns on spectrum application %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting origin dns on spectrum application %q: %s", d.Id(), err)) } } @@ -105,19 +105,19 @@ func resourceCloudflareSpectrumApplicationRead(ctx context.Context, d *schema.Re d.Set("origin_port", int(application.OriginPort.Port)) } else { if err := d.Set("origin_port_range", flattenOriginPortRange(application.OriginPort)); err != nil { - log.Printf("[WARN] Error setting origin port range on spectrum application %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting origin port range on spectrum application %q: %s", d.Id(), err)) } } } if application.EdgeIPs != nil { if err := d.Set("edge_ips", flattenEdgeIPs(application.EdgeIPs)); err != nil { - log.Printf("[WARN] Error setting Edge IPs on spectrum application %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting Edge IPs on spectrum application %q: %s", d.Id(), err)) } if application.EdgeIPs.Connectivity != nil { if err := d.Set("edge_ip_connectivity", application.EdgeIPs.Connectivity.String()); err != nil { - log.Printf("[WARN] Error setting Edge IP connectivity on spectrum application %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting Edge IP connectivity on spectrum application %q: %s", d.Id(), err)) } } } @@ -136,7 +136,7 @@ func resourceCloudflareSpectrumApplicationDelete(ctx context.Context, d *schema. zoneID := d.Get("zone_id").(string) applicationID := d.Id() - log.Printf("[INFO] Deleting Cloudflare Spectrum Application: %s in zone: %s", applicationID, zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Spectrum Application: %s in zone: %s", applicationID, zoneID)) err := client.DeleteSpectrumApplication(ctx, zoneID, applicationID) if err != nil { diff --git a/internal/provider/resource_cloudflare_spectrum_application_test.go b/internal/provider/resource_cloudflare_spectrum_application_test.go index 015c360f645..9a187dbb7bf 100644 --- a/internal/provider/resource_cloudflare_spectrum_application_test.go +++ b/internal/provider/resource_cloudflare_spectrum_application_test.go @@ -10,6 +10,7 @@ import ( "os" "github.com/cloudflare/cloudflare-go" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -22,22 +23,23 @@ func init() { } func testSweepCloudflareSpectrumApplications(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)) } zone := os.Getenv("CLOUDFLARE_DOMAIN") zones, zoneErr := client.ListZones(context.Background(), zone) 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)) } for _, zone := range zones { spectrumApps, spectrumErr := client.SpectrumApplications(context.Background(), zone.ID) if spectrumErr != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare spectrum applications: %s", zoneErr) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare spectrum applications: %s", zoneErr)) } if len(spectrumApps) == 0 { @@ -46,11 +48,11 @@ func testSweepCloudflareSpectrumApplications(r string) error { } for _, application := range spectrumApps { - log.Printf("[INFO] Deleting Cloudflare spectrum application ID: %s", application.ID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare spectrum application ID: %s", application.ID)) err := client.DeleteSpectrumApplication(context.Background(), zone.ID, application.ID) if err != nil { - log.Printf("[ERROR] Failed to delete Cloudflare spectrum application (%s) in zone ID: %s", application.ID, zone.ID) + tflog.Error(ctx, fmt.Sprintf("Failed to delete Cloudflare spectrum application (%s) in zone ID: %s", application.ID, zone.ID)) } } } diff --git a/internal/provider/resource_cloudflare_static_route.go b/internal/provider/resource_cloudflare_static_route.go index f74fc795da9..0d58f270962 100644 --- a/internal/provider/resource_cloudflare_static_route.go +++ b/internal/provider/resource_cloudflare_static_route.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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/pkg/errors" @@ -63,7 +63,7 @@ func resourceCloudflareStaticRouteRead(ctx context.Context, d *schema.ResourceDa staticRoute, err := client.GetMagicTransitStaticRoute(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "Route not found") { - log.Printf("[INFO] Static Route %s not found", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Static Route %s not found", d.Id())) d.SetId("") return nil } @@ -106,7 +106,7 @@ func resourceCloudflareStaticRouteDelete(ctx context.Context, d *schema.Resource client := meta.(*cloudflare.API) accountID := d.Get("account_id").(string) - log.Printf("[INFO] Deleting Static Route: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Static Route: %s", d.Id())) _, err := client.DeleteMagicTransitStaticRoute(ctx, accountID, d.Id()) if err != nil { diff --git a/internal/provider/resource_cloudflare_teams_accounts.go b/internal/provider/resource_cloudflare_teams_accounts.go index aa85c8f48c4..6c3f2e19afd 100644 --- a/internal/provider/resource_cloudflare_teams_accounts.go +++ b/internal/provider/resource_cloudflare_teams_accounts.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" ) @@ -32,7 +32,7 @@ func resourceCloudflareTeamsAccountRead(ctx context.Context, d *schema.ResourceD configuration, err := client.TeamsAccountConfiguration(ctx, accountID) if err != nil { if strings.Contains(err.Error(), "HTTP status 400") { - log.Printf("[INFO] Teams Account config %s does not exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Teams Account config %s does not exists", d.Id())) d.SetId("") return nil } @@ -130,7 +130,7 @@ func resourceCloudflareTeamsAccountUpdate(ctx context.Context, d *schema.Resourc updatedTeamsAccount.Settings.BrowserIsolation = &cloudflare.BrowserIsolation{UrlBrowserIsolationEnabled: browserIsolation.(bool)} } - log.Printf("[DEBUG] Updating Cloudflare Teams Account configuration from struct: %+v", updatedTeamsAccount) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Teams Account configuration from struct: %+v", updatedTeamsAccount)) if _, err := client.TeamsAccountUpdateConfiguration(ctx, accountID, updatedTeamsAccount); err != nil { return diag.FromErr(fmt.Errorf("error updating Teams Account configuration for account %q: %w", accountID, err)) diff --git a/internal/provider/resource_cloudflare_teams_list.go b/internal/provider/resource_cloudflare_teams_list.go index 99bec6f45a0..3c6ae41b808 100644 --- a/internal/provider/resource_cloudflare_teams_list.go +++ b/internal/provider/resource_cloudflare_teams_list.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -38,7 +38,7 @@ func resourceCloudflareTeamsListCreate(ctx context.Context, d *schema.ResourceDa newTeamsList.Items = append(newTeamsList.Items, cloudflare.TeamsListItem{Value: v.(string)}) } - log.Printf("[DEBUG] Creating Cloudflare Teams List from struct: %+v", newTeamsList) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Teams List from struct: %+v", newTeamsList)) accountID := d.Get("account_id").(string) @@ -59,7 +59,7 @@ func resourceCloudflareTeamsListRead(ctx context.Context, d *schema.ResourceData list, err := client.TeamsList(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Teams List %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Teams List %s no longer exists", d.Id())) d.SetId("") return nil } @@ -89,7 +89,7 @@ func resourceCloudflareTeamsListUpdate(ctx context.Context, d *schema.ResourceDa Description: d.Get("description").(string), } - log.Printf("[DEBUG] Updating Cloudflare Teams List from struct: %+v", updatedTeamsList) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Teams List from struct: %+v", updatedTeamsList)) accountID := d.Get("account_id").(string) @@ -123,7 +123,7 @@ func resourceCloudflareTeamsListDelete(ctx context.Context, d *schema.ResourceDa appID := d.Id() accountID := d.Get("account_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare Teams List using ID: %s", appID) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Teams List using ID: %s", appID)) err := client.DeleteTeamsList(ctx, accountID, appID) if err != nil { @@ -144,7 +144,7 @@ func resourceCloudflareTeamsListImport(ctx context.Context, d *schema.ResourceDa accountID, teamsListID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Teams List: id %s for account %s", teamsListID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Teams List: id %s for account %s", teamsListID, accountID)) d.Set("account_id", accountID) d.SetId(teamsListID) diff --git a/internal/provider/resource_cloudflare_teams_location.go b/internal/provider/resource_cloudflare_teams_location.go index 5c4f7669d6f..627cbb3771f 100644 --- a/internal/provider/resource_cloudflare_teams_location.go +++ b/internal/provider/resource_cloudflare_teams_location.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" ) @@ -31,7 +31,7 @@ func resourceCloudflareTeamsLocationRead(ctx context.Context, d *schema.Resource location, err := client.TeamsLocation(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 400") { - log.Printf("[INFO] Teams Location %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Teams Location %s no longer exists", d.Id())) d.SetId("") return nil } @@ -80,7 +80,7 @@ func resourceCloudflareTeamsLocationCreate(ctx context.Context, d *schema.Resour ClientDefault: d.Get("client_default").(bool), } - log.Printf("[DEBUG] Creating Cloudflare Teams Location from struct: %+v", newTeamLocation) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Teams Location from struct: %+v", newTeamLocation)) location, err := client.CreateTeamsLocation(ctx, accountID, newTeamLocation) if err != nil { @@ -103,7 +103,7 @@ func resourceCloudflareTeamsLocationUpdate(ctx context.Context, d *schema.Resour ClientDefault: d.Get("client_default").(bool), Networks: networks, } - log.Printf("[DEBUG] Updating Cloudflare Teams Location from struct: %+v", updatedTeamsLocation) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Teams Location from struct: %+v", updatedTeamsLocation)) teamsLocation, err := client.UpdateTeamsLocation(ctx, accountID, updatedTeamsLocation) if err != nil { @@ -120,7 +120,7 @@ func resourceCloudflareTeamsLocationDelete(ctx context.Context, d *schema.Resour id := d.Id() accountID := d.Get("account_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare Teams Location using ID: %s", id) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Teams Location using ID: %s", id)) err := client.DeleteTeamsLocation(ctx, accountID, id) if err != nil { @@ -139,7 +139,7 @@ func resourceCloudflareTeamsLocationImport(ctx context.Context, d *schema.Resour accountID, teamsLocationID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Teams Location: id %s for account %s", teamsLocationID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Teams Location: id %s for account %s", teamsLocationID, accountID)) d.Set("account_id", accountID) d.SetId(teamsLocationID) diff --git a/internal/provider/resource_cloudflare_teams_proxy_endpoints.go b/internal/provider/resource_cloudflare_teams_proxy_endpoints.go index 2e0462c5073..7694e9947e9 100644 --- a/internal/provider/resource_cloudflare_teams_proxy_endpoints.go +++ b/internal/provider/resource_cloudflare_teams_proxy_endpoints.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" ) @@ -31,7 +31,7 @@ func resourceCloudflareTeamsProxyEndpointRead(ctx context.Context, d *schema.Res endpoint, err := client.TeamsProxyEndpoint(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 400") { - log.Printf("[INFO] Teams Proxy Endpoint %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Teams Proxy Endpoint %s no longer exists", d.Id())) d.SetId("") return nil } @@ -62,7 +62,7 @@ func resourceCloudflareTeamsProxyEndpointCreate(ctx context.Context, d *schema.R IPs: expandInterfaceToStringList(d.Get("ips").(*schema.Set).List()), } - log.Printf("[DEBUG] Creating Cloudflare Teams Proxy Endpoint from struct: %+v", newProxyEndpoint) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Teams Proxy Endpoint from struct: %+v", newProxyEndpoint)) proxyEndpoint, err := client.CreateTeamsProxyEndpoint(ctx, accountID, newProxyEndpoint) if err != nil { @@ -82,7 +82,7 @@ func resourceCloudflareTeamsProxyEndpointUpdate(ctx context.Context, d *schema.R IPs: expandInterfaceToStringList(d.Get("ips").(*schema.Set).List()), } - log.Printf("[DEBUG] Updating Cloudflare Teams Proxy Endpoint from struct: %+v", updatedProxyEndpoint) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Teams Proxy Endpoint from struct: %+v", updatedProxyEndpoint)) teamsProxyEndpoint, err := client.UpdateTeamsProxyEndpoint(ctx, accountID, updatedProxyEndpoint) @@ -101,7 +101,7 @@ func resourceCloudflareTeamsProxyEndpointDelete(ctx context.Context, d *schema.R id := d.Id() accountID := d.Get("account_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare Teams Proxy Endpoint using ID: %s", id) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Teams Proxy Endpoint using ID: %s", id)) err := client.DeleteTeamsProxyEndpoint(ctx, accountID, id) if err != nil { @@ -120,7 +120,7 @@ func resourceCloudflareTeamsProxyEndpointImport(ctx context.Context, d *schema.R accountID, teamsProxyEndpointID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Teams Proxy Endpoint: id %s for account %s", teamsProxyEndpointID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Teams Proxy Endpoint: id %s for account %s", teamsProxyEndpointID, accountID)) d.Set("account_id", accountID) d.SetId(teamsProxyEndpointID) diff --git a/internal/provider/resource_cloudflare_teams_rules.go b/internal/provider/resource_cloudflare_teams_rules.go index 438dd1956a9..abc21341d60 100644 --- a/internal/provider/resource_cloudflare_teams_rules.go +++ b/internal/provider/resource_cloudflare_teams_rules.go @@ -3,12 +3,12 @@ package provider import ( "context" "fmt" - "log" "net/http" "strings" "time" "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" ) @@ -33,7 +33,7 @@ func resourceCloudflareTeamsRuleRead(ctx context.Context, d *schema.ResourceData rule, err := client.TeamsRule(ctx, accountID, d.Id()) if err != nil { if strings.Contains(err.Error(), "invalid rule id") { - log.Printf("[INFO] Teams Rule config %s does not exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Teams Rule config %s does not exists", d.Id())) d.SetId("") return nil } @@ -103,7 +103,7 @@ func resourceCloudflareTeamsRuleCreate(ctx context.Context, d *schema.ResourceDa newTeamsRule.RuleSettings = *settings } - log.Printf("[DEBUG] Creating Cloudflare Teams Rule from struct: %+v", newTeamsRule) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Teams Rule from struct: %+v", newTeamsRule)) rule, err := client.TeamsCreateRule(ctx, accountID, newTeamsRule) if err != nil { @@ -141,7 +141,7 @@ func resourceCloudflareTeamsRuleUpdate(ctx context.Context, d *schema.ResourceDa if settings != nil { teamsRule.RuleSettings = *settings } - log.Printf("[DEBUG] Updating Cloudflare Teams rule from struct: %+v", teamsRule) + tflog.Debug(ctx, fmt.Sprintf("Updating Cloudflare Teams rule from struct: %+v", teamsRule)) updatedTeamsRule, err := client.TeamsUpdateRule(ctx, accountID, teamsRule.ID, teamsRule) if err != nil { @@ -158,7 +158,7 @@ func resourceCloudflareTeamsRuleDelete(ctx context.Context, d *schema.ResourceDa id := d.Id() accountID := d.Get("account_id").(string) - log.Printf("[DEBUG] Deleting Cloudflare Teams Rule using ID: %s", id) + tflog.Debug(ctx, fmt.Sprintf("Deleting Cloudflare Teams Rule using ID: %s", id)) err := client.TeamsDeleteRule(ctx, accountID, id) if err != nil { @@ -177,7 +177,7 @@ func resourceCloudflareTeamsRuleImport(ctx context.Context, d *schema.ResourceDa accountID, teamsRuleID := attributes[0], attributes[1] - log.Printf("[DEBUG] Importing Cloudflare Teams Rule: id %s for account %s", teamsRuleID, accountID) + tflog.Debug(ctx, fmt.Sprintf("Importing Cloudflare Teams Rule: id %s for account %s", teamsRuleID, accountID)) d.Set("account_id", accountID) d.SetId(teamsRuleID) diff --git a/internal/provider/resource_cloudflare_tunnel_route.go b/internal/provider/resource_cloudflare_tunnel_route.go index 50c4954c5f0..4ccdcbb4aca 100644 --- a/internal/provider/resource_cloudflare_tunnel_route.go +++ b/internal/provider/resource_cloudflare_tunnel_route.go @@ -4,10 +4,10 @@ import ( "context" "errors" "fmt" - "log" "strings" "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" ) @@ -42,7 +42,7 @@ func resourceCloudflareTunnelRouteRead(ctx context.Context, d *schema.ResourceDa } if len(tunnelRoutes) < 1 { - log.Printf("[INFO] Tunnel Route for network %s in account %s not found", network, accountID) + tflog.Info(ctx, fmt.Sprintf("Tunnel Route for network %s in account %s not found", network, accountID)) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_tunnel_route_test.go b/internal/provider/resource_cloudflare_tunnel_route_test.go index 0299888c438..c3d33c3669d 100644 --- a/internal/provider/resource_cloudflare_tunnel_route_test.go +++ b/internal/provider/resource_cloudflare_tunnel_route_test.go @@ -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/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -21,9 +22,10 @@ func init() { } func testSweepCloudflareTunnelRoute(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") @@ -33,7 +35,7 @@ func testSweepCloudflareTunnelRoute(r string) error { tunnelRoutes, err := client.ListTunnelRoutes(context.Background(), cloudflare.TunnelRoutesListParams{AccountID: accountID}) if err != nil { - log.Printf("[ERROR] Failed to fetch Cloudflare Tunnel Routes: %s", err) + tflog.Error(ctx, fmt.Sprintf("Failed to fetch Cloudflare Tunnel Routes: %s", err)) } if len(tunnelRoutes) == 0 { @@ -42,7 +44,7 @@ func testSweepCloudflareTunnelRoute(r string) error { } for _, tunnel := range tunnelRoutes { - log.Printf("[INFO] Deleting Cloudflare Tunnel Route network: %s", tunnel.Network) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Tunnel Route network: %s", tunnel.Network)) //nolint:errcheck client.DeleteTunnelRoute(context.Background(), cloudflare.TunnelRoutesDeleteParams{AccountID: accountID, Network: tunnel.Network}) } diff --git a/internal/provider/resource_cloudflare_waf_override.go b/internal/provider/resource_cloudflare_waf_override.go index 9c676af30d2..b691f3c19eb 100644 --- a/internal/provider/resource_cloudflare_waf_override.go +++ b/internal/provider/resource_cloudflare_waf_override.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" "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" ) @@ -31,7 +31,7 @@ func resourceCloudflareWAFOverrideRead(ctx context.Context, d *schema.ResourceDa override, err := client.WAFOverride(ctx, zoneID, d.Id()) if err != nil { if strings.Contains(err.Error(), "wafuriconfig.api.not_found") { - log.Printf("[INFO] WAF override %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("WAF override %s no longer exists", d.Id())) d.SetId("") return nil } @@ -112,7 +112,7 @@ func resourceCloudflareWAFOverrideImport(ctx context.Context, d *schema.Resource zoneID, WAFOverrideID := idAttr[0], idAttr[1] - log.Printf("[DEBUG] Importing WAF override: id %s for zone %s", WAFOverrideID, zoneID) + tflog.Debug(ctx, fmt.Sprintf("Importing WAF override: id %s for zone %s", WAFOverrideID, zoneID)) d.Set("zone_id", zoneID) d.Set("override_id", WAFOverrideID) diff --git a/internal/provider/resource_cloudflare_waiting_room.go b/internal/provider/resource_cloudflare_waiting_room.go index 0d6fad63436..d3b6b5dc16f 100644 --- a/internal/provider/resource_cloudflare_waiting_room.go +++ b/internal/provider/resource_cloudflare_waiting_room.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "strings" "time" 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" ) @@ -73,7 +73,7 @@ func resourceCloudflareWaitingRoomRead(ctx context.Context, d *schema.ResourceDa waitingRoom, err := client.WaitingRoom(ctx, zoneID, waitingRoomID) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[WARN] Removing waiting room from state because it's not found in API") + tflog.Warn(ctx, fmt.Sprintf("Removing waiting room from state because it's not found in API")) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_waiting_room_event.go b/internal/provider/resource_cloudflare_waiting_room_event.go index 21123e16bce..783632b3481 100644 --- a/internal/provider/resource_cloudflare_waiting_room_event.go +++ b/internal/provider/resource_cloudflare_waiting_room_event.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "strings" "time" 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" ) @@ -97,7 +97,7 @@ func resourceCloudflareWaitingRoomEventRead(ctx context.Context, d *schema.Resou waitingRoomEvent, err := client.WaitingRoomEvent(ctx, zoneID, waitingRoomID, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[WARN] Removing waiting room event from state because it's not found in API") + tflog.Warn(ctx, fmt.Sprintf("Removing waiting room event from state because it's not found in API")) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_worker_kv.go b/internal/provider/resource_cloudflare_worker_kv.go index d444bad53cc..2a5abdb404e 100644 --- a/internal/provider/resource_cloudflare_worker_kv.go +++ b/internal/provider/resource_cloudflare_worker_kv.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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/pkg/errors" @@ -59,7 +59,7 @@ func resourceCloudflareWorkersKVUpdate(ctx context.Context, d *schema.ResourceDa d.SetId(fmt.Sprintf("%s/%s", namespaceID, key)) - log.Printf("[INFO] Cloudflare Workers KV Namespace ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Workers KV Namespace ID: %s", d.Id())) return resourceCloudflareWorkersKVRead(ctx, d, meta) } @@ -71,7 +71,7 @@ func resourceCloudflareWorkersKVDelete(ctx context.Context, d *schema.ResourceDa return diag.FromErr(err) } - log.Printf("[INFO] Deleting Cloudflare Workers KV with id: %+v", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Workers KV with id: %+v", d.Id())) _, err = client.DeleteWorkersKV(ctx, namespaceID, key) if err != nil { diff --git a/internal/provider/resource_cloudflare_worker_route.go b/internal/provider/resource_cloudflare_worker_route.go index 8874ab26269..3aeff05a413 100644 --- a/internal/provider/resource_cloudflare_worker_route.go +++ b/internal/provider/resource_cloudflare_worker_route.go @@ -7,6 +7,7 @@ import ( "strings" 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/pkg/errors" @@ -39,7 +40,7 @@ func resourceCloudflareWorkerRouteCreate(ctx context.Context, d *schema.Resource route := getRouteFromResource(d) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Creating Cloudflare Worker Route from struct: %+v", route) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare Worker Route from struct: %+v", route)) r, err := client.CreateWorkerRoute(ctx, zoneID, route) if err != nil { @@ -52,7 +53,7 @@ func resourceCloudflareWorkerRouteCreate(ctx context.Context, d *schema.Resource d.SetId(r.ID) - log.Printf("[INFO] Cloudflare Worker Route ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Worker Route ID: %s", d.Id())) return nil } diff --git a/internal/provider/resource_cloudflare_worker_script.go b/internal/provider/resource_cloudflare_worker_script.go index 818058a5c88..d1c01138117 100644 --- a/internal/provider/resource_cloudflare_worker_script.go +++ b/internal/provider/resource_cloudflare_worker_script.go @@ -5,10 +5,10 @@ import ( "encoding/base64" "fmt" "io/ioutil" - "log" "strings" 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/pkg/errors" @@ -114,7 +114,7 @@ func resourceCloudflareWorkerScriptCreate(ctx context.Context, d *schema.Resourc return diag.FromErr(fmt.Errorf("script content cannot be empty")) } - log.Printf("[INFO] Creating Cloudflare Worker Script from struct: %+v", &scriptData.Params) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare Worker Script from struct: %+v", &scriptData.Params)) bindings := make(ScriptBindings) @@ -240,7 +240,7 @@ func resourceCloudflareWorkerScriptUpdate(ctx context.Context, d *schema.Resourc return diag.FromErr(fmt.Errorf("script content cannot be empty")) } - log.Printf("[INFO] Updating Cloudflare Worker Script from struct: %+v", &scriptData.Params) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare Worker Script from struct: %+v", &scriptData.Params)) bindings := make(ScriptBindings) @@ -267,7 +267,7 @@ func resourceCloudflareWorkerScriptDelete(ctx context.Context, d *schema.Resourc return diag.FromErr(err) } - log.Printf("[INFO] Deleting Cloudflare Worker Script from struct: %+v", &scriptData.Params) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Worker Script from struct: %+v", &scriptData.Params)) _, err = client.DeleteWorker(ctx, &scriptData.Params) if err != nil { diff --git a/internal/provider/resource_cloudflare_workers_kv_namespace.go b/internal/provider/resource_cloudflare_workers_kv_namespace.go index 854b4d458ff..ce4ca937f0f 100644 --- a/internal/provider/resource_cloudflare_workers_kv_namespace.go +++ b/internal/provider/resource_cloudflare_workers_kv_namespace.go @@ -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" "github.com/pkg/errors" @@ -31,7 +31,7 @@ func resourceCloudflareWorkersKVNamespaceCreate(ctx context.Context, d *schema.R Title: d.Get("title").(string), } - log.Printf("[Info] Creating Cloudflare Workers KV Namespace from struct: %+v", req) + tflog.Debug(ctx, fmt.Sprintf("[Info] Creating Cloudflare Workers KV Namespace from struct: %+v", req)) r, err := client.CreateWorkersKVNamespace(ctx, req) if err != nil { @@ -44,7 +44,7 @@ func resourceCloudflareWorkersKVNamespaceCreate(ctx context.Context, d *schema.R d.SetId(r.Result.ID) - log.Printf("[INFO] Cloudflare Workers KV Namespace ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Workers KV Namespace ID: %s", d.Id())) return nil } @@ -81,7 +81,7 @@ func resourceCloudflareWorkersKVNamespaceUpdate(ctx context.Context, d *schema.R Title: d.Get("title").(string), } - log.Printf("[INFO] Updating Cloudflare Workers KV Namespace from struct %+v", namespace) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare Workers KV Namespace from struct %+v", namespace)) _, err := client.UpdateWorkersKVNamespace(ctx, d.Id(), namespace) if err != nil { @@ -94,7 +94,7 @@ func resourceCloudflareWorkersKVNamespaceUpdate(ctx context.Context, d *schema.R func resourceCloudflareWorkersKVNamespaceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting Cloudflare Workers KV Namespace with id: %+v", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Workers KV Namespace with id: %+v", d.Id())) _, err := client.DeleteWorkersKVNamespace(ctx, d.Id()) if err != nil { diff --git a/internal/provider/resource_cloudflare_zone.go b/internal/provider/resource_cloudflare_zone.go index f921571da4e..74d32e42ded 100644 --- a/internal/provider/resource_cloudflare_zone.go +++ b/internal/provider/resource_cloudflare_zone.go @@ -9,6 +9,7 @@ import ( "golang.org/x/net/idna" 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/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -97,7 +98,7 @@ func resourceCloudflareZoneCreate(ctx context.Context, d *schema.ResourceData, m ID: client.AccountID, } - log.Printf("[INFO] Creating Cloudflare Zone: name %s", zoneName) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare Zone: name %s", zoneName)) zone, err := client.CreateZone(ctx, zoneName, jumpstart, account, zoneType) @@ -139,12 +140,12 @@ func resourceCloudflareZoneRead(ctx context.Context, d *schema.ResourceData, met zone, err := client.ZoneDetails(ctx, zoneID) - log.Printf("[DEBUG] ZoneDetails: %#v", zone) - log.Printf("[DEBUG] ZoneDetails error: %#v", err) + tflog.Debug(ctx, fmt.Sprintf("ZoneDetails: %#v", zone)) + tflog.Debug(ctx, fmt.Sprintf("ZoneDetails error: %#v", err)) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Zone %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Zone %s no longer exists", d.Id())) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_zone_cache_variants.go b/internal/provider/resource_cloudflare_zone_cache_variants.go index d7fb1d6532d..00201999c74 100644 --- a/internal/provider/resource_cloudflare_zone_cache_variants.go +++ b/internal/provider/resource_cloudflare_zone_cache_variants.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -24,13 +24,13 @@ func resourceCloudflareZoneCacheVariants() *schema.Resource { func resourceCloudflareZoneCacheVariantsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[INFO] Reading Zone Cache Variants in zone %q", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Reading Zone Cache Variants in zone %q", d.Id())) zoneCacheVariants, err := client.ZoneCacheVariants(ctx, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Zone Cache Variants for zone %q not found", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Zone Cache Variants for zone %q not found", d.Id())) d.SetId("") return nil } else { @@ -94,7 +94,7 @@ func resourceCloudflareZoneCacheVariantsUpdate(ctx context.Context, d *schema.Re d.SetId(zoneID) variantsValue := cacheVariantsValuesFromResource(d) - log.Printf("[INFO] Setting Zone Cache Variants to struct: %+v for zone ID: %q", variantsValue, d.Id()) + tflog.Info(ctx, fmt.Sprintf("Setting Zone Cache Variants to struct: %+v for zone ID: %q", variantsValue, d.Id())) _, err := client.UpdateZoneCacheVariants(ctx, d.Id(), variantsValue) @@ -108,7 +108,7 @@ func resourceCloudflareZoneCacheVariantsUpdate(ctx context.Context, d *schema.Re func resourceCloudflareZoneCacheVariantsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { client := meta.(*cloudflare.API) - log.Printf("[INFO] Deleting Zone Cache Variants for zone ID: %q", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Deleting Zone Cache Variants for zone ID: %q", d.Id())) err := client.DeleteZoneCacheVariants(ctx, d.Id()) diff --git a/internal/provider/resource_cloudflare_zone_cache_variants_test.go b/internal/provider/resource_cloudflare_zone_cache_variants_test.go index 5cde3669382..a6e64d10524 100644 --- a/internal/provider/resource_cloudflare_zone_cache_variants_test.go +++ b/internal/provider/resource_cloudflare_zone_cache_variants_test.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "os" "testing" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -18,14 +18,15 @@ func init() { } func testSweepCloudflareZoneCacheVariants(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)) } zoneID := os.Getenv("CLOUDFLARE_ZONE_ID") - log.Printf("[INFO] Deleting Zone Cache Variants for zone: %q", zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Zone Cache Variants for zone: %q", zoneID)) client.DeleteZoneCacheVariants(context.Background(), zoneID) return nil diff --git a/internal/provider/resource_cloudflare_zone_dnssec.go b/internal/provider/resource_cloudflare_zone_dnssec.go index efdc4dbd4a7..cf1e4a0d073 100644 --- a/internal/provider/resource_cloudflare_zone_dnssec.go +++ b/internal/provider/resource_cloudflare_zone_dnssec.go @@ -3,11 +3,11 @@ package provider import ( "context" "fmt" - "log" "strings" "time" "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" ) @@ -37,7 +37,7 @@ func resourceCloudflareZoneDNSSECCreate(ctx context.Context, d *schema.ResourceD zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Creating Cloudflare Zone DNSSEC: name %s", zoneID) + tflog.Info(ctx, fmt.Sprintf("Creating Cloudflare Zone DNSSEC: name %s", zoneID)) currentDNSSEC, err := client.ZoneDNSSECSetting(ctx, zoneID) if err != nil { @@ -102,13 +102,13 @@ func resourceCloudflareZoneDNSSECDelete(ctx context.Context, d *schema.ResourceD zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Deleting Cloudflare Zone DNSSEC: id %s", zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Zone DNSSEC: id %s", zoneID)) _, err := client.UpdateZoneDNSSEC(ctx, zoneID, cloudflare.ZoneDNSSECUpdateOptions{Status: DNSSECStatusDisabled}) if err != nil { if strings.Contains(err.Error(), "DNSSEC is already disabled") { - log.Printf("[INFO] Zone DNSSEC %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Zone DNSSEC %s no longer exists", d.Id())) d.SetId("") return nil } diff --git a/internal/provider/resource_cloudflare_zone_lockdown.go b/internal/provider/resource_cloudflare_zone_lockdown.go index 2d36b251af7..1a128aacb93 100644 --- a/internal/provider/resource_cloudflare_zone_lockdown.go +++ b/internal/provider/resource_cloudflare_zone_lockdown.go @@ -3,10 +3,10 @@ package provider import ( "context" "fmt" - "log" "strings" 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" ) @@ -52,7 +52,7 @@ func resourceCloudflareZoneLockdownCreate(ctx context.Context, d *schema.Resourc newZoneLockdown.Configurations = expandZoneLockdownConfig(configurations.(*schema.Set)) } - log.Printf("[DEBUG] Creating Cloudflare Zone Lockdown from struct: %+v", newZoneLockdown) + tflog.Debug(ctx, fmt.Sprintf("Creating Cloudflare Zone Lockdown from struct: %+v", newZoneLockdown)) var r *cloudflare.ZoneLockdownResponse @@ -68,7 +68,7 @@ func resourceCloudflareZoneLockdownCreate(ctx context.Context, d *schema.Resourc d.SetId(r.Result.ID) - log.Printf("[INFO] Cloudflare Zone Lockdown ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Zone Lockdown ID: %s", d.Id())) return resourceCloudflareZoneLockdownRead(ctx, d, meta) } @@ -79,25 +79,25 @@ func resourceCloudflareZoneLockdownRead(ctx context.Context, d *schema.ResourceD zoneLockdownResponse, err := client.ZoneLockdown(ctx, zoneID, d.Id()) - log.Printf("[DEBUG] zoneLockdownResponse: %#v", zoneLockdownResponse) - log.Printf("[DEBUG] zoneLockdownResponse error: %#v", err) + tflog.Debug(ctx, fmt.Sprintf("zoneLockdownResponse: %#v", zoneLockdownResponse)) + tflog.Debug(ctx, fmt.Sprintf("zoneLockdownResponse error: %#v", err)) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Zone Lockdown %s no longer exists", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Zone Lockdown %s no longer exists", d.Id())) d.SetId("") return nil } return diag.FromErr(fmt.Errorf("error finding zone lockdown %q: %w", d.Id(), err)) } - log.Printf("[DEBUG] Cloudflare Zone Lockdown read configuration: %#v", zoneLockdownResponse) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Zone Lockdown read configuration: %#v", zoneLockdownResponse)) d.Set("paused", zoneLockdownResponse.Result.Paused) d.Set("priority", zoneLockdownResponse.Result.Priority) d.Set("description", zoneLockdownResponse.Result.Description) d.Set("urls", zoneLockdownResponse.Result.URLs) - log.Printf("[DEBUG] read configurations: %#v", d.Get("configurations")) + tflog.Debug(ctx, fmt.Sprintf("read configurations: %#v", d.Get("configurations"))) configurations := make([]map[string]interface{}, len(zoneLockdownResponse.Result.Configurations)) @@ -107,10 +107,10 @@ func resourceCloudflareZoneLockdownRead(ctx context.Context, d *schema.ResourceD "value": entryconfigZoneLockdownConfig.Value, } } - log.Printf("[DEBUG] Cloudflare Zone Lockdown configuration: %#v", configurations) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Zone Lockdown configuration: %#v", configurations)) if err := d.Set("configurations", configurations); err != nil { - log.Printf("[WARN] Error setting configurations in zone lockdown %q: %s", d.Id(), err) + tflog.Warn(ctx, fmt.Sprintf("Error setting configurations in zone lockdown %q: %s", d.Id(), err)) } return nil @@ -142,7 +142,7 @@ func resourceCloudflareZoneLockdownUpdate(ctx context.Context, d *schema.Resourc newZoneLockdown.Configurations = expandZoneLockdownConfig(configurations.(*schema.Set)) } - log.Printf("[INFO] Updating Cloudflare Zone Lockdown from struct: %+v", newZoneLockdown) + tflog.Info(ctx, fmt.Sprintf("Updating Cloudflare Zone Lockdown from struct: %+v", newZoneLockdown)) r, err := client.UpdateZoneLockdown(ctx, zoneID, d.Id(), newZoneLockdown) @@ -156,7 +156,7 @@ func resourceCloudflareZoneLockdownUpdate(ctx context.Context, d *schema.Resourc d.SetId(r.Result.ID) - log.Printf("[INFO] Cloudflare Zone Lockdown ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Cloudflare Zone Lockdown ID: %s", d.Id())) return resourceCloudflareZoneLockdownRead(ctx, d, meta) } @@ -165,7 +165,7 @@ func resourceCloudflareZoneLockdownDelete(ctx context.Context, d *schema.Resourc client := meta.(*cloudflare.API) zoneID := d.Get("zone_id").(string) - log.Printf("[INFO] Deleting Cloudflare Zone Lockdown: id %s for zone %s", d.Id(), zoneID) + tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Zone Lockdown: id %s for zone %s", d.Id(), zoneID)) _, err := client.DeleteZoneLockdown(ctx, zoneID, d.Id()) @@ -202,8 +202,8 @@ func resourceCloudflareZoneLockdownImport(ctx context.Context, d *schema.Resourc return nil, fmt.Errorf("invalid id (%q) specified, should be in format \"zoneID/zoneLockdownId\"", d.Id()) } - log.Printf("[DEBUG] zoneID: %s", zoneID) - log.Printf("[DEBUG] Resource ID : %s", zoneLockdownID) + tflog.Debug(ctx, fmt.Sprintf("zoneID: %s", zoneID)) + tflog.Debug(ctx, fmt.Sprintf("Resource ID : %s", zoneLockdownID)) resourceCloudflareZoneLockdownRead(ctx, d, meta) diff --git a/internal/provider/resource_cloudflare_zone_settings_override.go b/internal/provider/resource_cloudflare_zone_settings_override.go index 90d223cbcef..2b5d54c79e8 100644 --- a/internal/provider/resource_cloudflare_zone_settings_override.go +++ b/internal/provider/resource_cloudflare_zone_settings_override.go @@ -12,6 +12,7 @@ import ( "reflect" 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/pkg/errors" @@ -40,7 +41,7 @@ func resourceCloudflareZoneSettingsOverrideCreate(ctx context.Context, d *schema zoneID := d.Get("zone_id").(string) d.SetId(zoneID) - log.Printf("[INFO] Creating zone settings resource for zone ID: %s", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Creating zone settings resource for zone ID: %s", d.Id())) // do extra initial read to get initial_settings before updating zoneSettings, err := client.ZoneSettings(ctx, d.Id()) @@ -59,20 +60,20 @@ func resourceCloudflareZoneSettingsOverrideCreate(ctx context.Context, d *schema } } - log.Printf("[DEBUG] Read CloudflareZone initial settings: %#v", zoneSettings) + tflog.Debug(ctx, fmt.Sprintf("Read CloudflareZone initial settings: %#v", zoneSettings)) - if err := d.Set("initial_settings", flattenZoneSettings(d, zoneSettings.Result, true)); err != nil { - log.Printf("[WARN] Error setting initial_settings for zone %q: %s", d.Id(), err) + if err := d.Set("initial_settings", flattenZoneSettings(ctx, d, zoneSettings.Result, true)); err != nil { + tflog.Warn(ctx, fmt.Sprintf("Error setting initial_settings for zone %q: %s", d.Id(), err)) } d.Set("initial_settings_read_at", time.Now().UTC().Format(time.RFC3339Nano)) // set readonly setting so that update can behave correctly - if err := d.Set("readonly_settings", flattenReadOnlyZoneSettings(zoneSettings.Result)); err != nil { - log.Printf("[WARN] Error setting readonly_settings for zone %q: %s", d.Id(), err) + if err := d.Set("readonly_settings", flattenReadOnlyZoneSettings(ctx, zoneSettings.Result)); err != nil { + tflog.Warn(ctx, fmt.Sprintf("Error setting readonly_settings for zone %q: %s", d.Id(), err)) } - log.Printf("[DEBUG] Saved CloudflareZone initial settings: %#v", d.Get("initial_settings")) + tflog.Debug(ctx, fmt.Sprintf("Saved CloudflareZone initial settings: %#v", d.Get("initial_settings"))) return resourceCloudflareZoneSettingsOverrideUpdate(ctx, d, meta) } @@ -111,7 +112,7 @@ func resourceCloudflareZoneSettingsOverrideRead(ctx context.Context, d *schema.R zone, err := client.ZoneDetails(ctx, d.Id()) if err != nil { if strings.Contains(err.Error(), "HTTP status 404") { - log.Printf("[INFO] Zone %q not found", d.Id()) + tflog.Info(ctx, fmt.Sprintf("Zone %q not found", d.Id())) d.SetId("") return nil } else { @@ -138,12 +139,12 @@ func resourceCloudflareZoneSettingsOverrideRead(ctx context.Context, d *schema.R } } - log.Printf("[DEBUG] Read CloudflareZone Settings: %#v", zoneSettings) + tflog.Debug(ctx, fmt.Sprintf("Read CloudflareZone Settings: %#v", zoneSettings)) d.Set("zone_status", zone.Status) d.Set("zone_type", zone.Type) - newZoneSettings := flattenZoneSettings(d, zoneSettings.Result, false) + newZoneSettings := flattenZoneSettings(ctx, d, zoneSettings.Result, false) // if polish is off (or we don't know) we need to ignore what comes back from the api for webp if polish, ok := newZoneSettings[0]["polish"]; !ok || polish.(string) == "" || polish.(string) == "off" { newZoneSettings[0]["webp"] = d.Get("settings.0.webp").(string) @@ -153,14 +154,14 @@ func resourceCloudflareZoneSettingsOverrideRead(ctx context.Context, d *schema.R log.Printf("[WARN] Error setting settings for zone %q: %s", d.Id(), err) } - if err := d.Set("readonly_settings", flattenReadOnlyZoneSettings(zoneSettings.Result)); err != nil { + if err := d.Set("readonly_settings", flattenReadOnlyZoneSettings(ctx, zoneSettings.Result)); err != nil { log.Printf("[WARN] Error setting readonly_settings for zone %q: %s", d.Id(), err) } return nil } -func flattenZoneSettings(d *schema.ResourceData, settings []cloudflare.ZoneSetting, flattenAll bool) []map[string]interface{} { +func flattenZoneSettings(ctx context.Context, d *schema.ResourceData, settings []cloudflare.ZoneSetting, flattenAll bool) []map[string]interface{} { cfg := map[string]interface{}{} for _, s := range settings { if s.ID == "0rtt" { // NOTE: 0rtt is an invalid attribute in HCLs grammar. Remap to `zero_rtt` @@ -187,11 +188,11 @@ func flattenZoneSettings(d *schema.ResourceData, settings []cloudflare.ZoneSetti } else if floatValue, ok := s.Value.(float64); ok { cfg[s.ID] = int(floatValue) } else { - log.Printf("[WARN] Unexpected value type found in API zone settings - %q : %#v", s.ID, s.Value) + tflog.Warn(ctx, fmt.Sprintf("Unexpected value type found in API zone settings - %q : %#v", s.ID, s.Value)) } } - log.Printf("[DEBUG] Flattened Cloudflare Zone Settings: %#v", cfg) + tflog.Debug(ctx, fmt.Sprintf("Flattened Cloudflare Zone Settings: %#v", cfg)) return []map[string]interface{}{cfg} } @@ -205,14 +206,14 @@ func settingInSchema(val string) bool { return false } -func flattenReadOnlyZoneSettings(settings []cloudflare.ZoneSetting) []string { +func flattenReadOnlyZoneSettings(ctx context.Context, settings []cloudflare.ZoneSetting) []string { ids := make([]string, 0) for _, zs := range settings { if !zs.Editable { ids = append(ids, zs.ID) } } - log.Printf("[DEBUG] Flattened Cloudflare Read Only Zone Settings: %#v", ids) + tflog.Debug(ctx, fmt.Sprintf("Flattened Cloudflare Read Only Zone Settings: %#v", ids)) return ids } @@ -267,7 +268,7 @@ func resourceCloudflareZoneSettingsOverrideUpdate(ctx context.Context, d *schema return diag.FromErr(err) } - log.Printf("[DEBUG] Cloudflare Zone Settings update configuration: %#v", zoneSettings) + tflog.Debug(ctx, fmt.Sprintf("Cloudflare Zone Settings update configuration: %#v", zoneSettings)) if zoneSettings, err = updateSingleZoneSettings(ctx, zoneSettings, client, d.Id()); err != nil { return diag.FromErr(err) @@ -283,7 +284,7 @@ func resourceCloudflareZoneSettingsOverrideUpdate(ctx context.Context, d *schema return diag.FromErr(err) } } else { - log.Printf("[DEBUG] Skipped update call because no settings were set") + tflog.Debug(ctx, fmt.Sprintf("Skipped update call because no settings were set")) } } @@ -373,7 +374,7 @@ func resourceCloudflareZoneSettingsOverrideDelete(ctx context.Context, d *schema return diag.FromErr(err) } - log.Printf("[DEBUG] Reverting Cloudflare Zone Settings to initial settings with update configuration: %#v", zoneSettings) + tflog.Debug(ctx, fmt.Sprintf("Reverting Cloudflare Zone Settings to initial settings with update configuration: %#v", zoneSettings)) if zoneSettings, err = updateSingleZoneSettings(ctx, zoneSettings, client, d.Id()); err != nil { return diag.FromErr(err) @@ -389,7 +390,7 @@ func resourceCloudflareZoneSettingsOverrideDelete(ctx context.Context, d *schema return diag.FromErr(err) } } else { - log.Printf("[DEBUG] Skipped call to revert settings because no settings were changed") + tflog.Debug(ctx, fmt.Sprintf("Skipped call to revert settings because no settings were changed")) } } return nil