From 84e6364bff670f9230a5a90ccf0af0bf53aeb7fe Mon Sep 17 00:00:00 2001 From: Jakub Janczak Date: Fri, 6 Feb 2015 12:26:11 +0100 Subject: [PATCH] remote/s3: using address for bucket and path --- remote/s3.go | 28 ++++++++++++++++++---------- remote/s3_test.go | 6 ++---- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/remote/s3.go b/remote/s3.go index 6c4d1a41f..bc43e9d17 100644 --- a/remote/s3.go +++ b/remote/s3.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "os" + "regexp" "time" "github.com/goamz/goamz/aws" @@ -19,7 +20,7 @@ type S3RemoteClient struct { Path string } -func GetRegion(conf map[string]string) (aws.Region, error) { +func getRegion(conf map[string]string) (aws.Region, error) { regionName, ok := conf["region"] if !ok || regionName == "" { regionName = os.Getenv("AWS_DEFAULT_REGION") @@ -35,6 +36,15 @@ func GetRegion(conf map[string]string) (aws.Region, error) { return region, nil } +func getBucketAndPath(address string) (string, string, error) { + re := regexp.MustCompile("^s3://([^/]+)/(.+)$") + matches := re.FindStringSubmatch(address) + if len(matches) < 3 { + return "", "", fmt.Errorf("Address for s3 should be of form: s3:///") + } + return matches[1], matches[2], nil +} + func NewS3RemoteClient(conf map[string]string) (*S3RemoteClient, error) { client := &S3RemoteClient{} @@ -43,22 +53,20 @@ func NewS3RemoteClient(conf map[string]string) (*S3RemoteClient, error) { return nil, err } - region, err := GetRegion(conf) + region, err := getRegion(conf) if err != nil { return nil, err } - bucketName, ok := conf["bucket"] + address, ok := conf["address"] if !ok { - return nil, fmt.Errorf("Missing 'bucket_name' configuration") + return nil, fmt.Errorf("'address' configuration not set for S3 remote state storage backend") + } + bucketName, path, err := getBucketAndPath(address) + if err != nil { + return nil, err } - client.Bucket = s3.New(auth, region).Bucket(bucketName) - - path, ok := conf["path"] - if !ok { - return nil, fmt.Errorf("Missing 'path' configuration") - } client.Path = path return client, nil diff --git a/remote/s3_test.go b/remote/s3_test.go index 41309ae3f..07e1c2fd5 100644 --- a/remote/s3_test.go +++ b/remote/s3_test.go @@ -17,8 +17,7 @@ func TestS3Remote_NewClient(t *testing.T) { conf["access_token"] = "test" conf["secret_token"] = "test" - conf["path"] = "hashicorp/test-state" - conf["bucket"] = "plan3-test" + conf["address"] = "s3://plan3-test/hashicorp/test-state" conf["region"] = "eu-west-1" if _, err := NewS3RemoteClient(conf); err != nil { t.Fatalf("err: %v", err) @@ -40,8 +39,7 @@ func TestS3Remote_Validate_envVar(t *testing.T) { defer os.Setenv("AWS_DEFAULT_REGION", os.Getenv("AWS_DEFAULT_REGION")) os.Setenv("AWS_DEFAULT_REGION", "eu-west-1") - conf["path"] = "hashicorp/test-state" - conf["bucket"] = "plan3-test" + conf["address"] = "s3://terraform-state/hashicorp/test-state" if _, err := NewS3RemoteClient(conf); err != nil { t.Fatalf("err: %v", err) }