//DeployTemplate creates and deploys a service to the pool and returns the tenant id of the newly deployed service
777005
func (f *Facade) DeployTemplate(ctx datastore.Context, poolID string, templateID string, deploymentID string) ([]string, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.DeployTemplate"))
	alog := f.auditLogger.Message(ctx, "Deploying Service Template").
		Action(audit.Deploy).ID(templateID).Type(servicetemplate.GetType()).
		WithFields(logrus.Fields{"poolid": poolID, "deploymentid": deploymentID})
	logger := plog.WithFields(logrus.Fields{
		"poolid":       poolID,
		"templateid":   templateID,
		"deploymentid": deploymentID,
	})
	// add an entry for reporting status
	deployment, err := f.deployments.NewPendingDeployment(deploymentID, templateID, poolID)
	if err != nil {
		return nil, alog.Error(err)
	}
	defer f.deployments.DeletePendingDeployment(deploymentID)

	deployment.UpdateStatus("deploy_loading_template|" + templateID)
	template, err := f.templateStore.Get(ctx, templateID)
	if err != nil {
		logger.WithError(err).Error("Unable to load template")
		return nil, alog.Error(err)
	}

	//check that deployment id does not already exist
	logger = logger.WithField("template", template.Name)
	if svcs, err := f.serviceStore.GetServicesByDeployment(ctx, deploymentID); err != nil {
		logger.WithError(err).Error("Unable to validate deploymentID while deploying")
		return nil, alog.Error(err)
	} else if len(svcs) > 0 {
		return nil, alog.Error(fmt.Errorf("deployment ID %s is already in use", deploymentID))
	}

	//now that we know the template name, set it in the status
	deployment.SetTemplateName(template.Name)

	deployment.UpdateStatus("deploy_loading_resource_pool|" + poolID)
	pool, err := f.GetResourcePool(ctx, poolID)
	if err != nil {
		logger.WithError(err).Error("Unable to load resource pool")
		return nil, alog.Error(err)
	}
	if pool == nil {
		return nil, alog.Error(fmt.Errorf("poolid %s not found", poolID))
	}

	var statusUpdater = func(status string) {
		deployment.UpdateStatus(status)
	}

	tenantIDs := make([]string, len(template.Services))
	for i, sd := range template.Services {
		logger.WithField("servicename", sd.Name).Info("Deploying service")
		tenantID, err := f.deployService(ctx, "", "", deploymentID, poolID, false, sd, statusUpdater)
		if err != nil {
			logger.WithError(err).Error("Could not deploy application")
			return nil, alog.Error(err)
		}
		if err := f.dfs.Create(tenantID); err != nil {
			logger.WithError(err).WithField("tenantid", tenantID).Error("Could not initialize volume for tenant")
			return nil, alog.Error(err)
		}
		tenantIDs[i] = tenantID
	}

	// Update the logstash filters for the deployed services
	if err := f.ReloadLogstashConfig(ctx); err != nil {
		logger.WithError(err).Error("Could not reload logstash configs after deploying")
	}

	alog.Succeeded()
	return tenantIDs, nil
}
105149
func (loader *MapLoader) LoadTemplate(name string) (string, error) {
	if src, ok := (*loader)[name]; ok {
		return src, nil
	}
	return "", Errorf("Could not find template " + name)
}
1336180
func GenerateTemplate(filename, templateSource string, args map[string]interface{}) (err error) {
	tmpl := template.Must(template.New("").Parse(templateSource))

	var b bytes.Buffer
	if err = tmpl.Execute(&b, args); err != nil {
		return NewBuildIfError(err, "ExecuteTemplate: Execute failed")
	}
	sourceCode := b.String()
	filePath := filepath.Dir(filename)
	if !DirExists(filePath) {
		err = os.MkdirAll(filePath, 0777)
		if err != nil && !os.IsExist(err) {
			return NewBuildIfError(err, "Failed to make directory", "dir", filePath)
		}
	}

	// Create the file
	file, err := os.Create(filename)
	if err != nil {
		Logger.Fatal("Failed to create file", "error", err)
		return
	}
	defer func() {
		_ = file.Close()
	}()

	if _, err = file.WriteString(sourceCode); err != nil {
		Logger.Fatal("Failed to write to file: ", "error", err)
	}

	return
}
441428
func (s *TemplateService) RegisterTemplate(p *RegisterTemplateParams) (*RegisterTemplateResponse, error) {
	resp, err := s.cs.newRequest("registerTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r RegisterTemplateResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
641120
func (s *TemplatesService) CreateTemplate(accountID string, templateAttributes Template) (*templateResponse, error) {
	path := versioned(templatePath(accountID, ""))
	templateResponse := &templateResponse{}

	resp, err := s.client.post(path, templateAttributes, templateResponse)
	if err != nil {
		return nil, err
	}

	templateResponse.HttpResponse = resp
	return templateResponse, nil
}
963625
func (c *AppConfig) buildTemplates(components app.ComponentReferences, parameters app.Environment, environment app.Environment, buildEnvironment app.Environment, templateProcessor templateclientv1.TemplateProcessorInterface) (string, []runtime.Object, error) {
	objects := []runtime.Object{}
	name := ""
	for _, ref := range components {
		tpl := ref.Input().ResolvedMatch.Template

		klog.V(4).Infof("processing template %s/%s", c.OriginNamespace, tpl.Name)
		if len(c.ContextDir) > 0 {
			return "", nil, fmt.Errorf("--context-dir is not supported when using a template")
		}
		result, err := TransformTemplate(tpl, templateProcessor, c.OriginNamespace, parameters, c.IgnoreUnknownParameters)
		if err != nil {
			return name, nil, err
		}
		if len(name) == 0 {
			name = tpl.Name
		}
		resultObjects, err := templateObjectsToAppObjects(result.Objects)
		if err != nil {
			return "", nil, err
		}

		objects = append(objects, resultObjects...)
		if len(resultObjects) > 0 {
			// if environment variables were passed in, let's apply the environment variables
			// to every pod template object
			for _, obj := range resultObjects {
				if bc, ok := obj.(*buildv1.BuildConfig); ok {
					buildEnv := getBuildConfigEnv(bc)
					buildEnv = app.JoinEnvironment(buildEnv, buildEnvironment.List())
					setBuildConfigEnv(bc, buildEnv)
				}
				podSpec, _, err := ometa.GetPodSpecV1(obj)
				if err == nil {
					for ii := range podSpec.Containers {
						if podSpec.Containers[ii].Env != nil {
							podSpec.Containers[ii].Env = app.JoinEnvironment(environment.List(), podSpec.Containers[ii].Env)
						} else {
							podSpec.Containers[ii].Env = environment.List()
						}
					}
				}
			}
		}

		DescribeGeneratedTemplate(c.Out, ref.Input().String(), result, c.OriginNamespace)
	}
	return name, objects, nil
}
904353
func (client *Client) DeleteTemplate(ctx context.Context, templateID string) error {
	return client.request(ctx, "DELETE", "templates/"+templateID, nil, nil)
}
248732
func (s *SendTemplatedEmailInput) SetTemplate(v string) *SendTemplatedEmailInput {
	s.Template = &v
	return s
}
898277
func NewTemplate() *Template {
	return &Template{
		AWSTemplateFormatVersion: "2010-09-09",
		Description:              "",
		Metadata:                 map[string]interface{}{},
		Parameters:               map[string]interface{}{},
		Mappings:                 map[string]interface{}{},
		Conditions:               map[string]interface{}{},
		Resources:                Resources{},
		Outputs:                  map[string]interface{}{},
	}
}
16232
func ImageFromTemplate(t *template.Template) ImageBuilder {
	return ImageBuilderFunc(func(ctx context.Context, _ io.Writer, event events.Deployment) (image.Image, error) {
		buf := new(bytes.Buffer)
		if err := t.Execute(buf, event); err != nil {
			return image.Image{}, err
		}

		return image.Decode(buf.String())
	})
}
1109112
func (f *Facade) DeployService(ctx datastore.Context, poolID, parentID string, overwrite bool, svcDef servicedefinition.ServiceDefinition) (string, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.DeployService"))
	store := f.serviceStore
	alog := f.auditLogger.Message(ctx, "Deploying Service Definition").Action(audit.Deploy).
		ID(parentID).Type(service.GetType()).
		WithFields(logrus.Fields{"poolid": poolID, "svcdefname": svcDef.GetID()})
	logger := plog.WithFields(logrus.Fields{
		"poolid":     poolID,
		"parentid":   parentID,
		"overwrite":  overwrite,
		"svcdefname": svcDef.GetID(),
	})
	// get the parent service
	svc, err := store.Get(ctx, parentID)
	if err != nil {
		logger.WithError(err).Error("Could not get parent service")
		return "", alog.Error(err)
	}

	// Do some pool validation
	if poolID != "" {
		// check the pool ID
		if pool, err := f.GetResourcePool(ctx, poolID); err != nil {
			logger.WithError(err).Error("Could not look up resource pool")
			return "", alog.Error(err)
		} else if pool == nil {
			err := fmt.Errorf("pool not found")
			logger.WithError(err).Error("Could not look up resource pool")
			return "", alog.Error(err)
		}
	} else {
		// If the poolID is not specified, default to use the parent service's poolID
		poolID = svc.PoolID // I am going to assume that the pool on the parent service is correct
	}

	// get the tenant id
	tenantID := svc.ID
	alog = alog.WithField("tenantid", tenantID)
	logger = logger.WithFields(logrus.Fields{
		"tenantid": tenantID,
		"service":  svc.Name,
	})
	if svc.ParentServiceID != "" {
		if tenantID, err = f.GetTenantID(ctx, svc.ParentServiceID); err != nil { // make this call a little cheaper
			logger.WithError(err).Error("Could not get tenant")
			return "", alog.Error(err)
		}
	}

	var statusUpdater = func(status string) {}
	result, err := f.deployService(ctx, tenantID, svc.ID, svc.DeploymentID, poolID, overwrite, svcDef, statusUpdater)
	return result, alog.Error(err)
}
833959
func (s *CreateProjectInput) SetPlacementTemplate(v *PlacementTemplate) *CreateProjectInput {
	s.PlacementTemplate = v
	return s
}
347971
func (client *Client) CreateTemplate(ctx context.Context, template Template) (string, error) {
	content := map[string]interface{}{
		"name":     template.Name,
		"template": template.Content,
	}

	if err := client.request(ctx, "POST", "templates", content, &template); err != nil {
		return "", err
	}

	return template.ID, nil
}
537026
func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string {
	var b bytes.Buffer
	if err := tmpl.Execute(&b, data); err != nil {
		utilLog.Error("ExecuteTemplate: Execute failed", "error", err)
	}
	return b.String()
}
1084884
func (g *Generator) SetTemplate(tmpl string) error {
	t, err := template.New("mock").Parse(tmpl)
	if err != nil {
		return err
	}
	g.mockTmpl = t
	return nil
}
1110056
func (s *Store) GetTemplate(context.Context, string) ([]byte, error) {
	return nil, fmt.Errorf("not supported")
}
252531
func UseLaunchTemplate(ig *kops.InstanceGroup) bool {
	if featureflag.EnableLaunchTemplates.Enabled() {
		return true
	}

	return UseMixedInstancePolicies(ig)
}