diff --git a/.teamcity/components/generated/services.kt b/.teamcity/components/generated/services.kt index 0119bb49002b..57dcfe9c2a02 100644 --- a/.teamcity/components/generated/services.kt +++ b/.teamcity/components/generated/services.kt @@ -49,6 +49,7 @@ var services = mapOf( "iotcentral" to "IoT Central", "iothub" to "IoT Hub", "keyvault" to "KeyVault", + "kubernetes" to "Kubernetes", "kusto" to "Kusto", "lighthouse" to "Lighthouse", "loadbalancer" to "Load Balancer", diff --git a/internal/clients/client.go b/internal/clients/client.go index 0dfed7662fe5..cc2811c70d6f 100644 --- a/internal/clients/client.go +++ b/internal/clients/client.go @@ -56,6 +56,7 @@ import ( iothub "github.com/hashicorp/terraform-provider-azurerm/internal/services/iothub/client" timeseriesinsights "github.com/hashicorp/terraform-provider-azurerm/internal/services/iottimeseriesinsights/client" keyvault "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/client" + kubernetes "github.com/hashicorp/terraform-provider-azurerm/internal/services/kubernetes/client" kusto "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/client" lighthouse "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse/client" loadbalancers "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/client" @@ -166,6 +167,7 @@ type Client struct { IoTHub *iothub.Client IoTTimeSeriesInsights *timeseriesinsights.Client KeyVault *keyvault.Client + Kubernetes *kubernetes.Client Kusto *kusto.Client Lighthouse *lighthouse.Client LoadBalancers *loadbalancers.Client @@ -278,6 +280,7 @@ func (client *Client) Build(ctx context.Context, o *common.ClientOptions) error client.IoTHub = iothub.NewClient(o) client.IoTTimeSeriesInsights = timeseriesinsights.NewClient(o) client.KeyVault = keyvault.NewClient(o) + client.Kubernetes = kubernetes.NewClient(o) client.Kusto = kusto.NewClient(o) client.Lighthouse = lighthouse.NewClient(o) client.LogAnalytics = loganalytics.NewClient(o) diff --git a/internal/provider/services.go b/internal/provider/services.go index e8f81814dcf4..7325026b61e7 100644 --- a/internal/provider/services.go +++ b/internal/provider/services.go @@ -52,6 +52,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/iothub" "github.com/hashicorp/terraform-provider-azurerm/internal/services/iottimeseriesinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/kubernetes" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto" "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer" @@ -181,6 +182,7 @@ func SupportedUntypedServices() []sdk.UntypedServiceRegistration { iothub.Registration{}, iotcentral.Registration{}, keyvault.Registration{}, + kubernetes.Registration{}, kusto.Registration{}, loadbalancer.Registration{}, loganalytics.Registration{}, diff --git a/internal/services/kubernetes/client/client.go b/internal/services/kubernetes/client/client.go new file mode 100644 index 000000000000..fae08c50dd34 --- /dev/null +++ b/internal/services/kubernetes/client/client.go @@ -0,0 +1,20 @@ +package client + +import ( + "github.com/hashicorp/terraform-provider-azurerm/internal/common" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/kubernetes/sdk/2021-10-01/kubernetes" +) + +type Client struct { + KubernetesClient *kubernetes.KubernetesClient +} + +func NewClient(o *common.ClientOptions) *Client { + + kubernetesClient := kubernetes.NewKubernetesClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&kubernetesClient.Client, o.ResourceManagerAuthorizer) + + return &Client{ + KubernetesClient: &kubernetesClient, + } +} diff --git a/internal/services/kubernetes/kubernetes_connected_cluster_resource.go b/internal/services/kubernetes/kubernetes_connected_cluster_resource.go new file mode 100644 index 000000000000..6914ec865dce --- /dev/null +++ b/internal/services/kubernetes/kubernetes_connected_cluster_resource.go @@ -0,0 +1,206 @@ +package kubernetes + +import ( + "fmt" + "time" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + tagsHelper "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/location" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/kubernetes/sdk/2021-10-01/kubernetes" + "github.com/hashicorp/terraform-provider-azurerm/internal/tags" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +func resourceKubernetesConnectedCluster() *pluginsdk.Resource { + return &pluginsdk.Resource{ + Create: resourceKubernetesConnectedClusterCreate, + Read: resourceKubernetesConnectedClusterRead, + Update: resourceKubernetesConnectedClusterUpdate, + Delete: resourceKubernetesConnectedClusterDelete, + + Timeouts: &pluginsdk.ResourceTimeout{ + Create: pluginsdk.DefaultTimeout(30 * time.Minute), + Read: pluginsdk.DefaultTimeout(5 * time.Minute), + Update: pluginsdk.DefaultTimeout(30 * time.Minute), + Delete: pluginsdk.DefaultTimeout(30 * time.Minute), + }, + + Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { + _, err := kubernetes.ParseConnectedClusterID(id) + return err + }), + + Schema: map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": azure.SchemaResourceGroupName(), + + "agent_public_key_certificate": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + }, + + "distribution": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + }, + + "identity": commonschema.SystemAssignedIdentityRequired(), + + "infrastructure": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + }, + + "location": azure.SchemaLocation(), + + "provisioning_state": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "tags": tags.Schema(), + }, + } +} + +func resourceKubernetesConnectedClusterCreate(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Kubernetes.KubernetesClient + subscriptionId := meta.(*clients.Client).Account.SubscriptionId + ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) + defer cancel() + + id := kubernetes.NewConnectedClusterID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + + if d.IsNewResource() { + existing, err := client.ConnectedClusterGet(ctx, id) + if err != nil { + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for existing %s: %+v", id, err) + } + } + + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_kubernetes_connected_cluster", id.ID()) + } + } + + identity, err := identity.ExpandSystemAssigned(d.Get("identity").([]interface{})) + if err != nil { + return fmt.Errorf("expanding `identity`: %+v", err) + } + + location := azure.NormalizeLocation(d.Get("location")) + props := kubernetes.ConnectedCluster{ + Identity: *identity, + Location: location, + Properties: kubernetes.ConnectedClusterProperties{ + AgentPublicKeyCertificate: d.Get("agent_public_key_certificate").(string), + Distribution: utils.String(d.Get("distribution").(string)), + Infrastructure: utils.String(d.Get("infrastructure").(string)), + }, + Tags: tagsHelper.Expand(d.Get("tags").(map[string]interface{})), + } + + if err := client.ConnectedClusterCreateThenPoll(ctx, id, props); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) + } + + d.SetId(id.ID()) + return resourceKubernetesConnectedClusterRead(d, meta) +} + +func resourceKubernetesConnectedClusterRead(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Kubernetes.KubernetesClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := kubernetes.ParseConnectedClusterID(d.Id()) + if err != nil { + return err + } + + resp, err := client.ConnectedClusterGet(ctx, *id) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { + d.SetId("") + return nil + } + + return fmt.Errorf("retrieving %s: %+v", id, err) + } + + d.Set("name", id.ClusterName) + d.Set("resource_group_name", id.ResourceGroupName) + if model := resp.Model; model != nil { + if err := d.Set("identity", identity.FlattenSystemAssigned(&model.Identity)); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) + } + + d.Set("location", location.Normalize(model.Location)) + props := model.Properties + d.Set("agent_public_key_certificate", props.AgentPublicKeyCertificate) + d.Set("distribution", props.Distribution) + d.Set("infrastructure", props.Infrastructure) + d.Set("provisioning_state", props.ProvisioningState) + + if err := tagsHelper.FlattenAndSet(d, model.Tags); err != nil { + return err + } + } + + return nil +} + +func resourceKubernetesConnectedClusterUpdate(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Kubernetes.KubernetesClient + ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := kubernetes.ParseConnectedClusterID(d.Id()) + if err != nil { + return err + } + + props := kubernetes.ConnectedClusterPatch{ + Tags: tagsHelper.Expand(d.Get("tags").(map[string]interface{})), + } + + if _, err := client.ConnectedClusterUpdate(ctx, *id, props); err != nil { + return fmt.Errorf("updating %s: %+v", id, err) + } + + return resourceKubernetesConnectedClusterRead(d, meta) +} + +func resourceKubernetesConnectedClusterDelete(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Kubernetes.KubernetesClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := kubernetes.ParseConnectedClusterID(d.Id()) + if err != nil { + return err + } + + if err := client.ConnectedClusterDeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) + } + + return nil +} diff --git a/internal/services/kubernetes/kubernetes_connected_cluster_resource_test.go b/internal/services/kubernetes/kubernetes_connected_cluster_resource_test.go new file mode 100644 index 000000000000..05690a567172 --- /dev/null +++ b/internal/services/kubernetes/kubernetes_connected_cluster_resource_test.go @@ -0,0 +1,192 @@ +package kubernetes_test + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/kubernetes/sdk/2021-10-01/kubernetes" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type KubernetesConnectedClusterResource struct{} + +func TestAccKubernetesConnectedCluster_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_connected_cluster", "test") + r := KubernetesConnectedClusterResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccKubernetesConnectedCluster_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_connected_cluster", "test") + r := KubernetesConnectedClusterResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} + +func TestAccKubernetesConnectedCluster_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_connected_cluster", "test") + r := KubernetesConnectedClusterResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.complete(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccKubernetesConnectedCluster_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_connected_cluster", "test") + r := KubernetesConnectedClusterResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.complete(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.update(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func (r KubernetesConnectedClusterResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := kubernetes.ParseConnectedClusterID(state.ID) + if err != nil { + return nil, err + } + + client := clients.Kubernetes.KubernetesClient + resp, err := client.ConnectedClusterGet(ctx, *id) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", id, err) + } + return utils.Bool(true), nil +} + +func (r KubernetesConnectedClusterResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-kubernetes-%d" + location = "%s" +} +`, data.RandomInteger, data.Locations.Primary) +} + +func (r KubernetesConnectedClusterResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` + %s + +resource "azurerm_kubernetes_connected_cluster" "test" { + name = "acctest-k-%d" + resource_group_name = azurerm_resource_group.test.name + agent_public_key_certificate = "MIICCgKCAgEAsSpALlON3394ysLQdRSy6cCBwL08NgZp7c1xsy0kQH/wHuixfoCwtL1OZ0a5kqod9vE6L8ICsXAE+iEdU1OspcJxL9J/gSyiOCMYPUabbYRXFy5x258RRLtn60NoaqcaDW+Z80HLwJOMECdJ/yDkuuNbnL0J2cyR8/WXjoeee8cG52QmDuxB6a4ROOushroIE2NS3FuhJh3b3Ddj+NU3gfbgIjjCMJQDpJWqUi/68lB33K1FQwuY1CCT8rKC5dDRKnlTgEWtnhBBly1D+C9GPTh7l9NTxcAEcBKo1ZIkMcixcS+gTcsTtDRRwuTtt8kybohfRMvmBA/S9bkD6cCaGJMe8YerOyJsDd4zSUHz/qN9iTt8FDdFcCIjhEdsMKl350wMj7+UNPvchlRAAve3oCIntW9063fDlQHrsaPfhCplTlKLAt1jcUkGSaeuylnRi8te+hmDCIhmo8wDqMv8Yvy7BTX4bYMg+6j0EGiIKPMRf5NHt6bXbiWEcO5LWEwgCbvpTjf7XdrU/xJ+eB+uAP1etvE0tCYAEFisfFnqNZxMQCFjovI0ZNxizrZOBznk15fWTr4KTNsPUTkEvbJfZPQqc/QyC5yqIAFHAAj+jusd4tK9f19nCsoi78xeKGH2s1zrD0AmBNGUrPLPVzgfdueadJKbVbiPteYec9qSG50CAwEAAQ==" + identity { + type = "SystemAssigned" + } + location = "%s" +} +`, template, data.RandomInteger, data.Locations.Primary) +} + +func (r KubernetesConnectedClusterResource) requiresImport(data acceptance.TestData) string { + config := r.basic(data) + return fmt.Sprintf(` + %s + +resource "azurerm_kubernetes_connected_cluster" "import" { + name = azurerm_kubernetes_connected_cluster.test.name + resource_group_name = azurerm_resource_group.test.name + agent_public_key_certificate = azurerm_kubernetes_connected_cluster.test.agent_public_key_certificate + identity { + type = "SystemAssigned" + } + location = azurerm_kubernetes_connected_cluster.test.location +} +`, config) +} + +func (r KubernetesConnectedClusterResource) complete(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` + %s + +resource "azurerm_kubernetes_connected_cluster" "test" { + name = "acctest-k-%d" + resource_group_name = azurerm_resource_group.test.name + agent_public_key_certificate = "MIICCgKCAgEAsSpALlON3394ysLQdRSy6cCBwL08NgZp7c1xsy0kQH/wHuixfoCwtL1OZ0a5kqod9vE6L8ICsXAE+iEdU1OspcJxL9J/gSyiOCMYPUabbYRXFy5x258RRLtn60NoaqcaDW+Z80HLwJOMECdJ/yDkuuNbnL0J2cyR8/WXjoeee8cG52QmDuxB6a4ROOushroIE2NS3FuhJh3b3Ddj+NU3gfbgIjjCMJQDpJWqUi/68lB33K1FQwuY1CCT8rKC5dDRKnlTgEWtnhBBly1D+C9GPTh7l9NTxcAEcBKo1ZIkMcixcS+gTcsTtDRRwuTtt8kybohfRMvmBA/S9bkD6cCaGJMe8YerOyJsDd4zSUHz/qN9iTt8FDdFcCIjhEdsMKl350wMj7+UNPvchlRAAve3oCIntW9063fDlQHrsaPfhCplTlKLAt1jcUkGSaeuylnRi8te+hmDCIhmo8wDqMv8Yvy7BTX4bYMg+6j0EGiIKPMRf5NHt6bXbiWEcO5LWEwgCbvpTjf7XdrU/xJ+eB+uAP1etvE0tCYAEFisfFnqNZxMQCFjovI0ZNxizrZOBznk15fWTr4KTNsPUTkEvbJfZPQqc/QyC5yqIAFHAAj+jusd4tK9f19nCsoi78xeKGH2s1zrD0AmBNGUrPLPVzgfdueadJKbVbiPteYec9qSG50CAwEAAQ==" + distribution = "kind" + + identity { + type = "SystemAssigned" + } + infrastructure = "generic" + location = "%s" + + tags = { + ENV = "Test" + } +} +`, template, data.RandomInteger, data.Locations.Primary) +} + +func (r KubernetesConnectedClusterResource) update(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` + %s + +resource "azurerm_kubernetes_connected_cluster" "test" { + name = "acctest-k-%d" + resource_group_name = azurerm_resource_group.test.name + agent_public_key_certificate = "MIICCgKCAgEAsSpALlON3394ysLQdRSy6cCBwL08NgZp7c1xsy0kQH/wHuixfoCwtL1OZ0a5kqod9vE6L8ICsXAE+iEdU1OspcJxL9J/gSyiOCMYPUabbYRXFy5x258RRLtn60NoaqcaDW+Z80HLwJOMECdJ/yDkuuNbnL0J2cyR8/WXjoeee8cG52QmDuxB6a4ROOushroIE2NS3FuhJh3b3Ddj+NU3gfbgIjjCMJQDpJWqUi/68lB33K1FQwuY1CCT8rKC5dDRKnlTgEWtnhBBly1D+C9GPTh7l9NTxcAEcBKo1ZIkMcixcS+gTcsTtDRRwuTtt8kybohfRMvmBA/S9bkD6cCaGJMe8YerOyJsDd4zSUHz/qN9iTt8FDdFcCIjhEdsMKl350wMj7+UNPvchlRAAve3oCIntW9063fDlQHrsaPfhCplTlKLAt1jcUkGSaeuylnRi8te+hmDCIhmo8wDqMv8Yvy7BTX4bYMg+6j0EGiIKPMRf5NHt6bXbiWEcO5LWEwgCbvpTjf7XdrU/xJ+eB+uAP1etvE0tCYAEFisfFnqNZxMQCFjovI0ZNxizrZOBznk15fWTr4KTNsPUTkEvbJfZPQqc/QyC5yqIAFHAAj+jusd4tK9f19nCsoi78xeKGH2s1zrD0AmBNGUrPLPVzgfdueadJKbVbiPteYec9qSG50CAwEAAQ==" + distribution = "kind" + + identity { + type = "SystemAssigned" + } + infrastructure = "generic" + location = "%s" + + tags = { + ENV = "TestUpdate" + } +} +`, template, data.RandomInteger, data.Locations.Primary) +} diff --git a/internal/services/kubernetes/registration.go b/internal/services/kubernetes/registration.go new file mode 100644 index 000000000000..46204bb2726e --- /dev/null +++ b/internal/services/kubernetes/registration.go @@ -0,0 +1,29 @@ +package kubernetes + +import "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + +type Registration struct{} + +// Name is the name of this Service +func (r Registration) Name() string { + return "Kubernetes" +} + +// WebsiteCategories returns a list of categories which can be used for the sidebar +func (r Registration) WebsiteCategories() []string { + return []string{ + "Kubernetes", + } +} + +// SupportedDataSources returns the supported Data Sources supported by this Service +func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource { + return map[string]*pluginsdk.Resource{} +} + +// SupportedResources returns the supported Resources supported by this Service +func (r Registration) SupportedResources() map[string]*pluginsdk.Resource { + return map[string]*pluginsdk.Resource{ + "azurerm_kubernetes_connected_cluster": resourceKubernetesConnectedCluster(), + } +} diff --git a/internal/services/kubernetes/resourceids.go b/internal/services/kubernetes/resourceids.go new file mode 100644 index 000000000000..afa9e3b5a03e --- /dev/null +++ b/internal/services/kubernetes/resourceids.go @@ -0,0 +1,3 @@ +package kubernetes + +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=KubernetesConnectedCluster -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Kubernetes/connectedClusters/cluster1 diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/client.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/client.go new file mode 100644 index 000000000000..2855a1b76b6a --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/client.go @@ -0,0 +1,15 @@ +package kubernetes + +import "github.com/Azure/go-autorest/autorest" + +type KubernetesClient struct { + Client autorest.Client + baseUri string +} + +func NewKubernetesClientWithBaseURI(endpoint string) KubernetesClient { + return KubernetesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/constants.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/constants.go new file mode 100644 index 000000000000..834ddb83ae4f --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/constants.go @@ -0,0 +1,176 @@ +package kubernetes + +import "strings" + +type AuthenticationMethod string + +const ( + AuthenticationMethodAAD AuthenticationMethod = "AAD" + AuthenticationMethodToken AuthenticationMethod = "Token" +) + +func PossibleValuesForAuthenticationMethod() []string { + return []string{ + string(AuthenticationMethodAAD), + string(AuthenticationMethodToken), + } +} + +func parseAuthenticationMethod(input string) (*AuthenticationMethod, error) { + vals := map[string]AuthenticationMethod{ + "aad": AuthenticationMethodAAD, + "token": AuthenticationMethodToken, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AuthenticationMethod(input) + return &out, nil +} + +type ConnectivityStatus string + +const ( + ConnectivityStatusConnected ConnectivityStatus = "Connected" + ConnectivityStatusConnecting ConnectivityStatus = "Connecting" + ConnectivityStatusExpired ConnectivityStatus = "Expired" + ConnectivityStatusOffline ConnectivityStatus = "Offline" +) + +func PossibleValuesForConnectivityStatus() []string { + return []string{ + string(ConnectivityStatusConnected), + string(ConnectivityStatusConnecting), + string(ConnectivityStatusExpired), + string(ConnectivityStatusOffline), + } +} + +func parseConnectivityStatus(input string) (*ConnectivityStatus, error) { + vals := map[string]ConnectivityStatus{ + "connected": ConnectivityStatusConnected, + "connecting": ConnectivityStatusConnecting, + "expired": ConnectivityStatusExpired, + "offline": ConnectivityStatusOffline, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ConnectivityStatus(input) + return &out, nil +} + +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +func PossibleValuesForCreatedByType() []string { + return []string{ + string(CreatedByTypeApplication), + string(CreatedByTypeKey), + string(CreatedByTypeManagedIdentity), + string(CreatedByTypeUser), + } +} + +func parseCreatedByType(input string) (*CreatedByType, error) { + vals := map[string]CreatedByType{ + "application": CreatedByTypeApplication, + "key": CreatedByTypeKey, + "managedidentity": CreatedByTypeManagedIdentity, + "user": CreatedByTypeUser, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := CreatedByType(input) + return &out, nil +} + +type LastModifiedByType string + +const ( + LastModifiedByTypeApplication LastModifiedByType = "Application" + LastModifiedByTypeKey LastModifiedByType = "Key" + LastModifiedByTypeManagedIdentity LastModifiedByType = "ManagedIdentity" + LastModifiedByTypeUser LastModifiedByType = "User" +) + +func PossibleValuesForLastModifiedByType() []string { + return []string{ + string(LastModifiedByTypeApplication), + string(LastModifiedByTypeKey), + string(LastModifiedByTypeManagedIdentity), + string(LastModifiedByTypeUser), + } +} + +func parseLastModifiedByType(input string) (*LastModifiedByType, error) { + vals := map[string]LastModifiedByType{ + "application": LastModifiedByTypeApplication, + "key": LastModifiedByTypeKey, + "managedidentity": LastModifiedByTypeManagedIdentity, + "user": LastModifiedByTypeUser, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := LastModifiedByType(input) + return &out, nil +} + +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateAccepted), + string(ProvisioningStateCanceled), + string(ProvisioningStateDeleting), + string(ProvisioningStateFailed), + string(ProvisioningStateProvisioning), + string(ProvisioningStateSucceeded), + string(ProvisioningStateUpdating), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "accepted": ProvisioningStateAccepted, + "canceled": ProvisioningStateCanceled, + "deleting": ProvisioningStateDeleting, + "failed": ProvisioningStateFailed, + "provisioning": ProvisioningStateProvisioning, + "succeeded": ProvisioningStateSucceeded, + "updating": ProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/id_connectedcluster.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/id_connectedcluster.go new file mode 100644 index 000000000000..3b8c1ce299ea --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/id_connectedcluster.go @@ -0,0 +1,124 @@ +package kubernetes + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ConnectedClusterId{} + +// ConnectedClusterId is a struct representing the Resource ID for a Connected Cluster +type ConnectedClusterId struct { + SubscriptionId string + ResourceGroupName string + ClusterName string +} + +// NewConnectedClusterID returns a new ConnectedClusterId struct +func NewConnectedClusterID(subscriptionId string, resourceGroupName string, clusterName string) ConnectedClusterId { + return ConnectedClusterId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ClusterName: clusterName, + } +} + +// ParseConnectedClusterID parses 'input' into a ConnectedClusterId +func ParseConnectedClusterID(input string) (*ConnectedClusterId, error) { + parser := resourceids.NewParserFromResourceIdType(ConnectedClusterId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ConnectedClusterId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ClusterName, ok = parsed.Parsed["clusterName"]; !ok { + return nil, fmt.Errorf("the segment 'clusterName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseConnectedClusterIDInsensitively parses 'input' case-insensitively into a ConnectedClusterId +// note: this method should only be used for API response data and not user input +func ParseConnectedClusterIDInsensitively(input string) (*ConnectedClusterId, error) { + parser := resourceids.NewParserFromResourceIdType(ConnectedClusterId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ConnectedClusterId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ClusterName, ok = parsed.Parsed["clusterName"]; !ok { + return nil, fmt.Errorf("the segment 'clusterName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateConnectedClusterID checks that 'input' can be parsed as a Connected Cluster ID +func ValidateConnectedClusterID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseConnectedClusterID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Connected Cluster ID +func (id ConnectedClusterId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Kubernetes/connectedClusters/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ClusterName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Connected Cluster ID +func (id ConnectedClusterId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftKubernetes", "Microsoft.Kubernetes", "Microsoft.Kubernetes"), + resourceids.StaticSegment("staticConnectedClusters", "connectedClusters", "connectedClusters"), + resourceids.UserSpecifiedSegment("clusterName", "clusterValue"), + } +} + +// String returns a human-readable description of this Connected Cluster ID +func (id ConnectedClusterId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Cluster Name: %q", id.ClusterName), + } + return fmt.Sprintf("Connected Cluster (%s)", strings.Join(components, "\n")) +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/id_connectedcluster_test.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/id_connectedcluster_test.go new file mode 100644 index 000000000000..85c6566331cc --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/id_connectedcluster_test.go @@ -0,0 +1,279 @@ +package kubernetes + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ConnectedClusterId{} + +func TestNewConnectedClusterID(t *testing.T) { + id := NewConnectedClusterID("12345678-1234-9876-4563-123456789012", "example-resource-group", "clusterValue") + + if id.SubscriptionId != "12345678-1234-9876-4563-123456789012" { + t.Fatalf("Expected %q but got %q for Segment 'SubscriptionId'", id.SubscriptionId, "12345678-1234-9876-4563-123456789012") + } + + if id.ResourceGroupName != "example-resource-group" { + t.Fatalf("Expected %q but got %q for Segment 'ResourceGroupName'", id.ResourceGroupName, "example-resource-group") + } + + if id.ClusterName != "clusterValue" { + t.Fatalf("Expected %q but got %q for Segment 'ClusterName'", id.ClusterName, "clusterValue") + } +} + +func TestFormatConnectedClusterID(t *testing.T) { + actual := NewConnectedClusterID("12345678-1234-9876-4563-123456789012", "example-resource-group", "clusterValue").ID() + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters/clusterValue" + if actual != expected { + t.Fatalf("Expected the Formatted ID to be %q but got %q", expected, actual) + } +} + +func TestParseConnectedClusterID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *ConnectedClusterId + }{ + { + // Incomplete URI + Input: "", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters", + Error: true, + }, + { + // Valid URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters/clusterValue", + Expected: &ConnectedClusterId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroupName: "example-resource-group", + ClusterName: "clusterValue", + }, + }, + { + // Invalid (Valid Uri with Extra segment) + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters/clusterValue/extra", + Error: true, + }, + } + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := ParseConnectedClusterID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %+v", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + + if actual.ResourceGroupName != v.Expected.ResourceGroupName { + t.Fatalf("Expected %q but got %q for ResourceGroupName", v.Expected.ResourceGroupName, actual.ResourceGroupName) + } + + if actual.ClusterName != v.Expected.ClusterName { + t.Fatalf("Expected %q but got %q for ClusterName", v.Expected.ClusterName, actual.ClusterName) + } + + } +} + +func TestParseConnectedClusterIDInsensitively(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *ConnectedClusterId + }{ + { + // Incomplete URI + Input: "", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS/eXaMpLe-rEsOuRcE-GrOuP", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS/eXaMpLe-rEsOuRcE-GrOuP/pRoViDeRs", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS/eXaMpLe-rEsOuRcE-GrOuP/pRoViDeRs/mIcRoSoFt.kUbErNeTeS", + Error: true, + }, + { + // Incomplete URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters", + Error: true, + }, + { + // Incomplete URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS/eXaMpLe-rEsOuRcE-GrOuP/pRoViDeRs/mIcRoSoFt.kUbErNeTeS/cOnNeCtEdClUsTeRs", + Error: true, + }, + { + // Valid URI + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters/clusterValue", + Expected: &ConnectedClusterId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroupName: "example-resource-group", + ClusterName: "clusterValue", + }, + }, + { + // Invalid (Valid Uri with Extra segment) + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/example-resource-group/providers/Microsoft.Kubernetes/connectedClusters/clusterValue/extra", + Error: true, + }, + { + // Valid URI (mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS/eXaMpLe-rEsOuRcE-GrOuP/pRoViDeRs/mIcRoSoFt.kUbErNeTeS/cOnNeCtEdClUsTeRs/cLuStErVaLuE", + Expected: &ConnectedClusterId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroupName: "eXaMpLe-rEsOuRcE-GrOuP", + ClusterName: "cLuStErVaLuE", + }, + }, + { + // Invalid (Valid Uri with Extra segment - mIxEd CaSe since this is insensitive) + Input: "/sUbScRiPtIoNs/12345678-1234-9876-4563-123456789012/rEsOuRcEgRoUpS/eXaMpLe-rEsOuRcE-GrOuP/pRoViDeRs/mIcRoSoFt.kUbErNeTeS/cOnNeCtEdClUsTeRs/cLuStErVaLuE/extra", + Error: true, + }, + } + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := ParseConnectedClusterIDInsensitively(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %+v", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + + if actual.ResourceGroupName != v.Expected.ResourceGroupName { + t.Fatalf("Expected %q but got %q for ResourceGroupName", v.Expected.ResourceGroupName, actual.ResourceGroupName) + } + + if actual.ClusterName != v.Expected.ClusterName { + t.Fatalf("Expected %q but got %q for ClusterName", v.Expected.ClusterName, actual.ClusterName) + } + + } +} + +func TestSegmentsForConnectedClusterId(t *testing.T) { + segments := ConnectedClusterId{}.Segments() + if len(segments) == 0 { + t.Fatalf("ConnectedClusterId has no segments") + } + + uniqueNames := make(map[string]struct{}, 0) + for _, segment := range segments { + uniqueNames[segment.Name] = struct{}{} + } + if len(uniqueNames) != len(segments) { + t.Fatalf("Expected the Segments to be unique but got %q unique segments and %d total segments", len(uniqueNames), len(segments)) + } +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclustercreate_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclustercreate_autorest.go new file mode 100644 index 000000000000..98d10d873363 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclustercreate_autorest.go @@ -0,0 +1,75 @@ +package kubernetes + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +type ConnectedClusterCreateResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ConnectedClusterCreate ... +func (c KubernetesClient) ConnectedClusterCreate(ctx context.Context, id ConnectedClusterId, input ConnectedCluster) (result ConnectedClusterCreateResponse, err error) { + req, err := c.preparerForConnectedClusterCreate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterCreate", nil, "Failure preparing request") + return + } + + result, err = c.senderForConnectedClusterCreate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterCreate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ConnectedClusterCreateThenPoll performs ConnectedClusterCreate then polls until it's completed +func (c KubernetesClient) ConnectedClusterCreateThenPoll(ctx context.Context, id ConnectedClusterId, input ConnectedCluster) error { + result, err := c.ConnectedClusterCreate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing ConnectedClusterCreate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ConnectedClusterCreate: %+v", err) + } + + return nil +} + +// preparerForConnectedClusterCreate prepares the ConnectedClusterCreate request. +func (c KubernetesClient) preparerForConnectedClusterCreate(ctx context.Context, id ConnectedClusterId, input ConnectedCluster) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForConnectedClusterCreate sends the ConnectedClusterCreate request. The method will close the +// http.Response Body if it receives an error. +func (c KubernetesClient) senderForConnectedClusterCreate(ctx context.Context, req *http.Request) (future ConnectedClusterCreateResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + future.Poller, err = polling.NewLongRunningPollerFromResponse(ctx, resp, c.Client) + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterdelete_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterdelete_autorest.go new file mode 100644 index 000000000000..34abe80ff92e --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterdelete_autorest.go @@ -0,0 +1,74 @@ +package kubernetes + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +type ConnectedClusterDeleteResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ConnectedClusterDelete ... +func (c KubernetesClient) ConnectedClusterDelete(ctx context.Context, id ConnectedClusterId) (result ConnectedClusterDeleteResponse, err error) { + req, err := c.preparerForConnectedClusterDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForConnectedClusterDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ConnectedClusterDeleteThenPoll performs ConnectedClusterDelete then polls until it's completed +func (c KubernetesClient) ConnectedClusterDeleteThenPoll(ctx context.Context, id ConnectedClusterId) error { + result, err := c.ConnectedClusterDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing ConnectedClusterDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ConnectedClusterDelete: %+v", err) + } + + return nil +} + +// preparerForConnectedClusterDelete prepares the ConnectedClusterDelete request. +func (c KubernetesClient) preparerForConnectedClusterDelete(ctx context.Context, id ConnectedClusterId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForConnectedClusterDelete sends the ConnectedClusterDelete request. The method will close the +// http.Response Body if it receives an error. +func (c KubernetesClient) senderForConnectedClusterDelete(ctx context.Context, req *http.Request) (future ConnectedClusterDeleteResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + future.Poller, err = polling.NewLongRunningPollerFromResponse(ctx, resp, c.Client) + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterget_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterget_autorest.go new file mode 100644 index 000000000000..34dfb80496d1 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterget_autorest.go @@ -0,0 +1,64 @@ +package kubernetes + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +type ConnectedClusterGetResponse struct { + HttpResponse *http.Response + Model *ConnectedCluster +} + +// ConnectedClusterGet ... +func (c KubernetesClient) ConnectedClusterGet(ctx context.Context, id ConnectedClusterId) (result ConnectedClusterGetResponse, err error) { + req, err := c.preparerForConnectedClusterGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForConnectedClusterGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForConnectedClusterGet prepares the ConnectedClusterGet request. +func (c KubernetesClient) preparerForConnectedClusterGet(ctx context.Context, id ConnectedClusterId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForConnectedClusterGet handles the response to the ConnectedClusterGet request. The method always +// closes the http.Response Body. +func (c KubernetesClient) responderForConnectedClusterGet(resp *http.Response) (result ConnectedClusterGetResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistbyresourcegroup_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistbyresourcegroup_autorest.go new file mode 100644 index 000000000000..61a7df5b3410 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistbyresourcegroup_autorest.go @@ -0,0 +1,184 @@ +package kubernetes + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +type ConnectedClusterListByResourceGroupResponse struct { + HttpResponse *http.Response + Model *[]ConnectedCluster + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ConnectedClusterListByResourceGroupResponse, error) +} + +type ConnectedClusterListByResourceGroupCompleteResult struct { + Items []ConnectedCluster +} + +func (r ConnectedClusterListByResourceGroupResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ConnectedClusterListByResourceGroupResponse) LoadMore(ctx context.Context) (resp ConnectedClusterListByResourceGroupResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ConnectedClusterListByResourceGroup ... +func (c KubernetesClient) ConnectedClusterListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ConnectedClusterListByResourceGroupResponse, err error) { + req, err := c.preparerForConnectedClusterListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForConnectedClusterListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ConnectedClusterListByResourceGroupComplete retrieves all of the results into a single object +func (c KubernetesClient) ConnectedClusterListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ConnectedClusterListByResourceGroupCompleteResult, error) { + return c.ConnectedClusterListByResourceGroupCompleteMatchingPredicate(ctx, id, ConnectedClusterPredicate{}) +} + +// ConnectedClusterListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c KubernetesClient) ConnectedClusterListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate ConnectedClusterPredicate) (resp ConnectedClusterListByResourceGroupCompleteResult, err error) { + items := make([]ConnectedCluster, 0) + + page, err := c.ConnectedClusterListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ConnectedClusterListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForConnectedClusterListByResourceGroup prepares the ConnectedClusterListByResourceGroup request. +func (c KubernetesClient) preparerForConnectedClusterListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Kubernetes/connectedClusters", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForConnectedClusterListByResourceGroupWithNextLink prepares the ConnectedClusterListByResourceGroup request with the given nextLink token. +func (c KubernetesClient) preparerForConnectedClusterListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForConnectedClusterListByResourceGroup handles the response to the ConnectedClusterListByResourceGroup request. The method always +// closes the http.Response Body. +func (c KubernetesClient) responderForConnectedClusterListByResourceGroup(resp *http.Response) (result ConnectedClusterListByResourceGroupResponse, err error) { + type page struct { + Values []ConnectedCluster `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ConnectedClusterListByResourceGroupResponse, err error) { + req, err := c.preparerForConnectedClusterListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForConnectedClusterListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistbysubscription_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistbysubscription_autorest.go new file mode 100644 index 000000000000..4f0a965082b1 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistbysubscription_autorest.go @@ -0,0 +1,184 @@ +package kubernetes + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +type ConnectedClusterListBySubscriptionResponse struct { + HttpResponse *http.Response + Model *[]ConnectedCluster + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ConnectedClusterListBySubscriptionResponse, error) +} + +type ConnectedClusterListBySubscriptionCompleteResult struct { + Items []ConnectedCluster +} + +func (r ConnectedClusterListBySubscriptionResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ConnectedClusterListBySubscriptionResponse) LoadMore(ctx context.Context) (resp ConnectedClusterListBySubscriptionResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ConnectedClusterListBySubscription ... +func (c KubernetesClient) ConnectedClusterListBySubscription(ctx context.Context, id commonids.SubscriptionId) (resp ConnectedClusterListBySubscriptionResponse, err error) { + req, err := c.preparerForConnectedClusterListBySubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForConnectedClusterListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ConnectedClusterListBySubscriptionComplete retrieves all of the results into a single object +func (c KubernetesClient) ConnectedClusterListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId) (ConnectedClusterListBySubscriptionCompleteResult, error) { + return c.ConnectedClusterListBySubscriptionCompleteMatchingPredicate(ctx, id, ConnectedClusterPredicate{}) +} + +// ConnectedClusterListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c KubernetesClient) ConnectedClusterListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate ConnectedClusterPredicate) (resp ConnectedClusterListBySubscriptionCompleteResult, err error) { + items := make([]ConnectedCluster, 0) + + page, err := c.ConnectedClusterListBySubscription(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ConnectedClusterListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForConnectedClusterListBySubscription prepares the ConnectedClusterListBySubscription request. +func (c KubernetesClient) preparerForConnectedClusterListBySubscription(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Kubernetes/connectedClusters", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForConnectedClusterListBySubscriptionWithNextLink prepares the ConnectedClusterListBySubscription request with the given nextLink token. +func (c KubernetesClient) preparerForConnectedClusterListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForConnectedClusterListBySubscription handles the response to the ConnectedClusterListBySubscription request. The method always +// closes the http.Response Body. +func (c KubernetesClient) responderForConnectedClusterListBySubscription(resp *http.Response) (result ConnectedClusterListBySubscriptionResponse, err error) { + type page struct { + Values []ConnectedCluster `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ConnectedClusterListBySubscriptionResponse, err error) { + req, err := c.preparerForConnectedClusterListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForConnectedClusterListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistclusterusercredential_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistclusterusercredential_autorest.go new file mode 100644 index 000000000000..09e229386923 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterlistclusterusercredential_autorest.go @@ -0,0 +1,66 @@ +package kubernetes + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +type ConnectedClusterListClusterUserCredentialResponse struct { + HttpResponse *http.Response + Model *CredentialResults +} + +// ConnectedClusterListClusterUserCredential ... +func (c KubernetesClient) ConnectedClusterListClusterUserCredential(ctx context.Context, id ConnectedClusterId, input ListClusterUserCredentialProperties) (result ConnectedClusterListClusterUserCredentialResponse, err error) { + req, err := c.preparerForConnectedClusterListClusterUserCredential(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListClusterUserCredential", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListClusterUserCredential", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForConnectedClusterListClusterUserCredential(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterListClusterUserCredential", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForConnectedClusterListClusterUserCredential prepares the ConnectedClusterListClusterUserCredential request. +func (c KubernetesClient) preparerForConnectedClusterListClusterUserCredential(ctx context.Context, id ConnectedClusterId, input ListClusterUserCredentialProperties) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listClusterUserCredential", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForConnectedClusterListClusterUserCredential handles the response to the ConnectedClusterListClusterUserCredential request. The method always +// closes the http.Response Body. +func (c KubernetesClient) responderForConnectedClusterListClusterUserCredential(resp *http.Response) (result ConnectedClusterListClusterUserCredentialResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterupdate_autorest.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterupdate_autorest.go new file mode 100644 index 000000000000..5ca612cb989b --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/method_connectedclusterupdate_autorest.go @@ -0,0 +1,65 @@ +package kubernetes + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +type ConnectedClusterUpdateResponse struct { + HttpResponse *http.Response + Model *ConnectedCluster +} + +// ConnectedClusterUpdate ... +func (c KubernetesClient) ConnectedClusterUpdate(ctx context.Context, id ConnectedClusterId, input ConnectedClusterPatch) (result ConnectedClusterUpdateResponse, err error) { + req, err := c.preparerForConnectedClusterUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForConnectedClusterUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "kubernetes.KubernetesClient", "ConnectedClusterUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForConnectedClusterUpdate prepares the ConnectedClusterUpdate request. +func (c KubernetesClient) preparerForConnectedClusterUpdate(ctx context.Context, id ConnectedClusterId, input ConnectedClusterPatch) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForConnectedClusterUpdate handles the response to the ConnectedClusterUpdate request. The method always +// closes the http.Response Body. +func (c KubernetesClient) responderForConnectedClusterUpdate(resp *http.Response) (result ConnectedClusterUpdateResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedcluster.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedcluster.go new file mode 100644 index 000000000000..8d1b77e5b500 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedcluster.go @@ -0,0 +1,16 @@ +package kubernetes + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" +) + +type ConnectedCluster struct { + Id *string `json:"id,omitempty"` + Identity identity.SystemAssigned `json:"identity"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties ConnectedClusterProperties `json:"properties"` + SystemData *SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedclusterpatch.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedclusterpatch.go new file mode 100644 index 000000000000..cdf6ca12a058 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedclusterpatch.go @@ -0,0 +1,6 @@ +package kubernetes + +type ConnectedClusterPatch struct { + Properties *interface{} `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedclusterproperties.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedclusterproperties.go new file mode 100644 index 000000000000..8ee77ae749ae --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_connectedclusterproperties.go @@ -0,0 +1,46 @@ +package kubernetes + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +type ConnectedClusterProperties struct { + AgentPublicKeyCertificate string `json:"agentPublicKeyCertificate"` + AgentVersion *string `json:"agentVersion,omitempty"` + ConnectivityStatus *ConnectivityStatus `json:"connectivityStatus,omitempty"` + Distribution *string `json:"distribution,omitempty"` + Infrastructure *string `json:"infrastructure,omitempty"` + KubernetesVersion *string `json:"kubernetesVersion,omitempty"` + LastConnectivityTime *string `json:"lastConnectivityTime,omitempty"` + ManagedIdentityCertificateExpirationTime *string `json:"managedIdentityCertificateExpirationTime,omitempty"` + Offering *string `json:"offering,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + TotalCoreCount *int64 `json:"totalCoreCount,omitempty"` + TotalNodeCount *int64 `json:"totalNodeCount,omitempty"` +} + +func (o ConnectedClusterProperties) GetLastConnectivityTimeAsTime() (*time.Time, error) { + if o.LastConnectivityTime == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastConnectivityTime, "2006-01-02T15:04:05Z07:00") +} + +func (o ConnectedClusterProperties) SetLastConnectivityTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastConnectivityTime = &formatted +} + +func (o ConnectedClusterProperties) GetManagedIdentityCertificateExpirationTimeAsTime() (*time.Time, error) { + if o.ManagedIdentityCertificateExpirationTime == nil { + return nil, nil + } + return dates.ParseAsFormat(o.ManagedIdentityCertificateExpirationTime, "2006-01-02T15:04:05Z07:00") +} + +func (o ConnectedClusterProperties) SetManagedIdentityCertificateExpirationTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.ManagedIdentityCertificateExpirationTime = &formatted +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_credentialresult.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_credentialresult.go new file mode 100644 index 000000000000..6814442b2b30 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_credentialresult.go @@ -0,0 +1,6 @@ +package kubernetes + +type CredentialResult struct { + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_credentialresults.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_credentialresults.go new file mode 100644 index 000000000000..d7319f1be113 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_credentialresults.go @@ -0,0 +1,6 @@ +package kubernetes + +type CredentialResults struct { + HybridConnectionConfig *HybridConnectionConfig `json:"hybridConnectionConfig,omitempty"` + Kubeconfigs *[]CredentialResult `json:"kubeconfigs,omitempty"` +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_hybridconnectionconfig.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_hybridconnectionconfig.go new file mode 100644 index 000000000000..7b11962e13e7 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_hybridconnectionconfig.go @@ -0,0 +1,8 @@ +package kubernetes + +type HybridConnectionConfig struct { + ExpirationTime *int64 `json:"expirationTime,omitempty"` + HybridConnectionName *string `json:"hybridConnectionName,omitempty"` + Relay *string `json:"relay,omitempty"` + Token *string `json:"token,omitempty"` +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_listclusterusercredentialproperties.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_listclusterusercredentialproperties.go new file mode 100644 index 000000000000..c4b4ed1da6cf --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_listclusterusercredentialproperties.go @@ -0,0 +1,6 @@ +package kubernetes + +type ListClusterUserCredentialProperties struct { + AuthenticationMethod AuthenticationMethod `json:"authenticationMethod"` + ClientProxy bool `json:"clientProxy"` +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_systemdata.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_systemdata.go new file mode 100644 index 000000000000..bb4142485b4c --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/model_systemdata.go @@ -0,0 +1,40 @@ +package kubernetes + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +type SystemData struct { + CreatedAt *string `json:"createdAt,omitempty"` + CreatedBy *string `json:"createdBy,omitempty"` + CreatedByType *CreatedByType `json:"createdByType,omitempty"` + LastModifiedAt *string `json:"lastModifiedAt,omitempty"` + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + LastModifiedByType *LastModifiedByType `json:"lastModifiedByType,omitempty"` +} + +func (o SystemData) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o SystemData) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o SystemData) GetLastModifiedAtAsTime() (*time.Time, error) { + if o.LastModifiedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModifiedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o SystemData) SetLastModifiedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModifiedAt = &formatted +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/predicates.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/predicates.go new file mode 100644 index 000000000000..266ceee4e1a6 --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/predicates.go @@ -0,0 +1,29 @@ +package kubernetes + +type ConnectedClusterPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p ConnectedClusterPredicate) Matches(input ConnectedCluster) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/internal/services/kubernetes/sdk/2021-10-01/kubernetes/version.go b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/version.go new file mode 100644 index 000000000000..2b84f45b1dec --- /dev/null +++ b/internal/services/kubernetes/sdk/2021-10-01/kubernetes/version.go @@ -0,0 +1,9 @@ +package kubernetes + +import "fmt" + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("pandora/kubernetes/%s", defaultApiVersion) +} diff --git a/website/allowed-subcategories b/website/allowed-subcategories index e1fda4ccd692..bf980f775def 100644 --- a/website/allowed-subcategories +++ b/website/allowed-subcategories @@ -45,6 +45,7 @@ Healthcare IoT Central IoT Hub Key Vault +Kubernetes Lighthouse Load Balancer Load Test diff --git a/website/docs/r/kubernetes_connected_cluster.html.markdown b/website/docs/r/kubernetes_connected_cluster.html.markdown new file mode 100644 index 000000000000..fbc1053f66f9 --- /dev/null +++ b/website/docs/r/kubernetes_connected_cluster.html.markdown @@ -0,0 +1,98 @@ +--- +subcategory: "Kubernetes" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_kubernetes_connected_cluster" +description: |- + Manages a kubernetes connected cluster. +--- + +# azurerm_kubernetes_connected_cluster + +Manages a kubernetes connected cluster. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "test" { + name = "example-kubernetes" + location = "West Europe" +} + +resource "azurerm_kubernetes_connected_cluster" "test" { + name = "acctest-k-%d" + resource_group_name = azurerm_resource_group.test.name + agent_public_key_certificate = "xxxxxxxxxxxxxxxxxxx" + distribution = "gke" + + identity = { + type = "SystemAssigned" + } + infrastructure = "gcp" + location = "West Europe" + + tags = { + ENV = "Test" + } +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) The name which should be used for this Kubernetes Connected Cluster. Changing this forces a new Kubernetes Connected Cluster to be created. + +* `resource_group_name` - (Required) The name of the Resource Group where the kubernetes connected cluster should exist. Changing this forces a new kubernetes connected cluster to be created. + +* `agent_public_key_certificate` - (Required) Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. Changing this forces a new kubernetes connected cluster to be created. + +* `identity` - (Required) An `identity` block as defined below. + +* `location` - (Required) The Azure Region where the kubernetes connected cluster should exist. Changing this forces a new kubernetes connected cluster to be created. + +* `distribution` - (Optional) The Kubernetes distribution running on this connected cluster. Changing this forces a new kubernetes connected cluster to be created. + +* `infrastructure` - (Optional) The infrastructure on which the Kubernetes cluster represented by this connected cluster is running on. Changing this forces a new kubernetes connected cluster to be created. + +* `tags` - (Optional) A mapping of tags which should be assigned to the kubernetes connected cluster. + +--- + +An `identity` block exports the following: + +* `type` - (Required) Specifies the type of Managed Service Identity. Possible values are `SystemAssigned`. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the kubernetes connected cluster. + +* `identity` - An `identity` block as defined below. + +* `provisioning_state` - The current deployment state of connected clusters. + +--- + +An `identity` block exports the following: + +* `principal_id` - The Principal ID associated with this Managed Service Identity. + +* `tenant_id` - The Tenant ID associated with this Managed Service Identity. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the kubernetes connected cluster. +* `read` - (Defaults to 5 minutes) Used when retrieving the kubernetes connected cluster. +* `update` - (Defaults to 30 minutes) Used when updating the kubernetes connected cluster. +* `delete` - (Defaults to 30 minutes) Used when deleting the kubernetes connected cluster. + +## Import + +kubernetes connected cluster can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_kubernetes_connected_cluster.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceGroup1/providers/Microsoft.Kubernetes/connectedClusters/cluster1 +```