github.com/nathanielks/terraform@v0.6.1-0.20170509030759-13e1a62319dc/builtin/providers/kubernetes/provider.go (about)

     1  package kubernetes
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/terraform"
    11  	"github.com/mitchellh/go-homedir"
    12  	kubernetes "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5"
    13  	"k8s.io/kubernetes/pkg/client/restclient"
    14  	"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
    15  	clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
    16  )
    17  
    18  func Provider() terraform.ResourceProvider {
    19  	return &schema.Provider{
    20  		Schema: map[string]*schema.Schema{
    21  			"host": {
    22  				Type:        schema.TypeString,
    23  				Optional:    true,
    24  				DefaultFunc: schema.EnvDefaultFunc("KUBE_HOST", ""),
    25  				Description: "The hostname (in form of URI) of Kubernetes master.",
    26  			},
    27  			"username": {
    28  				Type:        schema.TypeString,
    29  				Optional:    true,
    30  				DefaultFunc: schema.EnvDefaultFunc("KUBE_USER", ""),
    31  				Description: "The username to use for HTTP basic authentication when accessing the Kubernetes master endpoint.",
    32  			},
    33  			"password": {
    34  				Type:        schema.TypeString,
    35  				Optional:    true,
    36  				DefaultFunc: schema.EnvDefaultFunc("KUBE_PASSWORD", ""),
    37  				Description: "The password to use for HTTP basic authentication when accessing the Kubernetes master endpoint.",
    38  			},
    39  			"insecure": {
    40  				Type:        schema.TypeBool,
    41  				Optional:    true,
    42  				DefaultFunc: schema.EnvDefaultFunc("KUBE_INSECURE", false),
    43  				Description: "Whether server should be accessed without verifying the TLS certificate.",
    44  			},
    45  			"client_certificate": {
    46  				Type:        schema.TypeString,
    47  				Optional:    true,
    48  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CLIENT_CERT_DATA", ""),
    49  				Description: "PEM-encoded client certificate for TLS authentication.",
    50  			},
    51  			"client_key": {
    52  				Type:        schema.TypeString,
    53  				Optional:    true,
    54  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CLIENT_KEY_DATA", ""),
    55  				Description: "PEM-encoded client certificate key for TLS authentication.",
    56  			},
    57  			"cluster_ca_certificate": {
    58  				Type:        schema.TypeString,
    59  				Optional:    true,
    60  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CLUSTER_CA_CERT_DATA", ""),
    61  				Description: "PEM-encoded root certificates bundle for TLS authentication.",
    62  			},
    63  			"config_path": {
    64  				Type:        schema.TypeString,
    65  				Optional:    true,
    66  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CONFIG", "~/.kube/config"),
    67  				Description: "Path to the kube config file, defaults to ~/.kube/config",
    68  			},
    69  			"config_context": {
    70  				Type:        schema.TypeString,
    71  				Optional:    true,
    72  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX", ""),
    73  			},
    74  			"config_context_auth_info": {
    75  				Type:        schema.TypeString,
    76  				Optional:    true,
    77  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX_AUTH_INFO", ""),
    78  				Description: "",
    79  			},
    80  			"config_context_cluster": {
    81  				Type:        schema.TypeString,
    82  				Optional:    true,
    83  				DefaultFunc: schema.EnvDefaultFunc("KUBE_CTX_CLUSTER", ""),
    84  				Description: "",
    85  			},
    86  		},
    87  
    88  		ResourcesMap: map[string]*schema.Resource{
    89  			"kubernetes_config_map":              resourceKubernetesConfigMap(),
    90  			"kubernetes_limit_range":             resourceKubernetesLimitRange(),
    91  			"kubernetes_namespace":               resourceKubernetesNamespace(),
    92  			"kubernetes_persistent_volume":       resourceKubernetesPersistentVolume(),
    93  			"kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(),
    94  			"kubernetes_resource_quota":          resourceKubernetesResourceQuota(),
    95  			"kubernetes_secret":                  resourceKubernetesSecret(),
    96  		},
    97  		ConfigureFunc: providerConfigure,
    98  	}
    99  }
   100  
   101  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
   102  	// Config file loading
   103  	cfg, err := tryLoadingConfigFile(d)
   104  	if err != nil {
   105  		return nil, err
   106  	}
   107  	if cfg == nil {
   108  		cfg = &restclient.Config{}
   109  	}
   110  
   111  	// Overriding with static configuration
   112  	cfg.UserAgent = fmt.Sprintf("HashiCorp/1.0 Terraform/%s", terraform.VersionString())
   113  
   114  	if v, ok := d.GetOk("host"); ok {
   115  		cfg.Host = v.(string)
   116  	}
   117  	if v, ok := d.GetOk("username"); ok {
   118  		cfg.Username = v.(string)
   119  	}
   120  	if v, ok := d.GetOk("password"); ok {
   121  		cfg.Password = v.(string)
   122  	}
   123  	if v, ok := d.GetOk("insecure"); ok {
   124  		cfg.Insecure = v.(bool)
   125  	}
   126  	if v, ok := d.GetOk("cluster_ca_certificate"); ok {
   127  		cfg.CAData = bytes.NewBufferString(v.(string)).Bytes()
   128  	}
   129  	if v, ok := d.GetOk("client_certificate"); ok {
   130  		cfg.CertData = bytes.NewBufferString(v.(string)).Bytes()
   131  	}
   132  	if v, ok := d.GetOk("client_key"); ok {
   133  		cfg.KeyData = bytes.NewBufferString(v.(string)).Bytes()
   134  	}
   135  
   136  	k, err := kubernetes.NewForConfig(cfg)
   137  	if err != nil {
   138  		return nil, fmt.Errorf("Failed to configure: %s", err)
   139  	}
   140  
   141  	return k, nil
   142  }
   143  
   144  func tryLoadingConfigFile(d *schema.ResourceData) (*restclient.Config, error) {
   145  	path, err := homedir.Expand(d.Get("config_path").(string))
   146  	if err != nil {
   147  		return nil, err
   148  	}
   149  
   150  	loader := &clientcmd.ClientConfigLoadingRules{
   151  		ExplicitPath: path,
   152  	}
   153  
   154  	overrides := &clientcmd.ConfigOverrides{}
   155  	ctxSuffix := "; default context"
   156  
   157  	ctx, ctxOk := d.GetOk("config_context")
   158  	authInfo, authInfoOk := d.GetOk("config_context_auth_info")
   159  	cluster, clusterOk := d.GetOk("config_context_cluster")
   160  	if ctxOk || authInfoOk || clusterOk {
   161  		ctxSuffix = "; overriden context"
   162  		if ctxOk {
   163  			overrides.CurrentContext = ctx.(string)
   164  			ctxSuffix += fmt.Sprintf("; config ctx: %s", overrides.CurrentContext)
   165  			log.Printf("[DEBUG] Using custom current context: %q", overrides.CurrentContext)
   166  		}
   167  
   168  		overrides.Context = clientcmdapi.Context{}
   169  		if authInfoOk {
   170  			overrides.Context.AuthInfo = authInfo.(string)
   171  			ctxSuffix += fmt.Sprintf("; auth_info: %s", overrides.Context.AuthInfo)
   172  		}
   173  		if clusterOk {
   174  			overrides.Context.Cluster = cluster.(string)
   175  			ctxSuffix += fmt.Sprintf("; cluster: %s", overrides.Context.Cluster)
   176  		}
   177  		log.Printf("[DEBUG] Using overidden context: %#v", overrides.Context)
   178  	}
   179  
   180  	cc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides)
   181  	cfg, err := cc.ClientConfig()
   182  	if err != nil {
   183  		if pathErr, ok := err.(*os.PathError); ok && os.IsNotExist(pathErr.Err) {
   184  			log.Printf("[INFO] Unable to load config file as it doesn't exist at %q", path)
   185  			return nil, nil
   186  		}
   187  		return nil, fmt.Errorf("Failed to load config (%s%s): %s", path, ctxSuffix, err)
   188  	}
   189  
   190  	log.Printf("[INFO] Successfully loaded config file (%s%s)", path, ctxSuffix)
   191  	return cfg, nil
   192  }