Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Feat add azure containers cache #24040

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions internal/services/containers/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2023-05-01/containerinstance"
containerregistry_v2019_06_01_preview "github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2019-06-01-preview"
containerregistry_v2021_08_01_preview "github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2021-08-01-preview"
containerregistry_v2023_07_01 "github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2023-07-01"
"github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2023-07-01/cacherules"
"github.com/hashicorp/go-azure-sdk/resource-manager/containerservice/2019-08-01/containerservices"
"github.com/hashicorp/go-azure-sdk/resource-manager/containerservice/2023-04-02-preview/agentpools"
"github.com/hashicorp/go-azure-sdk/resource-manager/containerservice/2023-04-02-preview/maintenanceconfigurations"
Expand All @@ -24,6 +26,7 @@ import (
type Client struct {
AgentPoolsClient *agentpools.AgentPoolsClient
ContainerInstanceClient *containerinstance.ContainerInstanceClient
ContainerRegistryClient_v2023_07_01 *containerregistry_v2023_07_01.Client
ContainerRegistryClient_v2021_08_01_preview *containerregistry_v2021_08_01_preview.Client
// v2019_06_01_preview is needed for container registry agent pools and tasks
ContainerRegistryClient_v2019_06_01_preview *containerregistry_v2019_06_01_preview.Client
Expand All @@ -37,6 +40,12 @@ type Client struct {
}

func NewContainersClient(o *common.ClientOptions) (*Client, error) {
cacheRulesClient, err := cacherules.NewCacheRulesClientWithBaseURI(o.Environment.ResourceManager)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this declaration of the cacheRulesClient is necessary for the new SDK clients anymore

if err != nil {
return nil, fmt.Errorf("building Cache Rules Client: %+v", err)
}
o.Configure(cacheRulesClient.Client, o.Authorizers.ResourceManager)

containerInstanceClient := containerinstance.NewContainerInstanceClientWithBaseURI(o.ResourceManagerEndpoint)
o.ConfigureClient(&containerInstanceClient.Client, o.ResourceManagerAuthorizer)

Expand All @@ -54,6 +63,13 @@ func NewContainersClient(o *common.ClientOptions) (*Client, error) {
return nil, err
}

containerRegistryClient_v2023_07_01, err := containerregistry_v2023_07_01.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) {
o.Configure(c, o.Authorizers.ResourceManager)
})
if err != nil {
return nil, err
}

// AKS
kubernetesClustersClient := managedclusters.NewManagedClustersClientWithBaseURI(o.ResourceManagerEndpoint)
o.ConfigureClient(&kubernetesClustersClient.Client, o.ResourceManagerAuthorizer)
Expand Down Expand Up @@ -85,6 +101,7 @@ func NewContainersClient(o *common.ClientOptions) (*Client, error) {
return &Client{
AgentPoolsClient: &agentPoolsClient,
ContainerInstanceClient: &containerInstanceClient,
ContainerRegistryClient_v2023_07_01: containerRegistryClient_v2023_07_01,
ContainerRegistryClient_v2021_08_01_preview: containerRegistryClient_v2021_08_01_preview,
ContainerRegistryClient_v2019_06_01_preview: containerRegistryClient_v2019_06_01_preview,
KubernetesClustersClient: &kubernetesClustersClient,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package containers

import (
"context"
"fmt"
"log"
"time"

"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2023-07-01/cacherules"
"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/validate"
containerValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
)

var _ sdk.Resource = ContainerRegistryCacheRule{}

type ContainerRegistryCacheRule struct{}

func (ContainerRegistryCacheRule) Arguments() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
Description: "The name of the cache rule.",
},

"registry": {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would opt for container_registry_id here, which contains both the resource group name and registry name, as input.

How to work with that ID is shown here:

ContainerRegistryId string `tfschema:"container_registry_id"`

Type: pluginsdk.TypeString,
Required: true,
Description: "The name of the container registry.",
ValidateFunc: containerValidate.ContainerRegistryName,
},

"source_repo": {
Type: pluginsdk.TypeString,
Required: true,
Description: "The full source repository path such as 'docker.io/library/ubuntu'.",
},

"target_repo": {
Type: pluginsdk.TypeString,
Required: true,
Description: "The target repository namespace such as 'ubuntu'.",
},
}
}

func (ContainerRegistryCacheRule) Attributes() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{}
}

func (ContainerRegistryCacheRule) ModelObject() interface{} {
return nil
}

func (ContainerRegistryCacheRule) ResourceType() string {
return "azurerm_container_registry_cache_rule"
}

func (r ContainerRegistryCacheRule) Create() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
cacheRulesClient := metadata.Client.Containers.ContainerRegistryClient_v2023_07_01.CacheRules
subscriptionId := metadata.Client.Account.SubscriptionId
ctx, cancel := timeouts.ForCreate(metadata.Client.StopContext, metadata.ResourceData)

defer cancel()
log.Printf("[INFO] preparing arguments for Container Registry Cache Rule creation.")

id := cacherules.NewCacheRuleID(subscriptionId,
metadata.ResourceData.Get("resource_group_name").(string),
metadata.ResourceData.Get("registry").(string),
metadata.ResourceData.Get("name").(string),
)

if metadata.ResourceData.IsNewResource() {
existing, err := cacheRulesClient.Get(ctx, id)

if err != nil {
if !response.WasNotFound(existing.HttpResponse) {
return fmt.Errorf("checking for presence of existing %s: %s", id, err)
}
}

if !response.WasNotFound(existing.HttpResponse) {
return tf.ImportAsExistsError("azurerm_container_registry_cache_rule", id.ID())
}

// TODO: make a check that the repo is available in the registry.
targetRepo := metadata.ResourceData.Get("target_repo").(string)

// TODO: validate the source repo.
sourceRepo := metadata.ResourceData.Get("source_repo").(string)

parameters := cacherules.CacheRule{
Name: &id.CacheRuleName,
Properties: &cacherules.CacheRuleProperties{
SourceRepository: &sourceRepo,
TargetRepository: &targetRepo,
},
}

if err := cacheRulesClient.CreateThenPoll(ctx, id, parameters); err != nil {
return fmt.Errorf("creating Container Registry Cache Rule %s: %+v", id, err)
}
}

metadata.SetID(id)

return r.Read().Func(ctx, metadata)
},
}
}

func (ContainerRegistryCacheRule) Read() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 5 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
cacheRulesClient := metadata.Client.Containers.ContainerRegistryClient_v2023_07_01.CacheRules
ctx, cancel := timeouts.ForRead(metadata.Client.StopContext, metadata.ResourceData)
defer cancel()

id, err := cacherules.ParseCacheRuleID(metadata.ResourceData.Id())
if err != nil {
return err
}

resp, err := cacheRulesClient.Get(ctx, *id)
if err != nil {
if response.WasNotFound(resp.HttpResponse) {
log.Printf("[DEBUG] Container Registry Cache Rule %s was not found.", *id)
return metadata.MarkAsGone(id)
}

return fmt.Errorf("retrieving Container Registry Cache Rule %s: %+v", *id, err)
}

metadata.ResourceData.Set("name", id.CacheRuleName)
metadata.ResourceData.Set("registry", id.RegistryName)

if model := resp.Model; model != nil {
if properties := model.Properties; properties != nil {
metadata.ResourceData.Set("source_repo", properties.SourceRepository)
metadata.ResourceData.Set("target_repo", properties.TargetRepository)
}
}

return nil
},
}
}

func (r ContainerRegistryCacheRule) Update() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
cacheRulesClient := metadata.Client.Containers.ContainerRegistryClient_v2023_07_01.CacheRules
ctx, cancel := timeouts.ForRead(metadata.Client.StopContext, metadata.ResourceData)

defer cancel()
log.Printf("[INFO] preparing arguments for Container Registry Cache Rule update.")

id, err := cacherules.ParseCacheRuleID(metadata.ResourceData.Id())
if err != nil {
return err
}

// TODO: You can only update the credential set. To be implemented
parameters := cacherules.CacheRuleUpdateParameters{
Properties: &cacherules.CacheRuleUpdateProperties{},
}

if err := cacheRulesClient.UpdateThenPoll(ctx, *id, parameters); err != nil {
return fmt.Errorf("updating %s: %+v", id, err)
}

metadata.SetID(id)

return nil
},
}
}

func (ContainerRegistryCacheRule) Delete() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
cacheRulesClient := metadata.Client.Containers.ContainerRegistryClient_v2023_07_01.CacheRules
ctx, cancel := timeouts.ForDelete(metadata.Client.StopContext, metadata.ResourceData)
defer cancel()

id, err := cacherules.ParseCacheRuleID(metadata.ResourceData.Id())
if err != nil {
return err
}

if err := cacheRulesClient.DeleteThenPoll(ctx, *id); err != nil {
return fmt.Errorf("deleting Container Registry Cache Rule %s: %+v", *id, err)
}

return nil
},
}
}

func (ContainerRegistryCacheRule) IDValidationFunc() pluginsdk.SchemaValidateFunc {
return validate.ContainerRegistryCacheRuleID
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you can replace the validate package with the content of cacherules in the new SDK, like this:

Suggested change
return validate.ContainerRegistryCacheRuleID
return cacherules.ValidateCacheRuleID

}
Loading