provider/kubernetes: Add support for Horizontal Pod Autoscaler (#14763)

This commit is contained in:
Radek Simko 2017-05-24 17:18:02 +01:00 committed by GitHub
parent cec3430b33
commit 2c3e8e3cfb
6 changed files with 659 additions and 8 deletions

View File

@ -86,14 +86,15 @@ func Provider() terraform.ResourceProvider {
},
ResourcesMap: map[string]*schema.Resource{
"kubernetes_config_map": resourceKubernetesConfigMap(),
"kubernetes_limit_range": resourceKubernetesLimitRange(),
"kubernetes_namespace": resourceKubernetesNamespace(),
"kubernetes_persistent_volume": resourceKubernetesPersistentVolume(),
"kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(),
"kubernetes_resource_quota": resourceKubernetesResourceQuota(),
"kubernetes_secret": resourceKubernetesSecret(),
"kubernetes_service": resourceKubernetesService(),
"kubernetes_config_map": resourceKubernetesConfigMap(),
"kubernetes_horizontal_pod_autoscaler": resourceKubernetesHorizontalPodAutoscaler(),
"kubernetes_limit_range": resourceKubernetesLimitRange(),
"kubernetes_namespace": resourceKubernetesNamespace(),
"kubernetes_persistent_volume": resourceKubernetesPersistentVolume(),
"kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(),
"kubernetes_resource_quota": resourceKubernetesResourceQuota(),
"kubernetes_secret": resourceKubernetesSecret(),
"kubernetes_service": resourceKubernetesService(),
},
ConfigureFunc: providerConfigure,
}

View File

@ -0,0 +1,183 @@
package kubernetes
import (
"fmt"
"log"
"github.com/hashicorp/terraform/helper/schema"
pkgApi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
api_v1 "k8s.io/kubernetes/pkg/api/v1"
api "k8s.io/kubernetes/pkg/apis/autoscaling/v1"
kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5"
)
func resourceKubernetesHorizontalPodAutoscaler() *schema.Resource {
return &schema.Resource{
Create: resourceKubernetesHorizontalPodAutoscalerCreate,
Read: resourceKubernetesHorizontalPodAutoscalerRead,
Exists: resourceKubernetesHorizontalPodAutoscalerExists,
Update: resourceKubernetesHorizontalPodAutoscalerUpdate,
Delete: resourceKubernetesHorizontalPodAutoscalerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"metadata": namespacedMetadataSchema("horizontal pod autoscaler", true),
"spec": {
Type: schema.TypeList,
Description: "Behaviour of the autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.",
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"max_replicas": {
Type: schema.TypeInt,
Description: "Upper limit for the number of pods that can be set by the autoscaler.",
Required: true,
},
"min_replicas": {
Type: schema.TypeInt,
Description: "Lower limit for the number of pods that can be set by the autoscaler, defaults to `1`.",
Optional: true,
Default: 1,
},
"scale_target_ref": {
Type: schema.TypeList,
Description: "Reference to scaled resource. e.g. Replication Controller",
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_version": {
Type: schema.TypeString,
Description: "API version of the referent",
Optional: true,
},
"kind": {
Type: schema.TypeString,
Description: "Kind of the referent. e.g. `ReplicationController`. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds",
Required: true,
},
"name": {
Type: schema.TypeString,
Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
Required: true,
},
},
},
},
"target_cpu_utilization_percentage": {
Type: schema.TypeInt,
Description: "Target average CPU utilization (represented as a percentage of requested CPU) over all the pods. If not specified the default autoscaling policy will be used.",
Optional: true,
},
},
},
},
},
}
}
func resourceKubernetesHorizontalPodAutoscalerCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
metadata := expandMetadata(d.Get("metadata").([]interface{}))
svc := api.HorizontalPodAutoscaler{
ObjectMeta: metadata,
Spec: expandHorizontalPodAutoscalerSpec(d.Get("spec").([]interface{})),
}
log.Printf("[INFO] Creating new horizontal pod autoscaler: %#v", svc)
out, err := conn.AutoscalingV1().HorizontalPodAutoscalers(metadata.Namespace).Create(&svc)
if err != nil {
return err
}
log.Printf("[INFO] Submitted new horizontal pod autoscaler: %#v", out)
d.SetId(buildId(out.ObjectMeta))
return resourceKubernetesHorizontalPodAutoscalerRead(d, meta)
}
func resourceKubernetesHorizontalPodAutoscalerRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
log.Printf("[INFO] Reading horizontal pod autoscaler %s", name)
svc, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(name)
if err != nil {
log.Printf("[DEBUG] Received error: %#v", err)
return err
}
log.Printf("[INFO] Received horizontal pod autoscaler: %#v", svc)
err = d.Set("metadata", flattenMetadata(svc.ObjectMeta))
if err != nil {
return err
}
flattened := flattenHorizontalPodAutoscalerSpec(svc.Spec)
log.Printf("[DEBUG] Flattened horizontal pod autoscaler spec: %#v", flattened)
err = d.Set("spec", flattened)
if err != nil {
return err
}
return nil
}
func resourceKubernetesHorizontalPodAutoscalerUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
ops := patchMetadata("metadata.0.", "/metadata/", d)
if d.HasChange("spec") {
diffOps := patchHorizontalPodAutoscalerSpec("spec.0.", "/spec", d)
ops = append(ops, diffOps...)
}
data, err := ops.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal update operations: %s", err)
}
log.Printf("[INFO] Updating horizontal pod autoscaler %q: %v", name, string(data))
out, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Patch(name, pkgApi.JSONPatchType, data)
if err != nil {
return fmt.Errorf("Failed to update horizontal pod autoscaler: %s", err)
}
log.Printf("[INFO] Submitted updated horizontal pod autoscaler: %#v", out)
d.SetId(buildId(out.ObjectMeta))
return resourceKubernetesHorizontalPodAutoscalerRead(d, meta)
}
func resourceKubernetesHorizontalPodAutoscalerDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
log.Printf("[INFO] Deleting horizontal pod autoscaler: %#v", name)
err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Delete(name, &api_v1.DeleteOptions{})
if err != nil {
return err
}
log.Printf("[INFO] Horizontal Pod Autoscaler %s deleted", name)
d.SetId("")
return nil
}
func resourceKubernetesHorizontalPodAutoscalerExists(d *schema.ResourceData, meta interface{}) (bool, error) {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
log.Printf("[INFO] Checking horizontal pod autoscaler %s", name)
_, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(name)
if err != nil {
if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 {
return false, nil
}
log.Printf("[DEBUG] Received error: %#v", err)
}
return true, err
}

View File

@ -0,0 +1,277 @@
package kubernetes
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
api "k8s.io/kubernetes/pkg/apis/autoscaling/v1"
kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5"
)
func TestAccKubernetesHorizontalPodAutoscaler_basic(t *testing.T) {
var conf api.HorizontalPodAutoscaler
name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "kubernetes_horizontal_pod_autoscaler.test",
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesHorizontalPodAutoscalerDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesHorizontalPodAutoscalerConfig_basic(name),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesHorizontalPodAutoscalerExists("kubernetes_horizontal_pod_autoscaler.test", &conf),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.%", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.TestAnnotationOne", "one"),
testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one"}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.%", "3"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.TestLabelOne", "one"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.TestLabelThree", "three"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.TestLabelFour", "four"),
testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelThree": "three", "TestLabelFour": "four"}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.name", name),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.generation"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.resource_version"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.self_link"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.uid"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.max_replicas", "10"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.min_replicas", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.kind", "ReplicationController"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.name", "TerraformAccTest"),
),
},
{
Config: testAccKubernetesHorizontalPodAutoscalerConfig_metaModified(name),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesHorizontalPodAutoscalerExists("kubernetes_horizontal_pod_autoscaler.test", &conf),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.%", "2"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.TestAnnotationOne", "one"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.TestAnnotationTwo", "two"),
testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.%", "3"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.TestLabelOne", "one"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.TestLabelTwo", "two"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.TestLabelThree", "three"),
testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.name", name),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.generation"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.resource_version"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.self_link"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.uid"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.max_replicas", "10"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.min_replicas", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.kind", "ReplicationController"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.name", "TerraformAccTest"),
),
},
{
Config: testAccKubernetesHorizontalPodAutoscalerConfig_specModified(name),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesHorizontalPodAutoscalerExists("kubernetes_horizontal_pod_autoscaler.test", &conf),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.%", "0"),
testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.%", "0"),
testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.name", name),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.generation"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.resource_version"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.self_link"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.uid"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.max_replicas", "8"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.min_replicas", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.kind", "ReplicationController"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.name", "TerraformAccTestModified"),
),
},
},
})
}
func TestAccKubernetesHorizontalPodAutoscaler_generatedName(t *testing.T) {
var conf api.HorizontalPodAutoscaler
prefix := "tf-acc-test-"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "kubernetes_horizontal_pod_autoscaler.test",
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesHorizontalPodAutoscalerDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesHorizontalPodAutoscalerConfig_generatedName(prefix),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesHorizontalPodAutoscalerExists("kubernetes_horizontal_pod_autoscaler.test", &conf),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.annotations.%", "0"),
testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.labels.%", "0"),
testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.generate_name", prefix),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.generation"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.resource_version"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.self_link"),
resource.TestCheckResourceAttrSet("kubernetes_horizontal_pod_autoscaler.test", "metadata.0.uid"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.max_replicas", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.min_replicas", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.#", "1"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.kind", "ReplicationController"),
resource.TestCheckResourceAttr("kubernetes_horizontal_pod_autoscaler.test", "spec.0.scale_target_ref.0.name", "TerraformAccTestGeneratedName"),
),
},
},
})
}
func TestAccKubernetesHorizontalPodAutoscaler_importBasic(t *testing.T) {
resourceName := "kubernetes_horizontal_pod_autoscaler.test"
name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesHorizontalPodAutoscalerDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesHorizontalPodAutoscalerConfig_basic(name),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccCheckKubernetesHorizontalPodAutoscalerDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*kubernetes.Clientset)
for _, rs := range s.RootModule().Resources {
if rs.Type != "kubernetes_horizontal_pod_autoscaler" {
continue
}
namespace, name := idParts(rs.Primary.ID)
resp, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(name)
if err == nil {
if resp.Namespace == namespace && resp.Name == name {
return fmt.Errorf("Horizontal Pod Autoscaler still exists: %s", rs.Primary.ID)
}
}
}
return nil
}
func testAccCheckKubernetesHorizontalPodAutoscalerExists(n string, obj *api.HorizontalPodAutoscaler) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
conn := testAccProvider.Meta().(*kubernetes.Clientset)
namespace, name := idParts(rs.Primary.ID)
out, err := conn.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(name)
if err != nil {
return err
}
*obj = *out
return nil
}
}
func testAccKubernetesHorizontalPodAutoscalerConfig_basic(name string) string {
return fmt.Sprintf(`
resource "kubernetes_horizontal_pod_autoscaler" "test" {
metadata {
annotations {
TestAnnotationOne = "one"
}
labels {
TestLabelOne = "one"
TestLabelThree = "three"
TestLabelFour = "four"
}
name = "%s"
}
spec {
max_replicas = 10
scale_target_ref {
kind = "ReplicationController"
name = "TerraformAccTest"
}
}
}
`, name)
}
func testAccKubernetesHorizontalPodAutoscalerConfig_metaModified(name string) string {
return fmt.Sprintf(`
resource "kubernetes_horizontal_pod_autoscaler" "test" {
metadata {
annotations {
TestAnnotationOne = "one"
TestAnnotationTwo = "two"
}
labels {
TestLabelOne = "one"
TestLabelTwo = "two"
TestLabelThree = "three"
}
name = "%s"
}
spec {
max_replicas = 10
scale_target_ref {
kind = "ReplicationController"
name = "TerraformAccTest"
}
}
}
`, name)
}
func testAccKubernetesHorizontalPodAutoscalerConfig_specModified(name string) string {
return fmt.Sprintf(`
resource "kubernetes_horizontal_pod_autoscaler" "test" {
metadata {
name = "%s"
}
spec {
max_replicas = 8
scale_target_ref {
kind = "ReplicationController"
name = "TerraformAccTestModified"
}
}
}
`, name)
}
func testAccKubernetesHorizontalPodAutoscalerConfig_generatedName(prefix string) string {
return fmt.Sprintf(`
resource "kubernetes_horizontal_pod_autoscaler" "test" {
metadata {
generate_name = "%s"
}
spec {
max_replicas = 1
scale_target_ref {
kind = "ReplicationController"
name = "TerraformAccTestGeneratedName"
}
}
}
`, prefix)
}

View File

@ -0,0 +1,105 @@
package kubernetes
import (
"github.com/hashicorp/terraform/helper/schema"
api "k8s.io/kubernetes/pkg/apis/autoscaling/v1"
)
func expandHorizontalPodAutoscalerSpec(in []interface{}) api.HorizontalPodAutoscalerSpec {
if len(in) == 0 || in[0] == nil {
return api.HorizontalPodAutoscalerSpec{}
}
spec := api.HorizontalPodAutoscalerSpec{}
m := in[0].(map[string]interface{})
if v, ok := m["max_replicas"]; ok {
spec.MaxReplicas = int32(v.(int))
}
if v, ok := m["min_replicas"].(int); ok && v > 0 {
spec.MinReplicas = ptrToInt32(int32(v))
}
if v, ok := m["scale_target_ref"]; ok {
spec.ScaleTargetRef = expandCrossVersionObjectReference(v.([]interface{}))
}
if v, ok := m["target_cpu_utilization_percentage"].(int); ok && v > 0 {
spec.TargetCPUUtilizationPercentage = ptrToInt32(int32(v))
}
return spec
}
func expandCrossVersionObjectReference(in []interface{}) api.CrossVersionObjectReference {
if len(in) == 0 || in[0] == nil {
return api.CrossVersionObjectReference{}
}
ref := api.CrossVersionObjectReference{}
m := in[0].(map[string]interface{})
if v, ok := m["api_version"]; ok {
ref.APIVersion = v.(string)
}
if v, ok := m["kind"]; ok {
ref.Kind = v.(string)
}
if v, ok := m["name"]; ok {
ref.Name = v.(string)
}
return ref
}
func flattenHorizontalPodAutoscalerSpec(spec api.HorizontalPodAutoscalerSpec) []interface{} {
m := make(map[string]interface{}, 0)
m["max_replicas"] = spec.MaxReplicas
if spec.MinReplicas != nil {
m["min_replicas"] = *spec.MinReplicas
}
m["scale_target_ref"] = flattenCrossVersionObjectReference(spec.ScaleTargetRef)
if spec.TargetCPUUtilizationPercentage != nil {
m["target_cpu_utilization_percentage"] = *spec.TargetCPUUtilizationPercentage
}
return []interface{}{m}
}
func flattenCrossVersionObjectReference(ref api.CrossVersionObjectReference) []interface{} {
m := make(map[string]interface{}, 0)
if ref.APIVersion != "" {
m["api_version"] = ref.APIVersion
}
if ref.Kind != "" {
m["kind"] = ref.Kind
}
if ref.Name != "" {
m["name"] = ref.Name
}
return []interface{}{m}
}
func patchHorizontalPodAutoscalerSpec(prefix string, pathPrefix string, d *schema.ResourceData) []PatchOperation {
ops := make([]PatchOperation, 0)
if d.HasChange(prefix + "max_replicas") {
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/maxReplicas",
Value: d.Get(prefix + "max_replicas").(int),
})
}
if d.HasChange(prefix + "min_replicas") {
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/minReplicas",
Value: d.Get(prefix + "min_replicas").(int),
})
}
if d.HasChange(prefix + "scale_target_ref") {
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/scaleTargetRef",
Value: expandCrossVersionObjectReference(d.Get(prefix + "scale_target_ref").([]interface{})),
})
}
if d.HasChange(prefix + "target_cpu_utilization_percentage") {
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/targetCPUUtilizationPercentage",
Value: d.Get(prefix + "target_cpu_utilization_percentage").(int),
})
}
return ops
}

View File

@ -0,0 +1,82 @@
---
layout: "kubernetes"
page_title: "Kubernetes: kubernetes_horizontal_pod_autoscaler"
sidebar_current: "docs-kubernetes-horizontal-pod-autoscaler"
description: |-
Horizontal Pod Autoscaler automatically scales the number of pods in a replication controller, deployment or replica set based on observed CPU utilization.
---
# kubernetes_horizontal_pod_autoscaler
Horizontal Pod Autoscaler automatically scales the number of pods in a replication controller, deployment or replica set based on observed CPU utilization.
## Example Usage
```hcl
resource "kubernetes_horizontal_pod_autoscaler" "example" {
metadata {
name = "terraform-example"
}
spec {
max_replicas = 10
min_replicas = 8
scale_target_ref {
kind = "ReplicationController"
name = "MyApp"
}
}
}
```
## Argument Reference
The following arguments are supported:
* `metadata` - (Required) Standard horizontal pod autoscaler's metadata. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#metadata
* `spec` - (Required) Behaviour of the autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.
## Nested Blocks
### `metadata`
#### Arguments
* `annotations` - (Optional) An unstructured key value map stored with the horizontal pod autoscaler that may be used to store arbitrary metadata. More info: http://kubernetes.io/docs/user-guide/annotations
* `generate_name` - (Optional) Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#idempotency
* `labels` - (Optional) Map of string keys and values that can be used to organize and categorize (scope and select) the horizontal pod autoscaler. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels
* `name` - (Optional) Name of the horizontal pod autoscaler, must be unique. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names
* `namespace` - (Optional) Namespace defines the space within which name of the horizontal pod autoscaler must be unique.
#### Attributes
* `generation` - A sequence number representing a specific generation of the desired state.
* `resource_version` - An opaque value that represents the internal version of this horizontal pod autoscaler that can be used by clients to determine when horizontal pod autoscaler has changed. Read more: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#concurrency-control-and-consistency
* `self_link` - A URL representing this horizontal pod autoscaler.
* `uid` - The unique in time and space value for this horizontal pod autoscaler. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
### `spec`
#### Arguments
* `max_replicas` - (Required) Upper limit for the number of pods that can be set by the autoscaler.
* `min_replicas` - (Optional) Lower limit for the number of pods that can be set by the autoscaler, defaults to `1`.
* `scale_target_ref` - (Required) Reference to scaled resource. e.g. Replication Controller
* `target_cpu_utilization_percentage` - (Optional) Target average CPU utilization (represented as a percentage of requested CPU) over all the pods. If not specified the default autoscaling policy will be used.
### `scale_target_ref`
#### Arguments
* `api_version` - (Optional) API version of the referent
* `kind` - (Required) Kind of the referent. e.g. `ReplicationController`. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
* `name` - (Required) Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names
## Import
Horizontal Pod Autoscaler can be imported using the namespace and name, e.g.
```
$ terraform import kubernetes_horizontal_pod_autoscaler.example default/terraform-example
```

View File

@ -16,6 +16,9 @@
<li<%= sidebar_current("docs-kubernetes-resource-config-map") %>>
<a href="/docs/providers/kubernetes/r/config_map.html">kubernetes_config_map</a>
</li>
<li<%= sidebar_current("docs-kubernetes-resource-horizontal-pod-autoscaler") %>>
<a href="/docs/providers/kubernetes/r/horizontal_pod_autoscaler.html">kubernetes_horizontal_pod_autoscaler</a>
</li>
<li<%= sidebar_current("docs-kubernetes-resource-limit-range") %>>
<a href="/docs/providers/kubernetes/r/limit_range.html">kubernetes_limit_range</a>
</li>