Subscription with topic in different project (#640)

Right now we can't create subscription on a topic in a different gcp
project since it assume the project from the subscription. The provider
always create the full topic name string
projects/{project}/topics/{topic} with the received topic property.
Using a regexp we validate if the string is already in
the format projects/{project}/topics/{topic} and if it's the case
we don't wrap it again and take it directly. The original functionality
is maintained but it's possible to specify a different project for the
topic.
This commit is contained in:
sebasrobert 2017-10-30 16:12:14 -04:00 committed by Vincent Roseberry
parent adbb5dd4fb
commit d3b8482388
2 changed files with 41 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import (
"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/pubsub/v1"
"regexp"
)
func resourcePubsubSubscription() *schema.Resource {
@ -82,7 +83,7 @@ func resourcePubsubSubscriptionCreate(d *schema.ResourceData, meta interface{})
}
name := fmt.Sprintf("projects/%s/subscriptions/%s", project, d.Get("name").(string))
computed_topic_name := fmt.Sprintf("projects/%s/topics/%s", project, d.Get("topic").(string))
computed_topic_name := getComputedTopicName(project, d.Get("topic").(string))
// process optional parameters
var ackDeadlineSeconds int64
@ -108,6 +109,17 @@ func resourcePubsubSubscriptionCreate(d *schema.ResourceData, meta interface{})
return resourcePubsubSubscriptionRead(d, meta)
}
func getComputedTopicName(project string, topic string) string {
computed_topic_name := ""
match, _ := regexp.MatchString("projects\\/.*\\/topics\\/.*", topic)
if match {
computed_topic_name = topic
} else {
computed_topic_name = fmt.Sprintf("projects/%s/topics/%s", project, topic)
}
return computed_topic_name
}
func resourcePubsubSubscriptionRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

View File

@ -92,3 +92,31 @@ resource "google_pubsub_subscription" "foobar_sub" {
ack_deadline_seconds = 20
}`, topic, subscription)
}
func TestGetComputedTopicName(t *testing.T) {
type testData struct {
project string
topic string
expected string
}
var testCases = []testData{
testData{
project: "my-project",
topic: "my-topic",
expected: "projects/my-project/topics/my-topic",
},
testData{
project: "my-project",
topic: "projects/another-project/topics/my-topic",
expected: "projects/another-project/topics/my-topic",
},
}
for _, testCase := range testCases {
computedTopicName := getComputedTopicName(testCase.project, testCase.topic)
if computedTopicName != testCase.expected {
t.Fatalf("bad computed topic name: %s' => expected %s", computedTopicName, testCase.expected)
}
}
}