Skip to content

Commit

Permalink
Open source the first release!
Browse files Browse the repository at this point in the history
  • Loading branch information
kushmansingh committed Mar 16, 2021
0 parents commit 2be9f48
Show file tree
Hide file tree
Showing 42 changed files with 3,760 additions and 0 deletions.
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## 1.0.0 (Unreleased)

NOTES:
First official release!

BREAKING CHANGES:

N/A

FEATURES:

* **New Resource:** `buildkite_pipeline`
* **New Resource:** `buildkite_pipeline_schedule`
* **New Resource:** `buildkite_team`
* **New Resource:** `buildkite_team_pipeline`
* **New Resource:** `buildkite_team_member`
* **New Data Source:** `buildkite_user`

IMPROVEMENTS:

N/A

BUG FIXES:

N/A
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2020 samsara-dev

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 changes: 20 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
BINARY_NAME=terraform-provider-buildkite
VERSION=1.0.0
BIN_PATH ?= ./bin

.PHONY: build
build:
@GOOS=darwin GOARCH=amd64 go build -o ${BIN_PATH}/${BINARY_NAME}_v${VERSION}_darwin_amd64
@GOOS=linux GOARCH=amd64 go build -o ${BIN_PATH}/${BINARY_NAME}_v${VERSION}_linux_amd64

.PHONY: test
test:
@go test -v ./...

.PHONY: testacc
testacc:
@TF_ACC=1 go test -v ./...

.PHONY: clean
clean:
@rm -rf ${BIN_PATH}
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[![Build status](https://badge.buildkite.com/ba2febb05f89921c3824ce22bd94d47310dcd481186151de21.svg?branch=main)](https://buildkite.com/samsara/hq-terraform-provider-buildkite)
# Terraform Provider for [Buildkite](https://buildkite.com)

Note: This provider is built for Terraform 0.11 and all docs/examples reflect this.
## Documentation
Documentation for this provider is located in `/docs` with the templates generated according to [Terraform Guidelines](https://www.terraform.io/docs/registry/providers/docs.html#generating-documentation).

## Development
To build binaries run
```
make build
```
which will output the binaries to `./bin` in the format `terraform-provider-buildkite_v0.1.0_${OS}_${ARCH}`.

### Testing
The tests for this provider create and delete *real* resources in a given Buildkite account specified by `BUILDKITE_ORGANIZATION_SLUG` and `BUILDKITE_TOKEN`. A real user already registered in the organization is also required and must be specified via `BUILDKITE_USER_EMAIL`.


Integration tests for just the Buildkite client can be run via:
```
make test
```
while full [Terraform Acceptance Tests](https://www.terraform.io/docs/extend/testing/acceptance-tests/index.html) are run via:
```
make testacc
```
90 changes: 90 additions & 0 deletions buildkite/client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package client

import (
"context"
"errors"
"fmt"
"net/http"

buildkiteRest "github.com/buildkite/go-buildkite/v2/buildkite"
"github.com/shurcooL/graphql"
)

// Base URLs for Buildkite API
const (
RESTBaseURL = "https://api.buildkite.com/v2"
GQLBaseURL = "https://graphql.buildkite.com/v1"
)

// Client encapsulates the REST and GQL client for a given org.
type Client struct {
// orgSlug is the slug of the org
orgSlug string
// orgID is the gql ID for the org
orgID string

httpClient *http.Client
restClient *buildkiteRest.Client
gqlClient *graphql.Client
}

// We need this transport to add the authorization headers to our requests.
// We can't use `buildkite.NewTokenConfig` because that transport does not work
// for GQL requests.
type tokenTransport struct {
token string
}

func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", t.token))
return http.DefaultTransport.RoundTrip(req)
}

// NewClient returns a new buildkite client based on the given org and token.
// It will return an error if the token is invalid.
func NewClient(org, token string) (*Client, error) {
httpClient := &http.Client{
Transport: &tokenTransport{token: token},
}
restCli := buildkiteRest.NewClient(httpClient)
gqlCli := graphql.NewClient(GQLBaseURL, httpClient)
c := &Client{
orgSlug: org,
httpClient: httpClient,
restClient: restCli,
gqlClient: gqlCli,
}
if err := c.CheckAuth(); err != nil {
return nil, fmt.Errorf("checking auth: %w", err)
}

// get org id
var query struct {
Organization struct {
ID string `graphql:"id"`
} `graphql:"organization(slug: $slug)"`
}
vars := map[string]interface{}{
"slug": org,
}
err := c.gqlClient.Query(context.TODO(), &query, vars)
if err != nil {
return nil, fmt.Errorf("getting org id: %w", err)
}
c.orgID = query.Organization.ID
return c, nil
}

// CheckAuth validates the client's token against the access token endpoint and
// returns whether the token appears valid based on this request.
func (c *Client) CheckAuth() error {
req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/access-token", RESTBaseURL), nil)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return errors.New("non 200 status")
}
return nil
}
62 changes: 62 additions & 0 deletions buildkite/client/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package client

import (
"fmt"
"net/http"
"os"
"testing"
)

const (
orgEnvVar = "BUILDKITE_ORGANIZATION_SLUG"
tokenEnvVar = "BUILDKITE_TOKEN"
userEnvVar = "BUILDKITE_USER_EMAIL"
)

var (
cli *Client
userEmail string
userID string
)

func init() {
requiredVars := []string{orgEnvVar, tokenEnvVar, userEnvVar}
for _, v := range requiredVars {
if val := os.Getenv(v); val == "" {
panic(fmt.Sprintf("Required env var %s is not set", v))
}
}

c, err := NewClient(os.Getenv(orgEnvVar), os.Getenv(tokenEnvVar))
if err != nil {
panic("Couldn't create client")
}
cli = c
userEmail = os.Getenv(userEnvVar)
u, err := cli.GetUser(userEmail)
if err != nil {
panic("Couldn't get user")
}
userID = string(u.ID)
}

func TestCheckAuth(t *testing.T) {
c := &Client{
httpClient: &http.Client{
Transport: &tokenTransport{token: "wontwork"},
},
}
if err := c.CheckAuth(); err == nil {
t.Error("Invalid token still passed auth")
}

token := os.Getenv("BUILDKITE_TOKEN")
c = &Client{
httpClient: &http.Client{
Transport: &tokenTransport{token: token},
},
}
if err := c.CheckAuth(); err != nil {
t.Errorf("Auth should have passed but failed, a valid token must be set at BUILDKITE_TOKEN")
}
}
96 changes: 96 additions & 0 deletions buildkite/client/pipeline.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package client

import (
"context"
"fmt"

buildkiteRest "github.com/buildkite/go-buildkite/v2/buildkite"
"github.com/shurcooL/graphql"
)

// Pipeline represents a pipeline in Buildkite.
type Pipeline = buildkiteRest.Pipeline

// GetPipelineID returns the gql ID for a given pipeline specified by its slug.
func (c *Client) GetPipelineID(slug string) (string, error) {
var query struct {
Pipeline struct {
ID graphql.String `graphql:"id"`
} `graphql:"pipeline(slug: $slug)"`
}
vars := map[string]interface{}{
"slug": fmt.Sprintf("%s/%s", c.orgSlug, slug),
}
if err := c.gqlClient.Query(context.TODO(), &query, vars); err != nil {
return "", err
}
return string(query.Pipeline.ID), nil
}

func (c *Client) CreatePipeline(pipeline *Pipeline) error {
safeString := func(s *string) string {
if s == nil {
return ""
}
return *s
}
safeBool := func(b *bool) bool {
if b == nil {
return false
}
return *b
}
var provider buildkiteRest.ProviderSettings
if pipeline.Provider != nil {
provider = pipeline.Provider.Settings
}
payload := &buildkiteRest.CreatePipeline{
// Steps are managed through the configuration field as a yaml string.
Steps: nil,
// Env is also part of the yaml steps.
Env: nil,
// Teams are associated through TeamPipelines rather than specifying them solely on
// Pipeline create.
TeamUuids: nil,

Name: safeString(pipeline.Name),
Repository: safeString(pipeline.Repository),
DefaultBranch: safeString(pipeline.DefaultBranch),
Description: safeString(pipeline.Description),
BranchConfiguration: safeString(pipeline.BranchConfiguration),
SkipQueuedBranchBuilds: safeBool(pipeline.SkipQueuedBranchBuilds),
SkipQueuedBranchBuildsFilter: safeString(pipeline.SkipQueuedBranchBuildsFilter),
CancelRunningBranchBuilds: safeBool(pipeline.CancelRunningBranchBuilds),
CancelRunningBranchBuildsFilter: safeString(pipeline.CancelRunningBranchBuildsFilter),
Configuration: pipeline.Configuration,

ProviderSettings: provider,
}
p, _, err := c.restClient.Pipelines.Create(c.orgSlug, payload)
if err != nil {
return err
}
if p.ID == nil {
return fmt.Errorf("nil ID for pipeline: %s", payload.Name)
}
pipeline.Slug = p.Slug
return nil
}

func (c *Client) ReadPipeline(slug string) (*Pipeline, error) {
p, _, err := c.restClient.Pipelines.Get(c.orgSlug, slug)
if err != nil {
return nil, err
}
return p, nil
}

func (c *Client) UpdatePipeline(pipeline *Pipeline) error {
_, err := c.restClient.Pipelines.Update(c.orgSlug, pipeline)
return err
}

func (c *Client) DeletePipeline(pipeline *Pipeline) error {
_, err := c.restClient.Pipelines.Delete(c.orgSlug, *pipeline.Slug)
return err
}
Loading

0 comments on commit 2be9f48

Please sign in to comment.