schematics

package
v0.0.0-...-af3a870 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2021 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// WorkspaceStatusNew is the status when the Workspace being created
	WorkspaceStatusNew = WorkspaceStatus("NEW")

	// WorkspaceStatusInactive is the status when it's alredy created waiting to do the planning
	WorkspaceStatusInactive = WorkspaceStatus("INACTIVE")

	// WorkspaceStatusPlaning is the status when the workspace is doing the planning
	WorkspaceStatusPlaning = WorkspaceStatus("PLANING")

	// WorkspaceStatusPlanned is the status when the workspace planing is completed
	WorkspaceStatusPlanned = WorkspaceStatus("PLANNED")

	// WorkspaceStatusApplying is the status when the workspace is applying the changes
	WorkspaceStatusApplying = WorkspaceStatus("APPLYING")

	// WorkspaceStatusDestroyed is the status when the workspace resources were destroyed and the workspace deleted
	WorkspaceStatusDestroyed = WorkspaceStatus("DESTROYED")

	// WorkspaceStatusDeleted is the status when the workspace was deleted
	WorkspaceStatusDeleted = WorkspaceStatus("DELETED")
)

Variables

View Source
var NilActivity = NewActivity(nil, "", nil)

NilActivity is an empty or nil activity that doesn't exists or already finished

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Message string                  `json:"message,omitempty"`
	Error   apiv1.APIMessagePayload `json:"error,omitempty"`
}

APIError encapsulate a returned error from the API

type Activity

type Activity struct {
	ID          string    `json:"id,omitempty" yaml:"id,omitempty"`
	Name        string    `json:"name,omitempty" yaml:"name,omitempty"`
	Status      string    `json:"status,omitempty" yaml:"status,omitempty"`
	StartTime   time.Time `json:"start_time,omitempty" yaml:"start_time,omitempty"`
	EndTime     time.Time `json:"end_time,omitempty" yaml:"end_time,omitempty"`
	PerformedAt time.Time `json:"performed_at,omitempty" yaml:"performed_at,omitempty"`
	PerformedBy string    `json:"performed_by,omitempty" yaml:"performed_by,omitempty"`
	Message     string    `json:"message,omitempty" yaml:"message,omitempty"`
	WorkspaceID string    `json:"workspace_id,omitempty" yaml:"workspace_id,omitempty"`
	// contains filtered or unexported fields
}

Activity encapsupate the information about a Schematics workspace activity

func NewActivity

func NewActivity(service *Service, workspaceID string, act *apiv1.WorkspaceActivity) Activity

NewActivity creates a new Activity from a WorkspaceActivity

func (*Activity) Error

func (a *Activity) Error() error

Error ...

func (*Activity) SetOutput

func (a *Activity) SetOutput(w io.Writer) *Activity

SetOutput sets a logger for the activity. It won't log by default

func (*Activity) Wait

func (a *Activity) Wait() error

Wait ...

type EnvVariable

type EnvVariable map[string]string

EnvVariable is an environment variable to set in the Schematics Workspace

type GitRepo

type GitRepo struct {
	Branch       string `json:"branch,omitempty" yaml:"branch,omitempty"`
	Release      string `json:"release,omitempty" yaml:"release,omitempty"`
	RepoShaValue string `json:"repo_sha_value,omitempty" yaml:"repo_sha_value,omitempty"`
	RepoURL      string `json:"repo_url,omitempty" yaml:"repo_url,omitempty"`
	URL          string `json:"url,omitempty" yaml:"url,omitempty"`
	Token        string `json:"token,omitempty" yaml:"token,omitempty"`
}

GitRepo encapsulate the parameters for a Git repository (GitHub or GitLab) storing a Terraform code to be executed by Schematics

type ICClient

type ICClient struct {
	UserAgent string
	// contains filtered or unexported fields
}

ICClient is an HTTP Client wrapped by the Schematics client to communicate with the IBM Cloud endpoint API and provide the provide the authentication

func (*ICClient) Do

func (c *ICClient) Do(req *http.Request) (*http.Response, error)

Do implements the Do method so ICClient is a HttpRequestDoer interface

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the Schematics service

func NewService

func NewService(opt *ServiceOptions) *Service

NewService creates a new Schematics service to communicate with the Schematics API endpoint

func (*Service) List

func (s *Service) List(ctx context.Context) (*WorkspaceList, error)

List return a list of existing Schematics workspaces in your IBM Cloud account

func (*Service) Version

func (s *Service) Version(ctx context.Context) (*SupportedVersion, error)

Version returns the Schematics versions and supported components

type ServiceOptions

type ServiceOptions struct {
	BaseURL    string
	HTTPClient *http.Client
	APIKey     string
	APIVersion string
}

ServiceOptions are the parameters to pass to create a new Schematics Service

type SupportedVersion

type SupportedVersion struct {
	Builddate                  string   `json:"builddate,omitempty" yaml:"builddate,omitempty"`
	Buildno                    string   `json:"buildno,omitempty" yaml:"buildno,omitempty"`
	Commitsha                  string   `json:"commitsha,omitempty" yaml:"commitsha,omitempty"`
	APIVersion                 string   `json:"api_version,omitempty" yaml:"api_version,omitempty"`
	TerraformVersions          []string `json:"terraform_versions,omitempty" yaml:"terraform_versions,omitempty"`
	IBMCloudProviderVersions   []string `json:"ibm_cloud_provider_versions,omitempty" yaml:"ibm_cloud_provider_versions,omitempty"`
	HelmVersions               []string `json:"helm_versions,omitempty" yaml:"helm_version,omitempty"`
	HelmProviderVersions       []string `json:"helm_provider_versions,omitempty" yaml:"helm_provider_version,omitempty"`
	AnsibleVersions            []string `json:"ansible_versions,omitempty" yaml:"ansible_versions,omitempty"`
	AnsibleProvisionerVersions []string `json:"ansible_provisioner_versions,omitempty" yaml:"ansible_provisioner_versions,omitempty"`
	KubernetesProviderVersions []string `json:"kubernetes_provider_versions,omitempty" yaml:"kubernetes_provider_versions,omitempty"`
	OCClientVersions           []string `json:"oc_client_versions,omitempty" yaml:"oc_client_versions,omitempty"`
	RestAPIProviderVersions    []string `json:"rest_api_provider_versions,omitempty" yaml:"rest_api_provider_versions,omitempty"`
	TemplateNames              []string `json:"template_names,omitempty" yaml:"template_names,omitempty"`
}

SupportedVersion contains the version of the Schamtics, used components and supported providers

func Version

func Version() (*SupportedVersion, error)

Version returns the Schematics versions and supported components using the default Schematics service

type Variable

type Variable struct {
	Name        string `json:"name,omitempty" yaml:"name,omitempty"`
	Value       string `json:"value,omitempty" yaml:"value,omitempty"`
	Type        string `json:"type,omitempty" yaml:"type,omitempty"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	Secure      bool   `json:"secure,omitempty" yaml:"secure,omitempty"`
}

Variable encapsulate the parameters for a Schematics Workspace or Terraform variable

type Workspace

type Workspace struct {
	ID                  string                 `json:"id,omitempty" yaml:"id,omitempty"`
	Name                string                 `json:"name,omitempty" yaml:"name,omitempty"`
	Description         string                 `json:"description,omitempty" yaml:"description,omitempty"`
	Location            string                 `json:"location,omitempty" yaml:"location,omitempty"`
	ResourceGroup       string                 `json:"resource_group,omitempty" yaml:"resource_group,omitempty"`
	Tags                []string               `json:"tags,omitempty" yaml:"tags,omitempty"`
	EnvValues           []EnvVariable          `json:"env_values,omitempty" yaml:"env_values,omitempty"`
	Folder              string                 `json:"folder,omitempty" yaml:"folder,omitempty"`
	InitStateFile       string                 `json:"init_state_file,omitempty" yaml:"init_state_file,omitempty"`
	Type                string                 `json:"type,omitempty" yaml:"type,omitempty"`
	UninstallScriptName string                 `json:"uninstall_script_name,omitempty" yaml:"uninstall_script_name,omitempty"`
	Values              string                 `json:"values,omitempty" yaml:"values,omitempty"`
	Variables           []Variable             `json:"variables,omitempty" yaml:"variables,omitempty"`
	GitRepo             *GitRepo               `json:"git_repo,omitempty" yaml:"git_repo,omitempty"`
	CreatedAt           time.Time              `json:"created_at,omitempty" yaml:"created_at,omitempty"`
	CreatedBy           string                 `json:"created_by,omitempty" yaml:"created_by,omitempty"`
	Status              WorkspaceStatus        `json:"status,omitempty" yaml:"status,omitempty"`
	Output              map[string]interface{} `json:"output,omitempty" yaml:"output,omitempty"`

	Code    []byte
	TarCode []byte
	// contains filtered or unexported fields
}

Workspace is a Schematics workspace

func New

func New(name, description string, service *Service) *Workspace

New creates an empty Workspace structure which is linked to a Schematics workspace and used to execute actions on it

func (*Workspace) AddRepo

func (w *Workspace) AddRepo(url string)

AddRepo assign a Git URL from GitHub, GitLab, BitBucket or any other supported by Schematics, to the Workspace

func (*Workspace) AddVar

func (w *Workspace) AddVar(name, value, varType, description string, secure bool) error

AddVar appends a new variable to the workspace settings

func (*Workspace) Apply

func (w *Workspace) Apply() (*Activity, error)

Apply executes the applying of the Schematics Workspace. It 'executes' the Terraform code in the workspace

Example

ExampleApply creates a workspace and execute all the actions to provision a Resource Group from a public GitHub repository

package main

import (
	"bytes"
	"fmt"
	"os"

	"github.com/johandry/gics/schematics"
)

func main() {
	if icAPIKey := os.Getenv("IC_API_KEY"); len(icAPIKey) == 0 {
		fmt.Printf("[ERROR] GICS requires the IBM Cloud API Key exported in the 'IC_API_KEY' variable")
		return
	}

	w := schematics.New("GICS Demo with a GH repository", "", nil)
	defer w.Delete(true)

	w.AddVar("prefix", "gics-gh-demo", "", "", false)
	w.AddVar("enable", "true", "bool", "", false)
	w.GitRepo = &schematics.GitRepo{
		URL: "https://github.com/johandry/gics-pub-test",
	}

	act, err := w.Create()
	if err != nil {
		fmt.Printf("[ERROR] Fail to trigger the Schematics Workspace creation. %s", err)
		return
	}
	if err := act.Wait(); err != nil {
		fmt.Printf("[ERROR] Fail to create the Schematics Workspace. %s", err)
		return
	}

	act, err = w.Plan()
	if err != nil {
		fmt.Printf("[ERROR] Fail trigger to generate the plan of the Schematics Workspace. %s", err)
		return
	}
	if err := act.SetOutput(os.Stdout).Wait(); err != nil {
		fmt.Printf("[ERROR] Fail to generate the plan of the Schematics Workspace. %s", err)
		return
	}

	var buf bytes.Buffer
	act, err = w.Apply()
	if err != nil {
		fmt.Printf("[ERROR] Fail to trigger the Schematics Workspace plan execution. %s", err)
		return
	}
	go func() {
		// do something with the buffer or the activity
	}()
	if err := act.SetOutput(&buf).Wait(); err != nil {
		fmt.Printf("[ERROR] Fail to execute the plan of the Schematics Workspace. %s", err)
		return
	}
	fmt.Println(buf.String())

	output := w.GetParam("name")
	fmt.Printf("Resource Group name: %s", output["name"])
}
Output:

Resource Group name: gics-gh-demo-group

func (*Workspace) ApplySync

func (w *Workspace) ApplySync(writer io.Writer) (*Activity, error)

ApplySync ...

func (*Workspace) Create

func (w *Workspace) Create() (*Activity, error)

Create creates a Schematics Workspace and returns the activity in charge of this task

func (*Workspace) CreateSync

func (w *Workspace) CreateSync(writer io.Writer) (*Activity, error)

CreateSync ...

func (*Workspace) Delete

func (w *Workspace) Delete(destroy bool) error

Delete deletes an existing Schematics workspace, it may destroy the resources and wait for them to be destroyed

func (*Workspace) Destroy

func (w *Workspace) Destroy() (*Activity, error)

Destroy destroyes the resources created by the Terraform code in the Schematics Workspace, it does not delete the workspace

func (*Workspace) DestroySync

func (w *Workspace) DestroySync(writer io.Writer) (*Activity, error)

DestroySync ...

func (*Workspace) GetParam

func (w *Workspace) GetParam(params ...string) map[string]interface{}

GetParam collect and returns the requested output parameters of the execution of the Schematics workspace

func (*Workspace) LastActivities

func (w *Workspace) LastActivities() ([]Activity, error)

LastActivities returns the last executed activities

func (*Workspace) LastActivity

func (w *Workspace) LastActivity(name string) (*Activity, error)

LastActivity returns the last executed activity. It should be call after every action (i.e. Plan, Apply) to return the action activity.

func (*Workspace) ListResources

func (w *Workspace) ListResources() ([]string, error)

ListResources returns the list of resources created by the workspace

func (*Workspace) LoadCode

func (w *Workspace) LoadCode(code string) error

LoadCode tar and loads the given code to the workspace

func (*Workspace) Plan

func (w *Workspace) Plan() (*Activity, error)

Plan executes the planning of the Schematics Workspace

func (*Workspace) PlanSync

func (w *Workspace) PlanSync(writer io.Writer) (*Activity, error)

PlanSync ...

func (*Workspace) Run

func (w *Workspace) Run() error

Run is used to create, generate and apply the plan of the Schematics workspace in a synchronous way, blocking the execution of the code until the process is completed or fail

Example

ExampleWorkspace_Run creates and runs a workspace with a simple/short code to provision a Resource Group. The executing is asynchronous, it does not block the execution of the code.

package main

import (
	"fmt"
	"os"

	"github.com/johandry/gics/schematics"
)

func main() {
	if icAPIKey := os.Getenv("IC_API_KEY"); len(icAPIKey) == 0 {
		fmt.Printf("[ERROR] GICS requires the IBM Cloud API Key exported in the 'IC_API_KEY' variable")
		return
	}

	w := schematics.New("GICS Demo", "", nil)
	defer w.Delete(true)

	w.AddVar("prefix", "gics-demo", "", "", false)
	w.Code = []byte(`
		variable "prefix" {}
		provider "ibm" {
			generation         = 2
			region             = "us-south"
		}
		resource "ibm_resource_group" "group" {
			name = "${var.prefix}-group"
		}
		output "name" {
			value = ibm_resource_group.group.name
		}
	`)

	if err := w.Run(); err != nil {
		fmt.Printf("[ERROR] Fail the execution of the Schematics Workspace. %s", err)
		return
	}

	output := w.GetParam("name")
	fmt.Printf("Resource Group name: %s", output["name"])
}
Output:

Resource Group name: gics-demo-group
Example (Private_repo)

ExampleWorkspace_RunSync creates and runs a workspace from a code located in a private GitHub repository to provision a Resource Group

package main

import (
	"fmt"
	"os"

	"github.com/johandry/gics/schematics"
)

func main() {
	if icAPIKey := os.Getenv("IC_API_KEY"); len(icAPIKey) == 0 {
		fmt.Printf("[ERROR] GICS requires the IBM Cloud API Key exported in the 'IC_API_KEY' variable")
		return
	}

	w := schematics.New("GICS Demo with a GH repository", "", nil)
	defer w.Delete(true)

	w.AddVar("prefix", "gics-gh-priv-demo", "", "", false)
	w.AddVar("enable", "true", "bool", "", false)
	w.GitRepo = &schematics.GitRepo{
		URL:    "https://github.com/johandry/gics-priv-test",
		Branch: "gics_demo",
		Token:  os.Getenv("GICS_GH_TOKEN"),
	}

	if err := w.Run(); err != nil {
		fmt.Printf("[ERROR] Fail the execution of the Schematics Workspace. %s", err)
		return
	}

	output := w.GetParam("name")
	fmt.Printf("Resource Group name: %s", output["name"])
}
Output:

Resource Group name: gics-gh-priv-demo-group

func (*Workspace) SetOutput

func (w *Workspace) SetOutput(out io.Writer)

SetOutput sets the output used for the logger. It won't log by default

func (*Workspace) UploadTar

func (w *Workspace) UploadTar(body io.Reader) error

UploadTar upload a compressed (Tar) file/content into the workspace

type WorkspaceList

type WorkspaceList struct {
	Workspaces []WorkspaceSummary `json:"workspaces,omitempty" yaml:"workspaces,omitempty"`
}

WorkspaceList is a data structure for a list of Schematics workspaces used by List()

func List

func List() (*WorkspaceList, error)

List return a list of existing Schematics workspaces in your IBM Cloud account using the default Schematics service

type WorkspaceStatus

type WorkspaceStatus string

WorkspaceStatus is the status of a Schematics workspace

type WorkspaceSummary

type WorkspaceSummary struct {
	ID          string    `json:"id,omitempty" yaml:"id,omitempty"`
	Name        string    `json:"name,omitempty" yaml:"name,omitempty"`
	Description string    `json:"description,omitempty" yaml:"description,omitempty"`
	Location    string    `json:"location,omitempty" yaml:"location,omitempty"`
	Owner       string    `json:"owner,omitempty" yaml:"owner,omitempty"`
	State       string    `json:"state,omitempty" yaml:"state,omitempty"`
	Created     time.Time `json:"created,omitempty" yaml:"created,omitempty"`
}

WorkspaceSummary is a data structure for the Schematic workspace information to return a list of workspaces

Directories

Path Synopsis
api
v1
Package v1 provides primitives to interact the openapi HTTP API.
Package v1 provides primitives to interact the openapi HTTP API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL