provider/kubernetes: Add support for pod (#13571)

Add support for K8s pod
This commit is contained in:
Ashish Kumar Thakur 2017-06-08 19:28:10 +05:30 committed by Radek Simko
parent 6177b479e1
commit a5c208ef68
14 changed files with 4646 additions and 487 deletions

View File

@ -0,0 +1,12 @@
package main
import (
"github.com/hashicorp/terraform/builtin/providers/kubernetes"
"github.com/hashicorp/terraform/plugin"
)
func main() {
plugin.Serve(&plugin.ServeOpts{
ProviderFunc: kubernetes.Provider,
})
}

View File

@ -0,0 +1,18 @@
package kubernetes
import (
"github.com/hashicorp/terraform/helper/schema"
"k8s.io/apimachinery/pkg/api/resource"
)
func suppressEquivalentResourceQuantity(k, old, new string, d *schema.ResourceData) bool {
oldQ, err := resource.ParseQuantity(old)
if err != nil {
return false
}
newQ, err := resource.ParseQuantity(new)
if err != nil {
return false
}
return oldQ.Cmp(newQ) == 0
}

View File

@ -97,6 +97,7 @@ func Provider() terraform.ResourceProvider {
"kubernetes_namespace": resourceKubernetesNamespace(),
"kubernetes_persistent_volume": resourceKubernetesPersistentVolume(),
"kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(),
"kubernetes_pod": resourceKubernetesPod(),
"kubernetes_resource_quota": resourceKubernetesResourceQuota(),
"kubernetes_secret": resourceKubernetesSecret(),
"kubernetes_service": resourceKubernetesService(),

View File

@ -0,0 +1,195 @@
package kubernetes
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
pkgApi "k8s.io/apimachinery/pkg/types"
api "k8s.io/kubernetes/pkg/api/v1"
kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
)
func resourceKubernetesPod() *schema.Resource {
return &schema.Resource{
Create: resourceKubernetesPodCreate,
Read: resourceKubernetesPodRead,
Update: resourceKubernetesPodUpdate,
Delete: resourceKubernetesPodDelete,
Exists: resourceKubernetesPodExists,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"metadata": namespacedMetadataSchema("pod", true),
"spec": {
Type: schema.TypeList,
Description: "Spec of the pod owned by the cluster",
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: podSpecFields(),
},
},
},
}
}
func resourceKubernetesPodCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
metadata := expandMetadata(d.Get("metadata").([]interface{}))
spec, err := expandPodSpec(d.Get("spec").([]interface{}))
if err != nil {
return err
}
spec.AutomountServiceAccountToken = ptrToBool(false)
pod := api.Pod{
ObjectMeta: metadata,
Spec: spec,
}
log.Printf("[INFO] Creating new pod: %#v", pod)
out, err := conn.CoreV1().Pods(metadata.Namespace).Create(&pod)
if err != nil {
return err
}
log.Printf("[INFO] Submitted new pod: %#v", out)
d.SetId(buildId(out.ObjectMeta))
stateConf := &resource.StateChangeConf{
Target: []string{"Running"},
Pending: []string{"Pending"},
Timeout: 5 * time.Minute,
Refresh: func() (interface{}, string, error) {
out, err := conn.CoreV1().Pods(metadata.Namespace).Get(metadata.Name, metav1.GetOptions{})
if err != nil {
log.Printf("[ERROR] Received error: %#v", err)
return out, "Error", err
}
statusPhase := fmt.Sprintf("%v", out.Status.Phase)
log.Printf("[DEBUG] Pods %s status received: %#v", out.Name, statusPhase)
return out, statusPhase, nil
},
}
_, err = stateConf.WaitForState()
if err != nil {
return err
}
log.Printf("[INFO] Pod %s created", out.Name)
return resourceKubernetesPodRead(d, meta)
}
func resourceKubernetesPodUpdate(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") {
specOps, err := patchPodSpec("/spec", "spec.0.", d)
if err != nil {
return err
}
ops = append(ops, specOps...)
}
data, err := ops.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal update operations: %s", err)
}
log.Printf("[INFO] Updating pod %s: %s", d.Id(), ops)
out, err := conn.CoreV1().Pods(namespace).Patch(name, pkgApi.JSONPatchType, data)
if err != nil {
return err
}
log.Printf("[INFO] Submitted updated pod: %#v", out)
d.SetId(buildId(out.ObjectMeta))
return resourceKubernetesPodRead(d, meta)
}
func resourceKubernetesPodRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
log.Printf("[INFO] Reading pod %s", name)
pod, err := conn.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
if err != nil {
log.Printf("[DEBUG] Received error: %#v", err)
return err
}
log.Printf("[INFO] Received pod: %#v", pod)
err = d.Set("metadata", flattenMetadata(pod.ObjectMeta))
if err != nil {
return err
}
podSpec, err := flattenPodSpec(pod.Spec)
if err != nil {
return err
}
err = d.Set("spec", podSpec)
if err != nil {
return err
}
return nil
}
func resourceKubernetesPodDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
log.Printf("[INFO] Deleting pod: %#v", name)
err := conn.CoreV1().Pods(namespace).Delete(name, nil)
if err != nil {
return err
}
err = resource.Retry(1*time.Minute, func() *resource.RetryError {
out, err := conn.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
if err != nil {
if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 {
return nil
}
return resource.NonRetryableError(err)
}
log.Printf("[DEBUG] Current state of pod: %#v", out.Status.Phase)
e := fmt.Errorf("Pod %s still exists (%s)", name, out.Status.Phase)
return resource.RetryableError(e)
})
if err != nil {
return err
}
log.Printf("[INFO] Pod %s deleted", name)
d.SetId("")
return nil
}
func resourceKubernetesPodExists(d *schema.ResourceData, meta interface{}) (bool, error) {
conn := meta.(*kubernetes.Clientset)
namespace, name := idParts(d.Id())
log.Printf("[INFO] Checking pod %s", name)
_, err := conn.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
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,724 @@
package kubernetes
import (
"fmt"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
api "k8s.io/kubernetes/pkg/api/v1"
kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccKubernetesPod_basic(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
secretName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
configMapName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName1 := "nginx:1.7.9"
imageName2 := "nginx:1.11"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigBasic(secretName, configMapName, podName, imageName1),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "metadata.0.annotations.%", "0"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "metadata.0.labels.%", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "metadata.0.labels.app", "pod_label"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "metadata.0.name", podName),
resource.TestCheckResourceAttrSet("kubernetes_pod.test", "metadata.0.generation"),
resource.TestCheckResourceAttrSet("kubernetes_pod.test", "metadata.0.resource_version"),
resource.TestCheckResourceAttrSet("kubernetes_pod.test", "metadata.0.self_link"),
resource.TestCheckResourceAttrSet("kubernetes_pod.test", "metadata.0.uid"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.env.0.value_from.0.secret_key_ref.0.name", secretName),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.env.1.value_from.0.config_map_key_ref.0.name", configMapName),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.image", imageName1),
),
},
{
Config: testAccKubernetesPodConfigBasic(secretName, configMapName, podName, imageName2),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.image", imageName2),
),
},
},
})
}
func TestAccKubernetesPod_importBasic(t *testing.T) {
resourceName := "kubernetes_pod.test"
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "nginx:1.7.9"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithSecurityContext(podName, imageName),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"metadata.0.resource_version"},
},
},
})
}
func TestAccKubernetesPod_with_pod_security_context(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "nginx:1.7.9"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithSecurityContext(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.security_context.0.run_as_non_root", "true"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.security_context.0.supplemental_groups.#", "1"),
),
},
},
})
}
func TestAccKubernetesPod_with_container_liveness_probe_using_exec(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "gcr.io/google_containers/busybox"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithLivenessProbeUsingExec(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.args.#", "3"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.exec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.exec.0.command.#", "2"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.exec.0.command.0", "cat"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.exec.0.command.1", "/tmp/healthy"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.failure_threshold", "3"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.initial_delay_seconds", "5"),
),
},
},
})
}
func TestAccKubernetesPod_with_container_liveness_probe_using_http_get(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "gcr.io/google_containers/liveness"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithLivenessProbeUsingHTTPGet(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.args.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.http_get.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.http_get.0.path", "/healthz"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.http_get.0.port", "8080"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.http_get.0.http_header.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.http_get.0.http_header.0.name", "X-Custom-Header"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.http_get.0.http_header.0.value", "Awesome"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.initial_delay_seconds", "3"),
),
},
},
})
}
func TestAccKubernetesPod_with_container_liveness_probe_using_tcp(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "gcr.io/google_containers/liveness"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithLivenessProbeUsingTCP(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.args.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.tcp_socket.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.liveness_probe.0.tcp_socket.0.port", "8080"),
),
},
},
})
}
func TestAccKubernetesPod_with_container_lifecycle(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "gcr.io/google_containers/liveness"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithLifeCycle(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.post_start.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.post_start.0.exec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.post_start.0.exec.0.command.#", "2"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.post_start.0.exec.0.command.0", "ls"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.post_start.0.exec.0.command.1", "-al"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.pre_stop.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.pre_stop.0.exec.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.pre_stop.0.exec.0.command.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.lifecycle.0.pre_stop.0.exec.0.command.0", "date"),
),
},
},
})
}
func TestAccKubernetesPod_with_container_security_context(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "nginx:1.7.9"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithContainerSecurityContext(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.security_context.#", "1"),
),
},
},
})
}
func TestAccKubernetesPod_with_volume_mount(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
secretName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "nginx:1.7.9"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithVolumeMounts(secretName, podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.image", imageName),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.0.mount_path", "/tmp/my_path"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.0.name", "db"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.0.read_only", "false"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.0.sub_path", ""),
),
},
},
})
}
func TestAccKubernetesPod_with_resource_requirements(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "nginx:1.7.9"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithResourceRequirements(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.image", imageName),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.resources.0.requests.0.memory", "50Mi"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.resources.0.requests.0.cpu", "250m"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.resources.0.limits.0.memory", "512Mi"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.resources.0.limits.0.cpu", "500m"),
),
},
},
})
}
func TestAccKubernetesPod_with_empty_dir_volume(t *testing.T) {
var conf api.Pod
podName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
imageName := "nginx:1.7.9"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesPodDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesPodConfigWithEmptyDirVolumes(podName, imageName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesPodExists("kubernetes_pod.test", &conf),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.image", imageName),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.#", "1"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.0.mount_path", "/cache"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.container.0.volume_mount.0.name", "cache-volume"),
resource.TestCheckResourceAttr("kubernetes_pod.test", "spec.0.volume.0.empty_dir.0.medium", "Memory"),
),
},
},
})
}
func testAccCheckKubernetesPodDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*kubernetes.Clientset)
for _, rs := range s.RootModule().Resources {
if rs.Type != "kubernetes_pod" {
continue
}
namespace, name := idParts(rs.Primary.ID)
resp, err := conn.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
if err == nil {
if resp.Namespace == namespace && resp.Name == name {
return fmt.Errorf("Pod still exists: %s: %#v", rs.Primary.ID, resp.Status.Phase)
}
}
}
return nil
}
func testAccCheckKubernetesPodExists(n string, obj *api.Pod) 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.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return err
}
*obj = *out
return nil
}
}
func testAccKubernetesPodConfigBasic(secretName, configMapName, podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_secret" "test" {
metadata {
name = "%s"
}
data {
one = "first"
}
}
resource "kubernetes_config_map" "test" {
metadata {
name = "%s"
}
data {
one = "ONE"
}
}
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
env = [{
name = "EXPORTED_VARIBALE_FROM_SECRET"
value_from {
secret_key_ref {
name = "${kubernetes_secret.test.metadata.0.name}"
key = "one"
}
}
},
{
name = "EXPORTED_VARIBALE_FROM_CONFIG_MAP"
value_from {
config_map_key_ref {
name = "${kubernetes_config_map.test.metadata.0.name}"
key = "one"
}
}
},
]
}
volume {
name = "db"
secret = {
secret_name = "${kubernetes_secret.test.metadata.0.name}"
}
}
}
}
`, secretName, configMapName, podName, imageName)
}
func testAccKubernetesPodConfigWithSecurityContext(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
security_context {
run_as_non_root = true
run_as_user = 101
supplemental_groups = [101]
}
container {
image = "%s"
name = "containername"
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithLivenessProbeUsingExec(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
args = ["/bin/sh", "-c", "touch /tmp/healthy; sleep 300; rm -rf /tmp/healthy; sleep 600"]
liveness_probe {
exec {
command = ["cat", "/tmp/healthy"]
}
initial_delay_seconds = 5
period_seconds = 5
}
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithLivenessProbeUsingHTTPGet(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
args = ["/server"]
liveness_probe {
http_get {
path = "/healthz"
port = 8080
http_header {
name = "X-Custom-Header"
value = "Awesome"
}
}
initial_delay_seconds = 3
period_seconds = 3
}
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithLivenessProbeUsingTCP(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
args = ["/server"]
liveness_probe {
tcp_socket {
port = 8080
}
initial_delay_seconds = 3
period_seconds = 3
}
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithLifeCycle(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
args = ["/server"]
lifecycle {
post_start {
exec {
command = ["ls", "-al"]
}
}
pre_stop {
exec {
command = ["date"]
}
}
}
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithContainerSecurityContext(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
security_context {
privileged = true
run_as_user = 1
se_linux_options {
level = "s0:c123,c456"
}
}
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithVolumeMounts(secretName, podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_secret" "test" {
metadata {
name = "%s"
}
data {
one = "first"
}
}
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
volume_mount {
mount_path = "/tmp/my_path"
name = "db"
}
}
volume {
name = "db"
secret = {
secret_name = "${kubernetes_secret.test.metadata.0.name}"
}
}
}
}
`, secretName, podName, imageName)
}
func testAccKubernetesPodConfigWithResourceRequirements(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
resources{
limits{
cpu = "0.5"
memory = "512Mi"
}
requests{
cpu = "250m"
memory = "50Mi"
}
}
}
}
}
`, podName, imageName)
}
func testAccKubernetesPodConfigWithEmptyDirVolumes(podName, imageName string) string {
return fmt.Sprintf(`
resource "kubernetes_pod" "test" {
metadata {
labels {
app = "pod_label"
}
name = "%s"
}
spec {
container {
image = "%s"
name = "containername"
volume_mount {
mount_path = "/cache"
name = "cache-volume"
}
}
volume {
name = "cache-volume"
empty_dir = {
medium = "Memory"
}
}
}
}
`, podName, imageName)
}

View File

@ -0,0 +1,580 @@
package kubernetes
import "github.com/hashicorp/terraform/helper/schema"
func handlerFields() map[string]*schema.Schema {
return map[string]*schema.Schema{
"exec": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "exec specifies the action to take.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"command": {
Type: schema.TypeList,
Description: `Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.`,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"http_get": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Specifies the http request to perform.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host": {
Type: schema.TypeString,
Optional: true,
Description: `Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.`,
},
"path": {
Type: schema.TypeString,
Optional: true,
Description: `Path to access on the HTTP server.`,
},
"scheme": {
Type: schema.TypeString,
Optional: true,
Default: "HTTP",
Description: `Scheme to use for connecting to the host.`,
},
"port": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validatePortNumOrName,
Description: `Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.`,
},
"http_header": {
Type: schema.TypeList,
Optional: true,
Description: `Scheme to use for connecting to the host.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Description: "The header field name",
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: "The header field value",
},
},
},
},
},
},
},
"tcp_socket": {
Type: schema.TypeList,
Optional: true,
Description: "TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"port": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validatePortNumOrName,
Description: "Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.",
},
},
},
},
}
}
func resourcesField() map[string]*schema.Schema {
return map[string]*schema.Schema{
"limits": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Description: "Describes the maximum amount of compute resources allowed. More info: http://kubernetes.io/docs/user-guide/compute-resources/",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validateResourceQuantity,
DiffSuppressFunc: suppressEquivalentResourceQuantity,
},
"memory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validateResourceQuantity,
DiffSuppressFunc: suppressEquivalentResourceQuantity,
},
},
},
},
"requests": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validateResourceQuantity,
DiffSuppressFunc: suppressEquivalentResourceQuantity,
},
"memory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validateResourceQuantity,
DiffSuppressFunc: suppressEquivalentResourceQuantity,
},
},
},
},
}
}
func seLinuxOptionsField() map[string]*schema.Schema {
return map[string]*schema.Schema{
"level": {
Type: schema.TypeString,
Optional: true,
Description: "Level is SELinux level label that applies to the container.",
},
"role": {
Type: schema.TypeString,
Optional: true,
Description: "Role is a SELinux role label that applies to the container.",
},
"type": {
Type: schema.TypeString,
Optional: true,
Description: "Type is a SELinux type label that applies to the container.",
},
"user": {
Type: schema.TypeString,
Optional: true,
Description: "User is a SELinux user label that applies to the container.",
},
}
}
func volumeMountFields() map[string]*schema.Schema {
return map[string]*schema.Schema{
"mount_path": {
Type: schema.TypeString,
Required: true,
Description: "Path within the container at which the volume should be mounted. Must not contain ':'.",
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "This must match the Name of a Volume.",
},
"read_only": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.",
},
"sub_path": {
Type: schema.TypeString,
Optional: true,
Description: `Path within the volume from which the container's volume should be mounted. Defaults to "" (volume's root).`,
},
}
}
func containerFields() map[string]*schema.Schema {
return map[string]*schema.Schema{
"args": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands",
},
"command": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands",
},
"env": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "List of environment variables to set in the container. Cannot be updated.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of the environment variable. Must be a C_IDENTIFIER",
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: `Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to "".`,
},
"value_from": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Source for the environment variable's value",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_map_key_ref": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Selects a key of a ConfigMap.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
Description: "The key to select.",
},
"name": {
Type: schema.TypeString,
Optional: true,
Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
},
},
},
},
"field_ref": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP..",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_version": {
Type: schema.TypeString,
Optional: true,
Default: "v1",
Description: `Version of the schema the FieldPath is written in terms of, defaults to "v1".`,
},
"field_path": {
Type: schema.TypeString,
Optional: true,
Description: "Path of the field to select in the specified API version",
},
},
},
},
"resource_field_ref": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP..",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"container_name": {
Type: schema.TypeString,
Optional: true,
},
"resource": {
Type: schema.TypeString,
Required: true,
Description: "Resource to select",
},
},
},
},
"secret_key_ref": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP..",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
Description: "The key of the secret to select from. Must be a valid secret key.",
},
"name": {
Type: schema.TypeString,
Optional: true,
Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
},
},
},
},
},
},
},
},
},
},
"image": {
Type: schema.TypeString,
Optional: true,
Description: "Docker image name. More info: http://kubernetes.io/docs/user-guide/images",
},
"image_pull_policy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/images#updating-images",
},
"lifecycle": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Description: "Actions that the management system should take in response to container lifecycle events",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"post_start": {
Type: schema.TypeList,
Description: `post_start is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: http://kubernetes.io/docs/user-guide/container-environment#hook-details`,
Optional: true,
Elem: &schema.Resource{
Schema: handlerFields(),
},
},
"pre_stop": {
Type: schema.TypeList,
Description: `pre_stop is called immediately before a container is terminated. The container is terminated after the handler completes. The reason for termination is passed to the handler. Regardless of the outcome of the handler, the container is eventually terminated. Other management of the container blocks until the hook completes. More info: http://kubernetes.io/docs/user-guide/container-environment#hook-details`,
Optional: true,
Elem: &schema.Resource{
Schema: handlerFields(),
},
},
},
},
},
"liveness_probe": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Description: "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes",
Elem: probeSchema(),
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.",
},
"port": {
Type: schema.TypeList,
Optional: true,
Description: `List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Cannot be updated.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"container_port": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validatePortNumOrName,
Description: "Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.",
},
"host_ip": {
Type: schema.TypeString,
Optional: true,
Description: "What host IP to bind the external port to.",
},
"host_port": {
Type: schema.TypeInt,
Optional: true,
Description: "Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.",
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validatePortNumOrName,
Description: "If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services",
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Description: `Protocol for port. Must be UDP or TCP. Defaults to "TCP".`,
Default: "TCP",
},
},
},
},
"readiness_probe": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Description: "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes",
Elem: probeSchema(),
},
"resources": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Computed: true,
Description: "Compute Resources required by this container. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources",
Elem: &schema.Resource{
Schema: resourcesField(),
},
},
"security_context": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Description: "Security options the pod should run with. More info: http://releases.k8s.io/HEAD/docs/design/security_context.md",
Elem: securityContextSchema(),
},
"stdin": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. ",
},
"stdin_once": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF.",
},
"termination_message_path": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "/dev/termination-log",
Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Defaults to /dev/termination-log. Cannot be updated.",
},
"tty": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether this container should allocate a TTY for itself",
},
"volume_mount": {
Type: schema.TypeList,
Optional: true,
Description: "Pod volumes to mount into the container's filesystem. Cannot be updated.",
Elem: &schema.Resource{
Schema: volumeMountFields(),
},
},
"working_dir": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.",
},
}
}
func probeSchema() *schema.Resource {
h := handlerFields()
h["failure_threshold"] = &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Description: "Minimum consecutive failures for the probe to be considered failed after having succeeded.",
Default: 3,
ValidateFunc: validatePositiveInteger,
}
h["initial_delay_seconds"] = &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Description: "Number of seconds after the container has started before liveness probes are initiated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes",
}
h["period_seconds"] = &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 10,
ValidateFunc: validatePositiveInteger,
Description: "How often (in seconds) to perform the probe",
}
h["success_threshold"] = &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validatePositiveInteger,
Description: "Minimum consecutive successes for the probe to be considered successful after having failed.",
}
h["timeout_seconds"] = &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validatePositiveInteger,
Description: "Number of seconds after which the probe times out. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes",
}
return &schema.Resource{
Schema: h,
}
}
func securityContextSchema() *schema.Resource {
m := map[string]*schema.Schema{
"privileged": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: `Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host.`,
},
"read_only_root_filesystem": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether this container has a read-only root filesystem.",
},
"run_as_non_root": {
Type: schema.TypeBool,
Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does.",
Optional: true,
},
"run_as_user": {
Type: schema.TypeInt,
Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified",
Optional: true,
},
"se_linux_options": {
Type: schema.TypeList,
Description: "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: http://kubernetes.io/docs/user-guide/images#specifying-imagepullsecrets-on-a-pod",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: seLinuxOptionsField(),
},
},
"capabilities": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"add": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "Added capabilities",
},
"drop": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "Removed capabilities",
},
},
},
},
}
return &schema.Resource{
Schema: m,
}
}

View File

@ -0,0 +1,373 @@
package kubernetes
import "github.com/hashicorp/terraform/helper/schema"
func podSpecFields() map[string]*schema.Schema {
return map[string]*schema.Schema{
"active_deadline_seconds": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validatePositiveInteger,
Description: "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.",
},
"container": {
Type: schema.TypeList,
Optional: true,
Description: "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers",
Elem: &schema.Resource{
Schema: containerFields(),
},
},
"dns_policy": {
Type: schema.TypeString,
Optional: true,
Default: "ClusterFirst",
Description: "Set DNS policy for containers within the pod. One of 'ClusterFirst' or 'Default'. Defaults to 'ClusterFirst'.",
},
"host_ipc": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Use the host's ipc namespace. Optional: Default to false.",
},
"host_network": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified.",
},
"host_pid": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Use the host's pid namespace.",
},
"hostname": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.",
},
"image_pull_secrets": {
Type: schema.TypeList,
Description: "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: http://kubernetes.io/docs/user-guide/images#specifying-imagepullsecrets-on-a-pod",
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
Required: true,
},
},
},
},
"node_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.",
},
"node_selector": {
Type: schema.TypeMap,
Optional: true,
Description: "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: http://kubernetes.io/docs/user-guide/node-selection.",
},
"restart_policy": {
Type: schema.TypeString,
Optional: true,
Default: "Always",
Description: "Restart policy for all containers within the pod. One of Always, OnFailure, Never. More info: http://kubernetes.io/docs/user-guide/pod-states#restartpolicy.",
},
"security_context": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"fs_group": {
Type: schema.TypeInt,
Description: "A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod: 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw---- If unset, the Kubelet will not modify the ownership and permissions of any volume.",
Optional: true,
},
"run_as_non_root": {
Type: schema.TypeBool,
Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does.",
Optional: true,
},
"run_as_user": {
Type: schema.TypeInt,
Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified",
Optional: true,
},
"supplemental_groups": {
Type: schema.TypeSet,
Description: "A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.",
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
},
"se_linux_options": {
Type: schema.TypeList,
Description: "The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: seLinuxOptionsField(),
},
},
},
},
},
"service_account_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md.",
},
"subdomain": {
Type: schema.TypeString,
Optional: true,
Description: `If specified, the fully qualified Pod hostname will be "...svc.". If not specified, the pod will not have a domainname at all..`,
},
"termination_grace_period_seconds": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
ValidateFunc: validateTerminationGracePeriodSeconds,
Description: "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process.",
},
"volume": {
Type: schema.TypeList,
Optional: true,
Description: "List of volumes that can be mounted by containers belonging to the pod. More info: http://kubernetes.io/docs/user-guide/volumes",
Elem: volumeSchema(),
},
}
}
func volumeSchema() *schema.Resource {
v := commonVolumeSources()
v["config_map"] = &schema.Schema{
Type: schema.TypeList,
Description: "ConfigMap represents a configMap that should populate this volume",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"items": {
Type: schema.TypeList,
Description: `If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.`,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
Description: "The key to project.",
},
"mode": {
Type: schema.TypeInt,
Optional: true,
Description: `Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.`,
},
"path": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateAttributeValueDoesNotContain(".."),
Description: `The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.`,
},
},
},
},
"default_mode": {
Type: schema.TypeInt,
Description: "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.",
Optional: true,
},
"name": {
Type: schema.TypeString,
Description: "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
Optional: true,
},
},
},
}
v["git_repo"] = &schema.Schema{
Type: schema.TypeList,
Description: "GitRepo represents a git repository at a particular revision.",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"directory": {
Type: schema.TypeString,
Description: "Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.",
Optional: true,
ValidateFunc: validateAttributeValueDoesNotContain(".."),
},
"repository": {
Type: schema.TypeString,
Description: "Repository URL",
Optional: true,
},
"revision": {
Type: schema.TypeString,
Description: "Commit hash for the specified revision.",
Optional: true,
},
},
},
}
v["downward_api"] = &schema.Schema{
Type: schema.TypeList,
Description: "DownwardAPI represents downward API about the pod that should populate this volume",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"default_mode": {
Type: schema.TypeInt,
Description: "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.",
Optional: true,
},
"items": {
Type: schema.TypeList,
Description: `If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.`,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"field_ref": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Description: "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_version": {
Type: schema.TypeString,
Optional: true,
Default: "v1",
Description: `Version of the schema the FieldPath is written in terms of, defaults to "v1".`,
},
"field_path": {
Type: schema.TypeString,
Optional: true,
Description: "Path of the field to select in the specified API version",
},
},
},
},
"mode": {
Type: schema.TypeInt,
Optional: true,
Description: `Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.`,
},
"path": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateAttributeValueDoesNotContain(".."),
Description: `Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'`,
},
"resource_field_ref": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"container_name": {
Type: schema.TypeString,
Required: true,
},
"quantity": {
Type: schema.TypeString,
Optional: true,
},
"resource": {
Type: schema.TypeString,
Required: true,
Description: "Resource to select",
},
},
},
},
},
},
},
},
},
}
v["empty_dir"] = &schema.Schema{
Type: schema.TypeList,
Description: "EmptyDir represents a temporary directory that shares a pod's lifetime. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"medium": {
Type: schema.TypeString,
Description: `What type of storage medium should back this directory. The default is "" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir`,
Optional: true,
Default: "",
ValidateFunc: validateAttributeValueIsIn([]string{"", "Memory"}),
},
},
},
}
v["persistent_volume_claim"] = &schema.Schema{
Type: schema.TypeList,
Description: "The specification of a persistent volume.",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"claim_name": {
Type: schema.TypeString,
Description: "ClaimName is the name of a PersistentVolumeClaim in the same ",
Optional: true,
},
"read_only": {
Type: schema.TypeBool,
Description: "Will force the ReadOnly setting in VolumeMounts.",
Optional: true,
Default: false,
},
},
},
}
v["secret"] = &schema.Schema{
Type: schema.TypeList,
Description: "Secret represents a secret that should populate this volume. More info: http://kubernetes.io/docs/user-guide/volumes#secrets",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"secret_name": {
Type: schema.TypeString,
Description: "Name of the secret in the pod's namespace to use. More info: http://kubernetes.io/docs/user-guide/volumes#secrets",
Optional: true,
},
},
},
}
v["name"] = &schema.Schema{
Type: schema.TypeString,
Description: "Volume's name. Must be a DNS_LABEL and unique within the pod. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
Optional: true,
}
return &schema.Resource{
Schema: v,
}
}

View File

@ -5,7 +5,15 @@ import (
)
func persistentVolumeSourceSchema() *schema.Resource {
volumeSources["host_path"] = &schema.Schema{
return &schema.Resource{
Schema: commonVolumeSources(),
}
}
// Common volume sources between Persistent Volumes and Pod Volumes
func commonVolumeSources() map[string]*schema.Schema {
return map[string]*schema.Schema{
"host_path": {
Type: schema.TypeList,
Description: "Represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath",
Optional: true,
@ -19,14 +27,7 @@ func persistentVolumeSourceSchema() *schema.Resource {
},
},
},
}
return &schema.Resource{
Schema: volumeSources,
}
}
// Common volume sources between Persistent Volumes and Pod Volumes
var volumeSources = map[string]*schema.Schema{
},
"aws_elastic_block_store": {
Type: schema.TypeList,
Description: "Represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore",
@ -554,4 +555,5 @@ var volumeSources = map[string]*schema.Schema{
},
},
},
}
}

View File

@ -1,11 +1,11 @@
package kubernetes
import (
"encoding/base64"
"fmt"
"net/url"
"strings"
"encoding/base64"
"github.com/hashicorp/terraform/helper/schema"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -137,6 +137,10 @@ func ptrToInt32(i int32) *int32 {
return &i
}
func ptrToInt64(i int64) *int64 {
return &i
}
func sliceOfString(slice []interface{}) []string {
result := make([]string, len(slice), len(slice))
for i, s := range slice {
@ -258,6 +262,13 @@ func newStringSet(f schema.SchemaSetFunc, in []string) *schema.Set {
}
return schema.NewSet(f, out)
}
func newInt64Set(f schema.SchemaSetFunc, in []int64) *schema.Set {
var out = make([]interface{}, len(in), len(in))
for i, v := range in {
out[i] = int(v)
}
return schema.NewSet(f, out)
}
func resourceListEquals(x, y api.ResourceList) bool {
for k, v := range x {
@ -374,3 +385,58 @@ func flattenLimitRangeSpec(in api.LimitRangeSpec) []interface{} {
}
return out
}
func schemaSetToStringArray(set *schema.Set) []string {
array := make([]string, 0, set.Len())
for _, elem := range set.List() {
e := elem.(string)
array = append(array, e)
}
return array
}
func schemaSetToInt64Array(set *schema.Set) []int64 {
array := make([]int64, 0, set.Len())
for _, elem := range set.List() {
e := elem.(int)
array = append(array, int64(e))
}
return array
}
func flattenLabelSelectorRequirementList(l []metav1.LabelSelectorRequirement) []interface{} {
att := make([]map[string]interface{}, len(l))
for i, v := range l {
m := map[string]interface{}{}
m["key"] = v.Key
m["values"] = newStringSet(schema.HashString, v.Values)
m["operator"] = string(v.Operator)
att[i] = m
}
return []interface{}{att}
}
func flattenLocalObjectReferenceArray(in []api.LocalObjectReference) []interface{} {
att := make([]interface{}, len(in))
for i, v := range in {
m := map[string]interface{}{}
if v.Name != "" {
m["name"] = v.Name
}
att[i] = m
}
return att
}
func expandLocalObjectReferenceArray(in []interface{}) []api.LocalObjectReference {
att := []api.LocalObjectReference{}
if len(in) < 1 {
return att
}
att = make([]api.LocalObjectReference, len(in))
for i, c := range in {
p := c.(map[string]interface{})
if name, ok := p["name"]; ok {
att[i].Name = name.(string)
}
}
return att
}

View File

@ -0,0 +1,846 @@
package kubernetes
import (
"strconv"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/kubernetes/pkg/api/v1"
)
func flattenCapability(in []v1.Capability) []string {
att := make([]string, 0, len(in))
for i, v := range in {
att[i] = string(v)
}
return att
}
func flattenContainerSecurityContext(in *v1.SecurityContext) []interface{} {
att := make(map[string]interface{})
if in.Privileged != nil {
att["privileged"] = *in.Privileged
}
if in.ReadOnlyRootFilesystem != nil {
att["read_only_root_filesystem"] = *in.ReadOnlyRootFilesystem
}
if in.RunAsNonRoot != nil {
att["run_as_non_root"] = *in.RunAsNonRoot
}
if in.RunAsUser != nil {
att["run_as_user"] = *in.RunAsUser
}
if in.SELinuxOptions != nil {
att["se_linux_options"] = flattenSeLinuxOptions(in.SELinuxOptions)
}
if in.Capabilities != nil {
att["capabilities"] = flattenSecurityCapabilities(in.Capabilities)
}
return []interface{}{att}
}
func flattenSecurityCapabilities(in *v1.Capabilities) []interface{} {
att := make(map[string]interface{})
if in.Add != nil {
att["add"] = flattenCapability(in.Add)
}
if in.Drop != nil {
att["drop"] = flattenCapability(in.Drop)
}
return []interface{}{att}
}
func flattenHandler(in *v1.Handler) []interface{} {
att := make(map[string]interface{})
if in.Exec != nil {
att["exec"] = flattenExec(in.Exec)
}
if in.HTTPGet != nil {
att["http_get"] = flattenHTTPGet(in.HTTPGet)
}
if in.TCPSocket != nil {
att["tcp_socket"] = flattenTCPSocket(in.TCPSocket)
}
return []interface{}{att}
}
func flattenHTTPHeader(in []v1.HTTPHeader) []interface{} {
att := make([]interface{}, len(in))
for i, v := range in {
m := map[string]interface{}{}
if v.Name != "" {
m["name"] = v.Name
}
if v.Value != "" {
m["value"] = v.Value
}
att[i] = m
}
return att
}
func expandPort(v string) intstr.IntOrString {
i, err := strconv.Atoi(v)
if err != nil {
return intstr.IntOrString{
Type: intstr.String,
StrVal: v,
}
}
return intstr.IntOrString{
Type: intstr.Int,
IntVal: int32(i),
}
}
func flattenHTTPGet(in *v1.HTTPGetAction) []interface{} {
att := make(map[string]interface{})
if in.Host != "" {
att["host"] = in.Host
}
if in.Path != "" {
att["path"] = in.Path
}
att["port"] = in.Port.String()
att["scheme"] = in.Scheme
if len(in.HTTPHeaders) > 0 {
att["http_header"] = flattenHTTPHeader(in.HTTPHeaders)
}
return []interface{}{att}
}
func flattenTCPSocket(in *v1.TCPSocketAction) []interface{} {
att := make(map[string]interface{})
att["port"] = in.Port.String()
return []interface{}{att}
}
func flattenExec(in *v1.ExecAction) []interface{} {
att := make(map[string]interface{})
if len(in.Command) > 0 {
att["command"] = in.Command
}
return []interface{}{att}
}
func flattenLifeCycle(in *v1.Lifecycle) []interface{} {
att := make(map[string]interface{})
if in.PostStart != nil {
att["post_start"] = flattenHandler(in.PostStart)
}
if in.PreStop != nil {
att["pre_stop"] = flattenHandler(in.PreStop)
}
return []interface{}{att}
}
func flattenProbe(in *v1.Probe) []interface{} {
att := make(map[string]interface{})
att["failure_threshold"] = in.FailureThreshold
att["initial_delay_seconds"] = in.InitialDelaySeconds
att["period_seconds"] = in.PeriodSeconds
att["success_threshold"] = in.SuccessThreshold
att["timeout_seconds"] = in.TimeoutSeconds
if in.Exec != nil {
att["exec"] = flattenExec(in.Exec)
}
if in.HTTPGet != nil {
att["http_get"] = flattenHTTPGet(in.HTTPGet)
}
if in.TCPSocket != nil {
att["tcp_socket"] = flattenTCPSocket(in.TCPSocket)
}
return []interface{}{att}
}
func flattenConfigMapKeyRef(in *v1.ConfigMapKeySelector) []interface{} {
att := make(map[string]interface{})
if in.Key != "" {
att["key"] = in.Key
}
if in.Name != "" {
att["name"] = in.Name
}
return []interface{}{att}
}
func flattenObjectFieldSelector(in *v1.ObjectFieldSelector) []interface{} {
att := make(map[string]interface{})
if in.APIVersion != "" {
att["api_version"] = in.APIVersion
}
if in.FieldPath != "" {
att["field_path"] = in.FieldPath
}
return []interface{}{att}
}
func flattenResourceFieldSelector(in *v1.ResourceFieldSelector) []interface{} {
att := make(map[string]interface{})
if in.ContainerName != "" {
att["container_name"] = in.ContainerName
}
if in.Resource != "" {
att["resource"] = in.Resource
}
return []interface{}{att}
}
func flattenSecretKeyRef(in *v1.SecretKeySelector) []interface{} {
att := make(map[string]interface{})
if in.Key != "" {
att["key"] = in.Key
}
if in.Name != "" {
att["name"] = in.Name
}
return []interface{}{att}
}
func flattenValueFrom(in *v1.EnvVarSource) []interface{} {
att := make(map[string]interface{})
if in.ConfigMapKeyRef != nil {
att["config_map_key_ref"] = flattenConfigMapKeyRef(in.ConfigMapKeyRef)
}
if in.ResourceFieldRef != nil {
att["resource_field_ref"] = flattenResourceFieldSelector(in.ResourceFieldRef)
}
if in.SecretKeyRef != nil {
att["secret_key_ref"] = flattenSecretKeyRef(in.SecretKeyRef)
}
if in.FieldRef != nil {
att["field_ref"] = flattenObjectFieldSelector(in.FieldRef)
}
return []interface{}{att}
}
func flattenContainerVolumeMounts(in []v1.VolumeMount) ([]interface{}, error) {
att := make([]interface{}, len(in))
for i, v := range in {
m := map[string]interface{}{}
m["read_only"] = v.ReadOnly
if v.MountPath != "" {
m["mount_path"] = v.MountPath
}
if v.Name != "" {
m["name"] = v.Name
}
if v.SubPath != "" {
m["sub_path"] = v.SubPath
}
att[i] = m
}
return att, nil
}
func flattenContainerEnvs(in []v1.EnvVar) []interface{} {
att := make([]interface{}, len(in))
for i, v := range in {
m := map[string]interface{}{}
if v.Name != "" {
m["name"] = v.Name
}
if v.Value != "" {
m["value"] = v.Value
}
if v.ValueFrom != nil {
m["value_from"] = flattenValueFrom(v.ValueFrom)
}
att[i] = m
}
return att
}
func flattenContainerPorts(in []v1.ContainerPort) []interface{} {
att := make([]interface{}, len(in))
for i, v := range in {
m := map[string]interface{}{}
m["container_port"] = v.ContainerPort
if v.HostIP != "" {
m["host_ip"] = v.HostIP
}
m["host_port"] = v.HostPort
if v.Name != "" {
m["name"] = v.Name
}
if v.Protocol != "" {
m["protocol"] = v.Protocol
}
att[i] = m
}
return att
}
func flattenContainerResourceRequirements(in v1.ResourceRequirements) ([]interface{}, error) {
att := make(map[string]interface{})
if len(in.Limits) > 0 {
att["limits"] = []interface{}{flattenResourceList(in.Limits)}
}
if len(in.Requests) > 0 {
att["requests"] = []interface{}{flattenResourceList(in.Requests)}
}
return []interface{}{att}, nil
}
func flattenContainers(in []v1.Container) ([]interface{}, error) {
att := make([]interface{}, len(in))
for i, v := range in {
c := make(map[string]interface{})
c["image"] = v.Image
c["name"] = v.Name
if len(v.Command) > 0 {
c["command"] = v.Command
}
if len(v.Args) > 0 {
c["args"] = v.Args
}
c["image_pull_policy"] = v.ImagePullPolicy
c["termination_message_path"] = v.TerminationMessagePath
c["stdin"] = v.Stdin
c["stdin_once"] = v.StdinOnce
c["tty"] = v.TTY
c["working_dir"] = v.WorkingDir
res, err := flattenContainerResourceRequirements(v.Resources)
if err != nil {
return nil, err
}
c["resources"] = res
if v.LivenessProbe != nil {
c["liveness_probe"] = flattenProbe(v.LivenessProbe)
}
if v.ReadinessProbe != nil {
c["readiness_probe"] = flattenProbe(v.ReadinessProbe)
}
if v.Lifecycle != nil {
c["lifecycle"] = flattenLifeCycle(v.Lifecycle)
}
if v.SecurityContext != nil {
c["security_context"] = flattenContainerSecurityContext(v.SecurityContext)
}
if len(v.Ports) > 0 {
c["port"] = flattenContainerPorts(v.Ports)
}
if len(v.Env) > 0 {
c["env"] = flattenContainerEnvs(v.Env)
}
if len(v.VolumeMounts) > 0 {
volumeMounts, err := flattenContainerVolumeMounts(v.VolumeMounts)
if err != nil {
return nil, err
}
c["volume_mount"] = volumeMounts
}
att[i] = c
}
return att, nil
}
func expandContainers(ctrs []interface{}) ([]v1.Container, error) {
if len(ctrs) == 0 {
return []v1.Container{}, nil
}
cs := make([]v1.Container, len(ctrs))
for i, c := range ctrs {
ctr := c.(map[string]interface{})
if image, ok := ctr["image"]; ok {
cs[i].Image = image.(string)
}
if name, ok := ctr["name"]; ok {
cs[i].Name = name.(string)
}
if command, ok := ctr["command"].([]interface{}); ok {
cs[i].Command = expandStringSlice(command)
}
if args, ok := ctr["args"].([]interface{}); ok {
cs[i].Args = expandStringSlice(args)
}
if v, ok := ctr["resources"].([]interface{}); ok && len(v) > 0 {
var err error
cs[i].Resources, err = expandContainerResourceRequirements(v)
if err != nil {
return cs, err
}
}
if v, ok := ctr["port"].([]interface{}); ok && len(v) > 0 {
var err error
cs[i].Ports, err = expandContainerPort(v)
if err != nil {
return cs, err
}
}
if v, ok := ctr["env"].([]interface{}); ok && len(v) > 0 {
var err error
cs[i].Env, err = expandContainerEnv(v)
if err != nil {
return cs, err
}
}
if policy, ok := ctr["image_pull_policy"]; ok {
cs[i].ImagePullPolicy = v1.PullPolicy(policy.(string))
}
if v, ok := ctr["lifecycle"].([]interface{}); ok && len(v) > 0 {
cs[i].Lifecycle = expandLifeCycle(v)
}
if v, ok := ctr["liveness_probe"].([]interface{}); ok && len(v) > 0 {
cs[i].LivenessProbe = expandProbe(v)
}
if v, ok := ctr["readiness_probe"].([]interface{}); ok && len(v) > 0 {
cs[i].ReadinessProbe = expandProbe(v)
}
if v, ok := ctr["stdin"]; ok {
cs[i].Stdin = v.(bool)
}
if v, ok := ctr["stdin_once"]; ok {
cs[i].StdinOnce = v.(bool)
}
if v, ok := ctr["termination_message_path"]; ok {
cs[i].TerminationMessagePath = v.(string)
}
if v, ok := ctr["tty"]; ok {
cs[i].TTY = v.(bool)
}
if v, ok := ctr["security_context"].([]interface{}); ok && len(v) > 0 {
cs[i].SecurityContext = expandContainerSecurityContext(v)
}
if v, ok := ctr["volume_mount"].([]interface{}); ok && len(v) > 0 {
var err error
cs[i].VolumeMounts, err = expandContainerVolumeMounts(v)
if err != nil {
return cs, err
}
}
}
return cs, nil
}
func expandExec(l []interface{}) *v1.ExecAction {
if len(l) == 0 || l[0] == nil {
return &v1.ExecAction{}
}
in := l[0].(map[string]interface{})
obj := v1.ExecAction{}
if v, ok := in["command"].([]interface{}); ok && len(v) > 0 {
obj.Command = expandStringSlice(v)
}
return &obj
}
func expandHTTPHeaders(l []interface{}) []v1.HTTPHeader {
if len(l) == 0 {
return []v1.HTTPHeader{}
}
headers := make([]v1.HTTPHeader, len(l))
for i, c := range l {
m := c.(map[string]interface{})
if v, ok := m["name"]; ok {
headers[i].Name = v.(string)
}
if v, ok := m["value"]; ok {
headers[i].Value = v.(string)
}
}
return headers
}
func expandContainerSecurityContext(l []interface{}) *v1.SecurityContext {
if len(l) == 0 || l[0] == nil {
return &v1.SecurityContext{}
}
in := l[0].(map[string]interface{})
obj := v1.SecurityContext{}
if v, ok := in["privileged"]; ok {
obj.Privileged = ptrToBool(v.(bool))
}
if v, ok := in["read_only_root_filesystem"]; ok {
obj.ReadOnlyRootFilesystem = ptrToBool(v.(bool))
}
if v, ok := in["run_as_non_root"]; ok {
obj.RunAsNonRoot = ptrToBool(v.(bool))
}
if v, ok := in["run_as_user"]; ok {
obj.RunAsUser = ptrToInt64(int64(v.(int)))
}
if v, ok := in["se_linux_options"].([]interface{}); ok && len(v) > 0 {
obj.SELinuxOptions = expandSeLinuxOptions(v)
}
if v, ok := in["capabilities"].([]interface{}); ok && len(v) > 0 {
obj.Capabilities = expandSecurityCapabilities(v)
}
return &obj
}
func expandCapabilitySlice(s []interface{}) []v1.Capability {
result := make([]v1.Capability, len(s), len(s))
for k, v := range s {
result[k] = v.(v1.Capability)
}
return result
}
func expandSecurityCapabilities(l []interface{}) *v1.Capabilities {
if len(l) == 0 || l[0] == nil {
return &v1.Capabilities{}
}
in := l[0].(map[string]interface{})
obj := v1.Capabilities{}
if v, ok := in["add"].([]interface{}); ok {
obj.Add = expandCapabilitySlice(v)
}
if v, ok := in["drop"].([]interface{}); ok {
obj.Drop = expandCapabilitySlice(v)
}
return &obj
}
func expandTCPSocket(l []interface{}) *v1.TCPSocketAction {
if len(l) == 0 || l[0] == nil {
return &v1.TCPSocketAction{}
}
in := l[0].(map[string]interface{})
obj := v1.TCPSocketAction{}
if v, ok := in["port"].(string); ok && len(v) > 0 {
obj.Port = expandPort(v)
}
return &obj
}
func expandHTTPGet(l []interface{}) *v1.HTTPGetAction {
if len(l) == 0 || l[0] == nil {
return &v1.HTTPGetAction{}
}
in := l[0].(map[string]interface{})
obj := v1.HTTPGetAction{}
if v, ok := in["host"].(string); ok && len(v) > 0 {
obj.Host = v
}
if v, ok := in["path"].(string); ok && len(v) > 0 {
obj.Path = v
}
if v, ok := in["scheme"].(string); ok && len(v) > 0 {
obj.Scheme = v1.URIScheme(v)
}
if v, ok := in["port"].(string); ok && len(v) > 0 {
obj.Port = expandPort(v)
}
if v, ok := in["http_header"].([]interface{}); ok && len(v) > 0 {
obj.HTTPHeaders = expandHTTPHeaders(v)
}
return &obj
}
func expandProbe(l []interface{}) *v1.Probe {
if len(l) == 0 || l[0] == nil {
return &v1.Probe{}
}
in := l[0].(map[string]interface{})
obj := v1.Probe{}
if v, ok := in["exec"].([]interface{}); ok && len(v) > 0 {
obj.Exec = expandExec(v)
}
if v, ok := in["http_get"].([]interface{}); ok && len(v) > 0 {
obj.HTTPGet = expandHTTPGet(v)
}
if v, ok := in["tcp_socket"].([]interface{}); ok && len(v) > 0 {
obj.TCPSocket = expandTCPSocket(v)
}
if v, ok := in["failure_threshold"].(int); ok {
obj.FailureThreshold = int32(v)
}
if v, ok := in["initial_delay_seconds"].(int); ok {
obj.InitialDelaySeconds = int32(v)
}
if v, ok := in["period_seconds"].(int); ok {
obj.PeriodSeconds = int32(v)
}
if v, ok := in["success_threshold"].(int); ok {
obj.SuccessThreshold = int32(v)
}
if v, ok := in["timeout_seconds"].(int); ok {
obj.TimeoutSeconds = int32(v)
}
return &obj
}
func expandHandlers(l []interface{}) *v1.Handler {
if len(l) == 0 || l[0] == nil {
return &v1.Handler{}
}
in := l[0].(map[string]interface{})
obj := v1.Handler{}
if v, ok := in["exec"].([]interface{}); ok && len(v) > 0 {
obj.Exec = expandExec(v)
}
if v, ok := in["http_get"].([]interface{}); ok && len(v) > 0 {
obj.HTTPGet = expandHTTPGet(v)
}
if v, ok := in["tcp_socket"].([]interface{}); ok && len(v) > 0 {
obj.TCPSocket = expandTCPSocket(v)
}
return &obj
}
func expandLifeCycle(l []interface{}) *v1.Lifecycle {
if len(l) == 0 || l[0] == nil {
return &v1.Lifecycle{}
}
in := l[0].(map[string]interface{})
obj := &v1.Lifecycle{}
if v, ok := in["post_start"].([]interface{}); ok && len(v) > 0 {
obj.PostStart = expandHandlers(v)
}
if v, ok := in["pre_stop"].([]interface{}); ok && len(v) > 0 {
obj.PreStop = expandHandlers(v)
}
return obj
}
func expandContainerVolumeMounts(in []interface{}) ([]v1.VolumeMount, error) {
if len(in) == 0 {
return []v1.VolumeMount{}, nil
}
vmp := make([]v1.VolumeMount, len(in))
for i, c := range in {
p := c.(map[string]interface{})
if mountPath, ok := p["mount_path"]; ok {
vmp[i].MountPath = mountPath.(string)
}
if name, ok := p["name"]; ok {
vmp[i].Name = name.(string)
}
if readOnly, ok := p["read_only"]; ok {
vmp[i].ReadOnly = readOnly.(bool)
}
if subPath, ok := p["sub_path"]; ok {
vmp[i].SubPath = subPath.(string)
}
}
return vmp, nil
}
func expandContainerEnv(in []interface{}) ([]v1.EnvVar, error) {
if len(in) == 0 {
return []v1.EnvVar{}, nil
}
envs := make([]v1.EnvVar, len(in))
for i, c := range in {
p := c.(map[string]interface{})
if name, ok := p["name"]; ok {
envs[i].Name = name.(string)
}
if value, ok := p["value"]; ok {
envs[i].Value = value.(string)
}
if v, ok := p["value_from"].([]interface{}); ok && len(v) > 0 {
var err error
envs[i].ValueFrom, err = expandEnvValueFrom(v)
if err != nil {
return envs, err
}
}
}
return envs, nil
}
func expandContainerPort(in []interface{}) ([]v1.ContainerPort, error) {
if len(in) == 0 {
return []v1.ContainerPort{}, nil
}
ports := make([]v1.ContainerPort, len(in))
for i, c := range in {
p := c.(map[string]interface{})
if containerPort, ok := p["container_port"]; ok {
ports[i].ContainerPort = int32(containerPort.(int))
}
if hostIP, ok := p["host_ip"]; ok {
ports[i].HostIP = hostIP.(string)
}
if hostPort, ok := p["host_port"]; ok {
ports[i].HostPort = int32(hostPort.(int))
}
if name, ok := p["name"]; ok {
ports[i].Name = name.(string)
}
if protocol, ok := p["protocol"]; ok {
ports[i].Protocol = v1.Protocol(protocol.(string))
}
}
return ports, nil
}
func expandConfigMapKeyRef(r []interface{}) (*v1.ConfigMapKeySelector, error) {
if len(r) == 0 || r[0] == nil {
return &v1.ConfigMapKeySelector{}, nil
}
in := r[0].(map[string]interface{})
obj := &v1.ConfigMapKeySelector{}
if v, ok := in["key"].(string); ok {
obj.Key = v
}
if v, ok := in["name"].(string); ok {
obj.Name = v
}
return obj, nil
}
func expandFieldRef(r []interface{}) (*v1.ObjectFieldSelector, error) {
if len(r) == 0 || r[0] == nil {
return &v1.ObjectFieldSelector{}, nil
}
in := r[0].(map[string]interface{})
obj := &v1.ObjectFieldSelector{}
if v, ok := in["api_version"].(string); ok {
obj.APIVersion = v
}
if v, ok := in["field_path"].(string); ok {
obj.FieldPath = v
}
return obj, nil
}
func expandResourceFieldRef(r []interface{}) (*v1.ResourceFieldSelector, error) {
if len(r) == 0 || r[0] == nil {
return &v1.ResourceFieldSelector{}, nil
}
in := r[0].(map[string]interface{})
obj := &v1.ResourceFieldSelector{}
if v, ok := in["container_name"].(string); ok {
obj.ContainerName = v
}
if v, ok := in["resource"].(string); ok {
obj.Resource = v
}
return obj, nil
}
func expandSecretKeyRef(r []interface{}) (*v1.SecretKeySelector, error) {
if len(r) == 0 || r[0] == nil {
return &v1.SecretKeySelector{}, nil
}
in := r[0].(map[string]interface{})
obj := &v1.SecretKeySelector{}
if v, ok := in["key"].(string); ok {
obj.Key = v
}
if v, ok := in["name"].(string); ok {
obj.Name = v
}
return obj, nil
}
func expandEnvValueFrom(r []interface{}) (*v1.EnvVarSource, error) {
if len(r) == 0 || r[0] == nil {
return &v1.EnvVarSource{}, nil
}
in := r[0].(map[string]interface{})
obj := &v1.EnvVarSource{}
var err error
if v, ok := in["config_map_key_ref"].([]interface{}); ok && len(v) > 0 {
obj.ConfigMapKeyRef, err = expandConfigMapKeyRef(v)
if err != nil {
return obj, err
}
}
if v, ok := in["field_ref"].([]interface{}); ok && len(v) > 0 {
obj.FieldRef, err = expandFieldRef(v)
if err != nil {
return obj, err
}
}
if v, ok := in["secret_key_ref"].([]interface{}); ok && len(v) > 0 {
obj.SecretKeyRef, err = expandSecretKeyRef(v)
if err != nil {
return obj, err
}
}
if v, ok := in["resource_field_ref"].([]interface{}); ok && len(v) > 0 {
obj.ResourceFieldRef, err = expandResourceFieldRef(v)
if err != nil {
return obj, err
}
}
return obj, nil
}
func expandContainerResourceRequirements(l []interface{}) (v1.ResourceRequirements, error) {
if len(l) == 0 || l[0] == nil {
return v1.ResourceRequirements{}, nil
}
in := l[0].(map[string]interface{})
obj := v1.ResourceRequirements{}
fn := func(in []interface{}) (v1.ResourceList, error) {
for _, c := range in {
p := c.(map[string]interface{})
if p["cpu"] == "" {
delete(p, "cpu")
}
if p["memory"] == "" {
delete(p, "memory")
}
return expandMapToResourceList(p)
}
return nil, nil
}
var err error
if v, ok := in["limits"].([]interface{}); ok && len(v) > 0 {
obj.Limits, err = fn(v)
if err != nil {
return obj, err
}
}
if v, ok := in["requests"].([]interface{}); ok && len(v) > 0 {
obj.Requests, err = fn(v)
if err != nil {
return obj, err
}
}
return obj, nil
}

View File

@ -0,0 +1,684 @@
package kubernetes
import (
"strconv"
"github.com/hashicorp/terraform/helper/schema"
"k8s.io/kubernetes/pkg/api/v1"
)
// Flatteners
func flattenPodSpec(in v1.PodSpec) ([]interface{}, error) {
att := make(map[string]interface{})
if in.ActiveDeadlineSeconds != nil {
att["active_deadline_seconds"] = *in.ActiveDeadlineSeconds
}
containers, err := flattenContainers(in.Containers)
if err != nil {
return nil, err
}
att["container"] = containers
att["dns_policy"] = in.DNSPolicy
att["host_ipc"] = in.HostIPC
att["host_network"] = in.HostNetwork
att["host_pid"] = in.HostPID
if in.Hostname != "" {
att["hostname"] = in.Hostname
}
att["image_pull_secrets"] = flattenLocalObjectReferenceArray(in.ImagePullSecrets)
if in.NodeName != "" {
att["node_name"] = in.NodeName
}
if len(in.NodeSelector) > 0 {
att["node_selector"] = in.NodeSelector
}
if in.RestartPolicy != "" {
att["restart_policy"] = in.RestartPolicy
}
if in.SecurityContext != nil {
att["security_context"] = flattenPodSecurityContext(in.SecurityContext)
}
if in.ServiceAccountName != "" {
att["service_account_name"] = in.ServiceAccountName
}
if in.Subdomain != "" {
att["subdomain"] = in.Subdomain
}
if in.TerminationGracePeriodSeconds != nil {
att["termination_grace_period_seconds"] = *in.TerminationGracePeriodSeconds
}
if len(in.Volumes) > 0 {
v, err := flattenVolumes(in.Volumes)
if err != nil {
return []interface{}{att}, err
}
att["volume"] = v
}
return []interface{}{att}, nil
}
func flattenPodSecurityContext(in *v1.PodSecurityContext) []interface{} {
att := make(map[string]interface{})
if in.FSGroup != nil {
att["fs_group"] = *in.FSGroup
}
if in.RunAsNonRoot != nil {
att["run_as_non_root"] = *in.RunAsNonRoot
}
if in.RunAsUser != nil {
att["run_as_user"] = *in.RunAsUser
}
if len(in.SupplementalGroups) > 0 {
att["supplemental_groups"] = newInt64Set(schema.HashSchema(&schema.Schema{
Type: schema.TypeInt,
}), in.SupplementalGroups)
}
if in.SELinuxOptions != nil {
att["se_linux_options"] = flattenSeLinuxOptions(in.SELinuxOptions)
}
if len(att) > 0 {
return []interface{}{att}
}
return []interface{}{}
}
func flattenSeLinuxOptions(in *v1.SELinuxOptions) []interface{} {
att := make(map[string]interface{})
if in.User != "" {
att["user"] = in.User
}
if in.Role != "" {
att["role"] = in.Role
}
if in.User != "" {
att["type"] = in.Type
}
if in.Level != "" {
att["level"] = in.Level
}
return []interface{}{att}
}
func flattenVolumes(volumes []v1.Volume) ([]interface{}, error) {
att := make([]interface{}, len(volumes))
for i, v := range volumes {
obj := map[string]interface{}{}
if v.Name != "" {
obj["name"] = v.Name
}
if v.ConfigMap != nil {
obj["config_map"] = flattenConfigMapVolumeSource(v.ConfigMap)
}
if v.GitRepo != nil {
obj["git_repo"] = flattenGitRepoVolumeSource(v.GitRepo)
}
if v.EmptyDir != nil {
obj["empty_dir"] = flattenEmptyDirVolumeSource(v.EmptyDir)
}
if v.DownwardAPI != nil {
obj["downward_api"] = flattenDownwardAPIVolumeSource(v.DownwardAPI)
}
if v.PersistentVolumeClaim != nil {
obj["persistent_volume_claim"] = flattenPersistentVolumeClaimVolumeSource(v.PersistentVolumeClaim)
}
if v.Secret != nil {
obj["secret"] = flattenSecretVolumeSource(v.Secret)
}
if v.GCEPersistentDisk != nil {
obj["gce_persistent_disk"] = flattenGCEPersistentDiskVolumeSource(v.GCEPersistentDisk)
}
if v.AWSElasticBlockStore != nil {
obj["aws_elastic_block_store"] = flattenAWSElasticBlockStoreVolumeSource(v.AWSElasticBlockStore)
}
if v.HostPath != nil {
obj["host_path"] = flattenHostPathVolumeSource(v.HostPath)
}
if v.Glusterfs != nil {
obj["glusterfs"] = flattenGlusterfsVolumeSource(v.Glusterfs)
}
if v.NFS != nil {
obj["nfs"] = flattenNFSVolumeSource(v.NFS)
}
if v.RBD != nil {
obj["rbd"] = flattenRBDVolumeSource(v.RBD)
}
if v.ISCSI != nil {
obj["iscsi"] = flattenISCSIVolumeSource(v.ISCSI)
}
if v.Cinder != nil {
obj["cinder"] = flattenCinderVolumeSource(v.Cinder)
}
if v.CephFS != nil {
obj["ceph_fs"] = flattenCephFSVolumeSource(v.CephFS)
}
if v.FC != nil {
obj["fc"] = flattenFCVolumeSource(v.FC)
}
if v.Flocker != nil {
obj["flocker"] = flattenFlockerVolumeSource(v.Flocker)
}
if v.FlexVolume != nil {
obj["flex_volume"] = flattenFlexVolumeSource(v.FlexVolume)
}
if v.AzureFile != nil {
obj["azure_file"] = flattenAzureFileVolumeSource(v.AzureFile)
}
if v.VsphereVolume != nil {
obj["vsphere_volume"] = flattenVsphereVirtualDiskVolumeSource(v.VsphereVolume)
}
if v.Quobyte != nil {
obj["quobyte"] = flattenQuobyteVolumeSource(v.Quobyte)
}
if v.AzureDisk != nil {
obj["azure_disk"] = flattenAzureDiskVolumeSource(v.AzureDisk)
}
if v.PhotonPersistentDisk != nil {
obj["photon_persistent_disk"] = flattenPhotonPersistentDiskVolumeSource(v.PhotonPersistentDisk)
}
att[i] = obj
}
return att, nil
}
func flattenPersistentVolumeClaimVolumeSource(in *v1.PersistentVolumeClaimVolumeSource) []interface{} {
att := make(map[string]interface{})
if in.ClaimName != "" {
att["claim_name"] = in.ClaimName
}
if in.ReadOnly {
att["read_only"] = in.ReadOnly
}
return []interface{}{att}
}
func flattenGitRepoVolumeSource(in *v1.GitRepoVolumeSource) []interface{} {
att := make(map[string]interface{})
if in.Directory != "" {
att["directory"] = in.Directory
}
att["repository"] = in.Repository
if in.Revision != "" {
att["revision"] = in.Revision
}
return []interface{}{att}
}
func flattenDownwardAPIVolumeSource(in *v1.DownwardAPIVolumeSource) []interface{} {
att := make(map[string]interface{})
if in.DefaultMode != nil {
att["default_mode"] = in.DefaultMode
}
if len(in.Items) > 0 {
att["items"] = flattenDownwardAPIVolumeFile(in.Items)
}
return []interface{}{att}
}
func flattenDownwardAPIVolumeFile(in []v1.DownwardAPIVolumeFile) []interface{} {
att := make([]interface{}, len(in))
for i, v := range in {
m := map[string]interface{}{}
if v.FieldRef != nil {
m["field_ref"] = flattenObjectFieldSelector(v.FieldRef)
}
if v.Mode != nil {
m["mode"] = *v.Mode
}
if v.Path != "" {
m["path"] = v.Path
}
if v.ResourceFieldRef != nil {
m["resource_field_ref"] = flattenResourceFieldSelector(v.ResourceFieldRef)
}
att[i] = m
}
return att
}
func flattenConfigMapVolumeSource(in *v1.ConfigMapVolumeSource) []interface{} {
att := make(map[string]interface{})
if in.DefaultMode != nil {
att["default_mode"] = *in.DefaultMode
}
att["name"] = in.Name
if len(in.Items) > 0 {
items := make([]interface{}, len(in.Items))
for i, v := range in.Items {
m := map[string]interface{}{}
m["key"] = v.Key
m["mode"] = v.Mode
m["path"] = v.Path
items[i] = m
}
att["items"] = items
}
return []interface{}{att}
}
func flattenEmptyDirVolumeSource(in *v1.EmptyDirVolumeSource) []interface{} {
att := make(map[string]interface{})
att["medium"] = in.Medium
return []interface{}{att}
}
func flattenSecretVolumeSource(in *v1.SecretVolumeSource) []interface{} {
att := make(map[string]interface{})
if in.SecretName != "" {
att["secret_name"] = in.SecretName
}
return []interface{}{att}
}
// Expanders
func expandPodSpec(p []interface{}) (v1.PodSpec, error) {
obj := v1.PodSpec{}
if len(p) == 0 || p[0] == nil {
return obj, nil
}
in := p[0].(map[string]interface{})
if v, ok := in["active_deadline_seconds"].(int); ok && v > 0 {
obj.ActiveDeadlineSeconds = ptrToInt64(int64(v))
}
if v, ok := in["container"].([]interface{}); ok && len(v) > 0 {
cs, err := expandContainers(v)
if err != nil {
return obj, err
}
obj.Containers = cs
}
if v, ok := in["dns_policy"].(string); ok {
obj.DNSPolicy = v1.DNSPolicy(v)
}
if v, ok := in["host_ipc"]; ok {
obj.HostIPC = v.(bool)
}
if v, ok := in["host_network"]; ok {
obj.HostNetwork = v.(bool)
}
if v, ok := in["host_pid"]; ok {
obj.HostPID = v.(bool)
}
if v, ok := in["hostname"]; ok {
obj.Hostname = v.(string)
}
if v, ok := in["image_pull_secrets"].([]interface{}); ok {
cs := expandLocalObjectReferenceArray(v)
obj.ImagePullSecrets = cs
}
if v, ok := in["node_name"]; ok {
obj.NodeName = v.(string)
}
if v, ok := in["node_selector"].(map[string]string); ok {
obj.NodeSelector = v
}
if v, ok := in["restart_policy"].(string); ok {
obj.RestartPolicy = v1.RestartPolicy(v)
}
if v, ok := in["security_context"].([]interface{}); ok && len(v) > 0 {
obj.SecurityContext = expandPodSecurityContext(v)
}
if v, ok := in["service_account_name"].(string); ok {
obj.ServiceAccountName = v
}
if v, ok := in["subdomain"].(string); ok {
obj.Subdomain = v
}
if v, ok := in["termination_grace_period_seconds"].(int); ok {
obj.TerminationGracePeriodSeconds = ptrToInt64(int64(v))
}
if v, ok := in["volume"].([]interface{}); ok && len(v) > 0 {
cs, err := expandVolumes(v)
if err != nil {
return obj, err
}
obj.Volumes = cs
}
return obj, nil
}
func expandPodSecurityContext(l []interface{}) *v1.PodSecurityContext {
if len(l) == 0 || l[0] == nil {
return &v1.PodSecurityContext{}
}
in := l[0].(map[string]interface{})
obj := &v1.PodSecurityContext{}
if v, ok := in["fs_group"].(int); ok {
obj.FSGroup = ptrToInt64(int64(v))
}
if v, ok := in["run_as_non_root"].(bool); ok {
obj.RunAsNonRoot = ptrToBool(v)
}
if v, ok := in["run_as_user"].(int); ok {
obj.RunAsUser = ptrToInt64(int64(v))
}
if v, ok := in["supplemental_groups"].(*schema.Set); ok {
obj.SupplementalGroups = schemaSetToInt64Array(v)
}
if v, ok := in["se_linux_options"].([]interface{}); ok && len(v) > 0 {
obj.SELinuxOptions = expandSeLinuxOptions(v)
}
return obj
}
func expandSeLinuxOptions(l []interface{}) *v1.SELinuxOptions {
if len(l) == 0 || l[0] == nil {
return &v1.SELinuxOptions{}
}
in := l[0].(map[string]interface{})
obj := &v1.SELinuxOptions{}
if v, ok := in["level"]; ok {
obj.Level = v.(string)
}
if v, ok := in["role"]; ok {
obj.Role = v.(string)
}
if v, ok := in["type"]; ok {
obj.Type = v.(string)
}
if v, ok := in["user"]; ok {
obj.User = v.(string)
}
return obj
}
func expandKeyPath(in []interface{}) []v1.KeyToPath {
if len(in) == 0 {
return []v1.KeyToPath{}
}
keyPaths := make([]v1.KeyToPath, len(in))
for i, c := range in {
p := c.(map[string]interface{})
if v, ok := p["key"].(string); ok {
keyPaths[i].Key = v
}
if v, ok := p["mode"].(int); ok {
keyPaths[i].Mode = ptrToInt32(int32(v))
}
if v, ok := p["path"].(string); ok {
keyPaths[i].Path = v
}
}
return keyPaths
}
func expandDownwardAPIVolumeFile(in []interface{}) ([]v1.DownwardAPIVolumeFile, error) {
var err error
if len(in) == 0 {
return []v1.DownwardAPIVolumeFile{}, nil
}
dapivf := make([]v1.DownwardAPIVolumeFile, len(in))
for i, c := range in {
p := c.(map[string]interface{})
if v, ok := p["mode"].(int); ok {
dapivf[i].Mode = ptrToInt32(int32(v))
}
if v, ok := p["path"].(string); ok {
dapivf[i].Path = v
}
if v, ok := p["field_ref"].([]interface{}); ok && len(v) > 0 {
dapivf[i].FieldRef, err = expandFieldRef(v)
if err != nil {
return dapivf, err
}
}
if v, ok := p["resource_field_ref"].([]interface{}); ok && len(v) > 0 {
dapivf[i].ResourceFieldRef, err = expandResourceFieldRef(v)
if err != nil {
return dapivf, err
}
}
}
return dapivf, nil
}
func expandConfigMapVolumeSource(l []interface{}) *v1.ConfigMapVolumeSource {
if len(l) == 0 || l[0] == nil {
return &v1.ConfigMapVolumeSource{}
}
in := l[0].(map[string]interface{})
obj := &v1.ConfigMapVolumeSource{
DefaultMode: ptrToInt32(int32(in["default_mode "].(int))),
}
if v, ok := in["name"].(string); ok {
obj.Name = v
}
if v, ok := in["items"].([]interface{}); ok && len(v) > 0 {
obj.Items = expandKeyPath(v)
}
return obj
}
func expandDownwardAPIVolumeSource(l []interface{}) (*v1.DownwardAPIVolumeSource, error) {
if len(l) == 0 || l[0] == nil {
return &v1.DownwardAPIVolumeSource{}, nil
}
in := l[0].(map[string]interface{})
obj := &v1.DownwardAPIVolumeSource{
DefaultMode: ptrToInt32(int32(in["default_mode "].(int))),
}
if v, ok := in["items"].([]interface{}); ok && len(v) > 0 {
var err error
obj.Items, err = expandDownwardAPIVolumeFile(v)
if err != nil {
return obj, err
}
}
return obj, nil
}
func expandGitRepoVolumeSource(l []interface{}) *v1.GitRepoVolumeSource {
if len(l) == 0 || l[0] == nil {
return &v1.GitRepoVolumeSource{}
}
in := l[0].(map[string]interface{})
obj := &v1.GitRepoVolumeSource{}
if v, ok := in["directory"].(string); ok {
obj.Directory = v
}
if v, ok := in["repository"].(string); ok {
obj.Repository = v
}
if v, ok := in["revision"].(string); ok {
obj.Revision = v
}
return obj
}
func expandEmptyDirVolumeSource(l []interface{}) *v1.EmptyDirVolumeSource {
if len(l) == 0 || l[0] == nil {
return &v1.EmptyDirVolumeSource{}
}
in := l[0].(map[string]interface{})
obj := &v1.EmptyDirVolumeSource{
Medium: v1.StorageMedium(in["medium"].(string)),
}
return obj
}
func expandPersistentVolumeClaimVolumeSource(l []interface{}) *v1.PersistentVolumeClaimVolumeSource {
if len(l) == 0 || l[0] == nil {
return &v1.PersistentVolumeClaimVolumeSource{}
}
in := l[0].(map[string]interface{})
obj := &v1.PersistentVolumeClaimVolumeSource{
ClaimName: in["claim_name"].(string),
ReadOnly: in["read_only"].(bool),
}
return obj
}
func expandSecretVolumeSource(l []interface{}) *v1.SecretVolumeSource {
if len(l) == 0 || l[0] == nil {
return &v1.SecretVolumeSource{}
}
in := l[0].(map[string]interface{})
obj := &v1.SecretVolumeSource{
SecretName: in["secret_name"].(string),
}
return obj
}
func expandVolumes(volumes []interface{}) ([]v1.Volume, error) {
if len(volumes) == 0 {
return []v1.Volume{}, nil
}
vl := make([]v1.Volume, len(volumes))
for i, c := range volumes {
m := c.(map[string]interface{})
if value, ok := m["name"]; ok {
vl[i].Name = value.(string)
}
if value, ok := m["config_map"].([]interface{}); ok && len(value) > 0 {
vl[i].ConfigMap = expandConfigMapVolumeSource(value)
}
if value, ok := m["git_repo"].([]interface{}); ok && len(value) > 0 {
vl[i].GitRepo = expandGitRepoVolumeSource(value)
}
if value, ok := m["empty_dir"].([]interface{}); ok && len(value) > 0 {
vl[i].EmptyDir = expandEmptyDirVolumeSource(value)
}
if value, ok := m["downward_api"].([]interface{}); ok && len(value) > 0 {
var err error
vl[i].DownwardAPI, err = expandDownwardAPIVolumeSource(value)
if err != nil {
return vl, err
}
}
if value, ok := m["persistent_volume_claim"].([]interface{}); ok && len(value) > 0 {
vl[i].PersistentVolumeClaim = expandPersistentVolumeClaimVolumeSource(value)
}
if value, ok := m["secret"].([]interface{}); ok && len(value) > 0 {
vl[i].Secret = expandSecretVolumeSource(value)
}
if v, ok := m["gce_persistent_disk"].([]interface{}); ok && len(v) > 0 {
vl[i].GCEPersistentDisk = expandGCEPersistentDiskVolumeSource(v)
}
if v, ok := m["aws_elastic_block_store"].([]interface{}); ok && len(v) > 0 {
vl[i].AWSElasticBlockStore = expandAWSElasticBlockStoreVolumeSource(v)
}
if v, ok := m["host_path"].([]interface{}); ok && len(v) > 0 {
vl[i].HostPath = expandHostPathVolumeSource(v)
}
if v, ok := m["glusterfs"].([]interface{}); ok && len(v) > 0 {
vl[i].Glusterfs = expandGlusterfsVolumeSource(v)
}
if v, ok := m["nfs"].([]interface{}); ok && len(v) > 0 {
vl[i].NFS = expandNFSVolumeSource(v)
}
if v, ok := m["rbd"].([]interface{}); ok && len(v) > 0 {
vl[i].RBD = expandRBDVolumeSource(v)
}
if v, ok := m["iscsi"].([]interface{}); ok && len(v) > 0 {
vl[i].ISCSI = expandISCSIVolumeSource(v)
}
if v, ok := m["cinder"].([]interface{}); ok && len(v) > 0 {
vl[i].Cinder = expandCinderVolumeSource(v)
}
if v, ok := m["ceph_fs"].([]interface{}); ok && len(v) > 0 {
vl[i].CephFS = expandCephFSVolumeSource(v)
}
if v, ok := m["fc"].([]interface{}); ok && len(v) > 0 {
vl[i].FC = expandFCVolumeSource(v)
}
if v, ok := m["flocker"].([]interface{}); ok && len(v) > 0 {
vl[i].Flocker = expandFlockerVolumeSource(v)
}
if v, ok := m["flex_volume"].([]interface{}); ok && len(v) > 0 {
vl[i].FlexVolume = expandFlexVolumeSource(v)
}
if v, ok := m["azure_file"].([]interface{}); ok && len(v) > 0 {
vl[i].AzureFile = expandAzureFileVolumeSource(v)
}
if v, ok := m["vsphere_volume"].([]interface{}); ok && len(v) > 0 {
vl[i].VsphereVolume = expandVsphereVirtualDiskVolumeSource(v)
}
if v, ok := m["quobyte"].([]interface{}); ok && len(v) > 0 {
vl[i].Quobyte = expandQuobyteVolumeSource(v)
}
if v, ok := m["azure_disk"].([]interface{}); ok && len(v) > 0 {
vl[i].AzureDisk = expandAzureDiskVolumeSource(v)
}
if v, ok := m["photon_persistent_disk"].([]interface{}); ok && len(v) > 0 {
vl[i].PhotonPersistentDisk = expandPhotonPersistentDiskVolumeSource(v)
}
}
return vl, nil
}
func patchPodSpec(pathPrefix, prefix string, d *schema.ResourceData) (PatchOperations, error) {
ops := make([]PatchOperation, 0)
if d.HasChange(prefix + "active_deadline_seconds") {
v := d.Get(prefix + "active_deadline_seconds").(int)
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/activeDeadlineSeconds",
Value: v,
})
}
if d.HasChange(prefix + "container") {
containers := d.Get(prefix + "container").([]interface{})
value, _ := expandContainers(containers)
for i, v := range value {
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/containers/" + strconv.Itoa(i) + "/image",
Value: v.Image,
})
ops = append(ops, &ReplaceOperation{
Path: pathPrefix + "/containers/" + strconv.Itoa(i) + "/name",
Value: v.Name,
})
}
}
return ops, nil
}

View File

@ -2,8 +2,11 @@ package kubernetes
import (
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"k8s.io/apimachinery/pkg/api/resource"
apiValidation "k8s.io/apimachinery/pkg/api/validation"
utilValidation "k8s.io/apimachinery/pkg/util/validation"
@ -60,6 +63,42 @@ func validateLabels(value interface{}, key string) (ws []string, es []error) {
return
}
func validatePortNum(value interface{}, key string) (ws []string, es []error) {
errors := utilValidation.IsValidPortNum(value.(int))
if len(errors) > 0 {
for _, err := range errors {
es = append(es, fmt.Errorf("%s %s", key, err))
}
}
return
}
func validatePortName(value interface{}, key string) (ws []string, es []error) {
errors := utilValidation.IsValidPortName(value.(string))
if len(errors) > 0 {
for _, err := range errors {
es = append(es, fmt.Errorf("%s %s", key, err))
}
}
return
}
func validatePortNumOrName(value interface{}, key string) (ws []string, es []error) {
switch value.(type) {
case string:
intVal, err := strconv.Atoi(value.(string))
if err != nil {
return validatePortName(value, key)
}
return validatePortNum(intVal, key)
case int:
return validatePortNum(value, key)
default:
es = append(es, fmt.Errorf("%s must be defined of type string or int on the schema", key))
return
}
}
func validateResourceList(value interface{}, key string) (ws []string, es []error) {
m := value.(map[string]interface{})
for k, value := range m {
@ -80,3 +119,80 @@ func validateResourceList(value interface{}, key string) (ws []string, es []erro
}
return
}
func validateResourceQuantity(value interface{}, key string) (ws []string, es []error) {
if v, ok := value.(string); ok {
_, err := resource.ParseQuantity(v)
if err != nil {
es = append(es, fmt.Errorf("%s.%s : %s", key, v, err))
}
}
return
}
func validatePositiveInteger(value interface{}, key string) (ws []string, es []error) {
v := value.(int)
if v <= 0 {
es = append(es, fmt.Errorf("%s must be greater than 0", key))
}
return
}
func validateDNSPolicy(value interface{}, key string) (ws []string, es []error) {
v := value.(string)
if v != "ClusterFirst" && v != "Default" {
es = append(es, fmt.Errorf("%s must be either ClusterFirst or Default", key))
}
return
}
func validateRestartPolicy(value interface{}, key string) (ws []string, es []error) {
v := value.(string)
switch v {
case "Always", "OnFailure", "Never":
return
default:
es = append(es, fmt.Errorf("%s must be one of Always, OnFailure or Never ", key))
}
return
}
func validateTerminationGracePeriodSeconds(value interface{}, key string) (ws []string, es []error) {
v := value.(int)
if v < 0 {
es = append(es, fmt.Errorf("%s must be greater than or equal to 0", key))
}
return
}
func validateAttributeValueDoesNotContain(searchString string) schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
input := v.(string)
if !strings.Contains(input, searchString) {
errors = append(errors, fmt.Errorf(
"%q must not contain %q",
k, searchString))
}
return
}
}
func validateAttributeValueIsIn(validValues []string) schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
input := v.(string)
isValid := false
for _, s := range validValues {
if s == input {
isValid = true
break
}
}
if !isValid {
errors = append(errors, fmt.Errorf(
"%q must contain a value from %#v, got %q",
k, validValues, input))
}
return
}
}

View File

@ -0,0 +1,539 @@
---
layout: "kubernetes"
page_title: "Kubernetes: kubernetes_pod"
sidebar_current: "docs-kubernetes-resource-pod"
description: |-
A pod is a group of one or more containers, the shared storage for those containers, and options about how to run the containers. Pods are always co-located and co-scheduled, and run in a shared context.
---
# kubernetes_pod
A pod is a group of one or more containers, the shared storage for those containers, and options about how to run the containers. Pods are always co-located and co-scheduled, and run in a shared context.
Read more at https://kubernetes.io/docs/concepts/workloads/pods/pod/
## Example Usage
```hcl
resource "kubernetes_pod" "test" {
metadata {
name = "terraform-example"
}
spec {
container {
image = "nginx:1.7.9"
name = "example"
}
}
}
```
## Argument Reference
The following arguments are supported:
* `metadata` - (Required) Standard pod's metadata. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#metadata
* `spec` - (Required) Spec of the pod owned by the cluster
## Nested Blocks
### `metadata`
#### Arguments
* `annotations` - (Optional) An unstructured key value map stored with the pod 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 pod. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels
* `name` - (Optional) Name of the pod, 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 pod 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 pod that can be used by clients to determine when pod 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 pod.
* `uid` - The unique in time and space value for this pod. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
### `spec`
#### Arguments
* `active_deadline_seconds` - (Optional) Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.
* `container` - (Optional) List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers
* `dns_policy` - (Optional) Set DNS policy for containers within the pod. One of 'ClusterFirst' or 'Default'. Defaults to 'ClusterFirst'.
* `host_ipc` - (Optional) Use the host's ipc namespace. Optional: Default to false.
* `host_network` - (Optional) Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified.
* `host_pid` - (Optional) Use the host's pid namespace.
* `hostname` - (Optional) Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.
* `image_pull_secrets` - (Optional) ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: http://kubernetes.io/docs/user-guide/images#specifying-imagepullsecrets-on-a-pod
* `node_name` - (Optional) NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.
* `node_selector` - (Optional) NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: http://kubernetes.io/docs/user-guide/node-selection.
* `restart_policy` - (Optional) Restart policy for all containers within the pod. One of Always, OnFailure, Never. More info: http://kubernetes.io/docs/user-guide/pod-states#restartpolicy.
* `security_context` - (Optional) SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty
* `service_account_name` - (Optional) ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md.
* `subdomain` - (Optional) If specified, the fully qualified Pod hostname will be "...svc.". If not specified, the pod will not have a domainname at all..
* `termination_grace_period_seconds` - (Optional) Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process.
* `volume` - (Optional) List of volumes that can be mounted by containers belonging to the pod. More info: http://kubernetes.io/docs/user-guide/volumes
### `container`
#### Arguments
* `args` - (Optional) Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands
* `command` - (Optional) Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands
* `env` - (Optional) List of environment variables to set in the container. Cannot be updated.
* `image` - (Optional) Docker image name. More info: http://kubernetes.io/docs/user-guide/images
* `image_pull_policy` - (Optional) Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/images#updating-images
* `lifecycle` - (Optional) Actions that the management system should take in response to container lifecycle events
* `liveness_probe` - (Optional) Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes
* `name` - (Required) Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.
* `port` - (Optional) List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Cannot be updated.
* `readiness_probe` - (Optional) Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes
* `resources` - (Optional) Compute Resources required by this container. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources
* `security_context` - (Optional) Security options the pod should run with. More info: http://releases.k8s.io/HEAD/docs/design/security_context.md
* `stdin` - (Optional) Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF.
* `stdin_once` - (Optional) Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF.
* `termination_message_path` - (Optional) Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Defaults to /dev/termination-log. Cannot be updated.
* `tty` - (Optional) Whether this container should allocate a TTY for itself
* `volume_mount` - (Optional) Pod volumes to mount into the container's filesystem. Cannot be updated.
* `working_dir` - (Optional) Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.
### `aws_elastic_block_store`
#### Arguments
* `fs_type` - (Optional) Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore
* `partition` - (Optional) The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty).
* `read_only` - (Optional) Whether to set the read-only property in VolumeMounts to "true". If omitted, the default is "false". More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore
* `volume_id` - (Required) Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore
### `azure_disk`
#### Arguments
* `caching_mode` - (Required) Host Caching mode: None, Read Only, Read Write.
* `data_disk_uri` - (Required) The URI the data disk in the blob storage
* `disk_name` - (Required) The Name of the data disk in the blob storage
* `fs_type` - (Optional) Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).
### `azure_file`
#### Arguments
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).
* `secret_name` - (Required) The name of secret that contains Azure Storage Account Name and Key
* `share_name` - (Required) Share Name
### `capabilities`
#### Arguments
* `add` - (Optional) Added capabilities
* `drop` - (Optional) Removed capabilities
### `ceph_fs`
#### Arguments
* `monitors` - (Required) Monitors is a collection of Ceph monitors More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it
* `path` - (Optional) Used as the mounted root, rather than the full Ceph tree, default is /
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to `false` (read/write). More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it
* `secret_file` - (Optional) The path to key ring for User, default is /etc/ceph/user.secret More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it
* `secret_ref` - (Optional) Reference to the authentication secret for User, default is empty. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it
* `user` - (Optional) User is the rados user name, default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it
### `cinder`
#### Arguments
* `fs_type` - (Optional) Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write). More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md
* `volume_id` - (Required) Volume ID used to identify the volume in Cinder. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md
### `config_map`
#### Arguments
* `default_mode` - (Optional) Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
* `items` - (Optional) If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.
* `name` - (Optional) Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names
### `config_map_key_ref`
#### Arguments
* `key` - (Optional) The key to select.
* `name` - (Optional) Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names
### `downward_api`
#### Arguments
* `default_mode` - (Optional) Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
* `items` - (Optional) If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.
### `empty_dir`
#### Arguments
* `medium` - (Optional) What type of storage medium should back this directory. The default is "" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir
### `env`
#### Arguments
* `name` - (Required) Name of the environment variable. Must be a C_IDENTIFIER
* `value` - (Optional) Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to "".
* `value_from` - (Optional) Source for the environment variable's value
### `exec`
#### Arguments
* `command` - (Optional) Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
### `fc`
#### Arguments
* `fs_type` - (Optional) Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
* `lun` - (Required) FC target lun number
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to false (read/write).
* `target_ww_ns` - (Required) FC target worldwide names (WWNs)
### `field_ref`
#### Arguments
* `api_version` - (Optional) Version of the schema the FieldPath is written in terms of, defaults to "v1".
* `field_path` - (Optional) Path of the field to select in the specified API version
### `flex_volume`
#### Arguments
* `driver` - (Required) Driver is the name of the driver to use for this volume.
* `fs_type` - (Optional) Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". The default filesystem depends on FlexVolume script.
* `options` - (Optional) Extra command options if any.
* `read_only` - (Optional) Whether to force the ReadOnly setting in VolumeMounts. Defaults to false (read/write).
* `secret_ref` - (Optional) Reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.
### `flocker`
#### Arguments
* `dataset_name` - (Optional) Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated
* `dataset_uuid` - (Optional) UUID of the dataset. This is unique identifier of a Flocker dataset
### `gce_persistent_disk`
#### Arguments
* `fs_type` - (Optional) Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk
* `partition` - (Optional) The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty). More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk
* `pd_name` - (Required) Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk
* `read_only` - (Optional) Whether to force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk
### `git_repo`
#### Arguments
* `directory` - (Optional) Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.
* `repository` - (Optional) Repository URL
* `revision` - (Optional) Commit hash for the specified revision.
### `glusterfs`
#### Arguments
* `endpoints_name` - (Required) The endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
* `path` - (Required) The Glusterfs volume path. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
* `read_only` - (Optional) Whether to force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
### `host_path`
#### Arguments
* `path` - (Optional) Path of the directory on the host. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath
### `http_get`
#### Arguments
* `host` - (Optional) Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.
* `http_header` - (Optional) Scheme to use for connecting to the host.
* `path` - (Optional) Path to access on the HTTP server.
* `port` - (Optional) Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
* `scheme` - (Optional) Scheme to use for connecting to the host.
### `http_header`
#### Arguments
* `name` - (Optional) The header field name
* `value` - (Optional) The header field value
### `image_pull_secrets`
#### Arguments
* `name` - (Required) Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names
### `iscsi`
#### Arguments
* `fs_type` - (Optional) Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#iscsi
* `iqn` - (Required) Target iSCSI Qualified Name.
* `iscsi_interface` - (Optional) iSCSI interface name that uses an iSCSI transport. Defaults to 'default' (tcp).
* `lun` - (Optional) iSCSI target lun number.
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to false.
* `target_portal` - (Required) iSCSI target portal. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).
### `items`
#### Arguments
* `key` - (Optional) The key to project.
* `mode` - (Optional) Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
* `path` - (Optional) The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.
### `lifecycle`
#### Arguments
* `post_start` - (Optional) post_start is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: http://kubernetes.io/docs/user-guide/container-environment#hook-details
* `pre_stop` - (Optional) pre_stop is called immediately before a container is terminated. The container is terminated after the handler completes. The reason for termination is passed to the handler. Regardless of the outcome of the handler, the container is eventually terminated. Other management of the container blocks until the hook completes. More info: http://kubernetes.io/docs/user-guide/container-environment#hook-details
### `limits`
#### Arguments
* `cpu` - (Optional) CPU
* `memory` - (Optional) Memory
### `liveness_probe`
#### Arguments
* `exec` - (Optional) exec specifies the action to take.
* `failure_threshold` - (Optional) Minimum consecutive failures for the probe to be considered failed after having succeeded.
* `http_get` - (Optional) Specifies the http request to perform.
* `initial_delay_seconds` - (Optional) Number of seconds after the container has started before liveness probes are initiated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes
* `period_seconds` - (Optional) How often (in seconds) to perform the probe
* `success_threshold` - (Optional) Minimum consecutive successes for the probe to be considered successful after having failed.
* `tcp_socket` - (Optional) TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
* `timeout_seconds` - (Optional) Number of seconds after which the probe times out. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes
### `nfs`
#### Arguments
* `path` - (Required) Path that is exported by the NFS server. More info: http://kubernetes.io/docs/user-guide/volumes#nfs
* `read_only` - (Optional) Whether to force the NFS export to be mounted with read-only permissions. Defaults to false. More info: http://kubernetes.io/docs/user-guide/volumes#nfs
* `server` - (Required) Server is the hostname or IP address of the NFS server. More info: http://kubernetes.io/docs/user-guide/volumes#nfs
### `persistent_volume_claim`
#### Arguments
* `claim_name` - (Optional) ClaimName is the name of a PersistentVolumeClaim in the same
* `read_only` - (Optional) Will force the ReadOnly setting in VolumeMounts.
### `photon_persistent_disk`
#### Arguments
* `fs_type` - (Optional) Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
* `pd_id` - (Required) ID that identifies Photon Controller persistent disk
### `port`
#### Arguments
* `container_port` - (Required) Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.
* `host_ip` - (Optional) What host IP to bind the external port to.
* `host_port` - (Optional) Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.
* `name` - (Optional) If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services
* `protocol` - (Optional) Protocol for port. Must be UDP or TCP. Defaults to "TCP".
### `post_start`
#### Arguments
* `exec` - (Optional) exec specifies the action to take.
* `http_get` - (Optional) Specifies the http request to perform.
* `tcp_socket` - (Optional) TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
### `pre_stop`
#### Arguments
* `exec` - (Optional) exec specifies the action to take.
* `http_get` - (Optional) Specifies the http request to perform.
* `tcp_socket` - (Optional) TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
### `quobyte`
#### Arguments
* `group` - (Optional) Group to map volume access to Default is no group
* `read_only` - (Optional) Whether to force the Quobyte volume to be mounted with read-only permissions. Defaults to false.
* `registry` - (Required) Registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes
* `user` - (Optional) User to map volume access to Defaults to serivceaccount user
* `volume` - (Required) Volume is a string that references an already created Quobyte volume by name.
### `rbd`
#### Arguments
* `ceph_monitors` - (Required) A collection of Ceph monitors. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it
* `fs_type` - (Optional) Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: http://kubernetes.io/docs/user-guide/volumes#rbd
* `keyring` - (Optional) Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it
* `rados_user` - (Optional) The rados user name. Default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it
* `rbd_image` - (Required) The rados image name. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it
* `rbd_pool` - (Optional) The rados pool name. Default is rbd. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it.
* `read_only` - (Optional) Whether to force the read-only setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it
* `secret_ref` - (Optional) Name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it
### `readiness_probe`
#### Arguments
* `exec` - (Optional) exec specifies the action to take.
* `failure_threshold` - (Optional) Minimum consecutive failures for the probe to be considered failed after having succeeded.
* `http_get` - (Optional) Specifies the http request to perform.
* `initial_delay_seconds` - (Optional) Number of seconds after the container has started before liveness probes are initiated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes
* `period_seconds` - (Optional) How often (in seconds) to perform the probe
* `success_threshold` - (Optional) Minimum consecutive successes for the probe to be considered successful after having failed.
* `tcp_socket` - (Optional) TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
* `timeout_seconds` - (Optional) Number of seconds after which the probe times out. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes
### `resources`
#### Arguments
* `limits` - (Optional) Describes the maximum amount of compute resources allowed. More info: http://kubernetes.io/docs/user-guide/compute-resources/
* `requests` - (Optional) Describes the minimum amount of compute resources required.
### `requests`
#### Arguments
* `cpu` - (Optional) CPU
* `memory` - (Optional) Memory
### `resource_field_ref`
#### Arguments
* `container_name` - (Optional) The name of the container
* `resource` - (Required) Resource to select
### `se_linux_options`
#### Arguments
* `level` - (Optional) Level is SELinux level label that applies to the container.
* `role` - (Optional) Role is a SELinux role label that applies to the container.
* `type` - (Optional) Type is a SELinux type label that applies to the container.
* `user` - (Optional) User is a SELinux user label that applies to the container.
### `secret`
#### Arguments
* `secret_name` - (Optional) Name of the secret in the pod's namespace to use. More info: http://kubernetes.io/docs/user-guide/volumes#secrets
### `secret_key_ref`
#### Arguments
* `key` - (Optional) The key of the secret to select from. Must be a valid secret key.
* `name` - (Optional) Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names
### `secret_ref`
#### Arguments
* `name` - (Optional) Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names
### `security_context`
#### Arguments
* `fs_group` - (Optional) A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod: 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw---- If unset, the Kubelet will not modify the ownership and permissions of any volume.
* `run_as_non_root` - (Optional) Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does.
* `run_as_user` - (Optional) The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified
* `se_linux_options` - (Optional) The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
* `supplemental_groups` - (Optional) A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.
### `tcp_socket`
#### Arguments
* `port` - (Required) Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
### `value_from`
#### Arguments
* `config_map_key_ref` - (Optional) Selects a key of a ConfigMap.
* `field_ref` - (Optional) Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP..
* `resource_field_ref` - (Optional) Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP..
* `secret_key_ref` - (Optional) Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.podIP..
### `volume`
#### Arguments
* `aws_elastic_block_store` - (Optional) Represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://kubernetes.io/docs/user-guide/volumes#awselasticblockstore
* `azure_disk` - (Optional) Represents an Azure Data Disk mount on the host and bind mount to the pod.
* `azure_file` - (Optional) Represents an Azure File Service mount on the host and bind mount to the pod.
* `ceph_fs` - (Optional) Represents a Ceph FS mount on the host that shares a pod's lifetime
* `cinder` - (Optional) Represents a cinder volume attached and mounted on kubelets host machine. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md
* `config_map` - (Optional) ConfigMap represents a configMap that should populate this volume
* `downward_api` - (Optional) DownwardAPI represents downward API about the pod that should populate this volume
* `empty_dir` - (Optional) EmptyDir represents a temporary directory that shares a pod's lifetime. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir
* `fc` - (Optional) Represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.
* `flex_volume` - (Optional) Represents a generic volume resource that is provisioned/attached using an exec based plugin. This is an alpha feature and may change in future.
* `flocker` - (Optional) Represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running
* `gce_persistent_disk` - (Optional) Represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: http://kubernetes.io/docs/user-guide/volumes#gcepersistentdisk
* `git_repo` - (Optional) GitRepo represents a git repository at a particular revision.
* `glusterfs` - (Optional) Represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md
* `host_path` - (Optional) Represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: http://kubernetes.io/docs/user-guide/volumes#hostpath
* `iscsi` - (Optional) Represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.
* `name` - (Optional) Volume's name. Must be a DNS_LABEL and unique within the pod. More info: http://kubernetes.io/docs/user-guide/identifiers#names
* `nfs` - (Optional) Represents an NFS mount on the host. Provisioned by an admin. More info: http://kubernetes.io/docs/user-guide/volumes#nfs
* `persistent_volume_claim` - (Optional) The specification of a persistent volume.
* `photon_persistent_disk` - (Optional) Represents a PhotonController persistent disk attached and mounted on kubelets host machine
* `quobyte` - (Optional) Quobyte represents a Quobyte mount on the host that shares a pod's lifetime
* `rbd` - (Optional) Represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md
* `secret` - (Optional) Secret represents a secret that should populate this volume. More info: http://kubernetes.io/docs/user-guide/volumes#secrets
* `vsphere_volume` - (Optional) Represents a vSphere volume attached and mounted on kubelets host machine
### `volume_mount`
#### Arguments
* `mount_path` - (Required) Path within the container at which the volume should be mounted. Must not contain ':'.
* `name` - (Required) This must match the Name of a Volume.
* `read_only` - (Optional) Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.
* `sub_path` - (Optional) Path within the volume from which the container's volume should be mounted. Defaults to "" (volume's root).
### `vsphere_volume`
#### Arguments
* `fs_type` - (Optional) Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
* `volume_path` - (Required) Path that identifies vSphere volume vmdk
## Import
Pod can be imported using the namespace and name, e.g.
```
$ terraform import kubernetes_pod.example default/terraform-example
```

View File

@ -31,6 +31,9 @@
<li<%= sidebar_current("docs-kubernetes-resource-persistent-volume-claim") %>>
<a href="/docs/providers/kubernetes/r/persistent_volume_claim.html">kubernetes_persistent_volume_claim</a>
</li>
<li<%= sidebar_current("docs-kubernetes-resource-pod") %>>
<a href="/docs/providers/kubernetes/r/pod.html">kubernetes_pod</a>
</li>
<li<%= sidebar_current("docs-kubernetes-resource-resource-quota") %>>
<a href="/docs/providers/kubernetes/r/resource_quota.html">kubernetes_resource_quota</a>
</li>