Skip to content

Commit fdd3ca8

Browse files
Add deadLetterPolicy to Pub/Sub Subscription resource (#3305) (#1913)
* Add deadLetterPolicy to Pub/Sub subscription resource * fix: disable allow_empty_objects, fix docstring, add example * fix: set max_delivery_attempts * fix: block and topic name Signed-off-by: Modular Magician <[email protected]>
1 parent 8d2e6ff commit fdd3ca8

File tree

4 files changed

+248
-0
lines changed

4 files changed

+248
-0
lines changed

.changelog/3305.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:enhancement
2+
pubsub: Added `dead_letter_policy` support to `google_pubsub_subscription`
3+
```

google-beta/resource_pubsub_subscription.go

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,54 @@ for the call to the push endpoint.
9393
If the subscriber never acknowledges the message, the Pub/Sub system
9494
will eventually redeliver the message.`,
9595
},
96+
"dead_letter_policy": {
97+
Type: schema.TypeList,
98+
Optional: true,
99+
Description: `A policy that specifies the conditions for dead lettering messages in
100+
this subscription. If dead_letter_policy is not set, dead lettering
101+
is disabled.
102+
103+
The Cloud Pub/Sub service account associated with this subscriptions's
104+
parent project (i.e.,
105+
service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have
106+
permission to Acknowledge() messages on this subscription.`,
107+
MaxItems: 1,
108+
Elem: &schema.Resource{
109+
Schema: map[string]*schema.Schema{
110+
"dead_letter_topic": {
111+
Type: schema.TypeString,
112+
Optional: true,
113+
Description: `The name of the topic to which dead letter messages should be published.
114+
Format is 'projects/{project}/topics/{topic}'.
115+
116+
The Cloud Pub/Sub service\naccount associated with the enclosing subscription's
117+
parent project (i.e.,
118+
service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have
119+
permission to Publish() to this topic.
120+
121+
The operation will fail if the topic does not exist.
122+
Users should ensure that there is a subscription attached to this topic
123+
since messages published to a topic with no subscriptions are lost.`,
124+
},
125+
"max_delivery_attempts": {
126+
Type: schema.TypeInt,
127+
Optional: true,
128+
Description: `The maximum number of delivery attempts for any message. The value must be
129+
between 5 and 100.
130+
131+
The number of delivery attempts is defined as 1 + (the sum of number of
132+
NACKs and number of times the acknowledgement deadline has been exceeded for the message).
133+
134+
A NACK is any call to ModifyAckDeadline with a 0 deadline. Note that
135+
client libraries may automatically extend ack_deadlines.
136+
137+
This field will be honored on a best effort basis.
138+
139+
If this parameter is 0, a default value of 5 is used.`,
140+
},
141+
},
142+
},
143+
},
96144
"expiration_policy": {
97145
Type: schema.TypeList,
98146
Computed: true,
@@ -290,6 +338,12 @@ func resourcePubsubSubscriptionCreate(d *schema.ResourceData, meta interface{})
290338
} else if v, ok := d.GetOkExists("expiration_policy"); ok || !reflect.DeepEqual(v, expirationPolicyProp) {
291339
obj["expirationPolicy"] = expirationPolicyProp
292340
}
341+
deadLetterPolicyProp, err := expandPubsubSubscriptionDeadLetterPolicy(d.Get("dead_letter_policy"), d, config)
342+
if err != nil {
343+
return err
344+
} else if v, ok := d.GetOkExists("dead_letter_policy"); ok || !reflect.DeepEqual(v, deadLetterPolicyProp) {
345+
obj["deadLetterPolicy"] = deadLetterPolicyProp
346+
}
293347

294348
obj, err = resourcePubsubSubscriptionEncoder(d, meta, obj)
295349
if err != nil {
@@ -418,6 +472,9 @@ func resourcePubsubSubscriptionRead(d *schema.ResourceData, meta interface{}) er
418472
if err := d.Set("expiration_policy", flattenPubsubSubscriptionExpirationPolicy(res["expirationPolicy"], d, config)); err != nil {
419473
return fmt.Errorf("Error reading Subscription: %s", err)
420474
}
475+
if err := d.Set("dead_letter_policy", flattenPubsubSubscriptionDeadLetterPolicy(res["deadLetterPolicy"], d, config)); err != nil {
476+
return fmt.Errorf("Error reading Subscription: %s", err)
477+
}
421478

422479
return nil
423480
}
@@ -467,6 +524,12 @@ func resourcePubsubSubscriptionUpdate(d *schema.ResourceData, meta interface{})
467524
} else if v, ok := d.GetOkExists("expiration_policy"); ok || !reflect.DeepEqual(v, expirationPolicyProp) {
468525
obj["expirationPolicy"] = expirationPolicyProp
469526
}
527+
deadLetterPolicyProp, err := expandPubsubSubscriptionDeadLetterPolicy(d.Get("dead_letter_policy"), d, config)
528+
if err != nil {
529+
return err
530+
} else if v, ok := d.GetOkExists("dead_letter_policy"); ok || !reflect.DeepEqual(v, deadLetterPolicyProp) {
531+
obj["deadLetterPolicy"] = deadLetterPolicyProp
532+
}
470533

471534
obj, err = resourcePubsubSubscriptionUpdateEncoder(d, meta, obj)
472535
if err != nil {
@@ -504,6 +567,10 @@ func resourcePubsubSubscriptionUpdate(d *schema.ResourceData, meta interface{})
504567
if d.HasChange("expiration_policy") {
505568
updateMask = append(updateMask, "expirationPolicy")
506569
}
570+
571+
if d.HasChange("dead_letter_policy") {
572+
updateMask = append(updateMask, "deadLetterPolicy")
573+
}
507574
// updateMask is a URL parameter but not present in the schema, so replaceVars
508575
// won't set it
509576
url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
@@ -669,6 +736,42 @@ func flattenPubsubSubscriptionExpirationPolicyTtl(v interface{}, d *schema.Resou
669736
return v
670737
}
671738

739+
func flattenPubsubSubscriptionDeadLetterPolicy(v interface{}, d *schema.ResourceData, config *Config) interface{} {
740+
if v == nil {
741+
return nil
742+
}
743+
original := v.(map[string]interface{})
744+
if len(original) == 0 {
745+
return nil
746+
}
747+
transformed := make(map[string]interface{})
748+
transformed["dead_letter_topic"] =
749+
flattenPubsubSubscriptionDeadLetterPolicyDeadLetterTopic(original["deadLetterTopic"], d, config)
750+
transformed["max_delivery_attempts"] =
751+
flattenPubsubSubscriptionDeadLetterPolicyMaxDeliveryAttempts(original["maxDeliveryAttempts"], d, config)
752+
return []interface{}{transformed}
753+
}
754+
func flattenPubsubSubscriptionDeadLetterPolicyDeadLetterTopic(v interface{}, d *schema.ResourceData, config *Config) interface{} {
755+
return v
756+
}
757+
758+
func flattenPubsubSubscriptionDeadLetterPolicyMaxDeliveryAttempts(v interface{}, d *schema.ResourceData, config *Config) interface{} {
759+
// Handles the string fixed64 format
760+
if strVal, ok := v.(string); ok {
761+
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
762+
return intVal
763+
}
764+
}
765+
766+
// number values are represented as float64
767+
if floatVal, ok := v.(float64); ok {
768+
intVal := int(floatVal)
769+
return intVal
770+
}
771+
772+
return v // let terraform core handle it otherwise
773+
}
774+
672775
func expandPubsubSubscriptionName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
673776
return replaceVars(d, config, "projects/{{project}}/subscriptions/{{name}}")
674777
}
@@ -826,6 +929,40 @@ func expandPubsubSubscriptionExpirationPolicyTtl(v interface{}, d TerraformResou
826929
return v, nil
827930
}
828931

932+
func expandPubsubSubscriptionDeadLetterPolicy(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
933+
l := v.([]interface{})
934+
if len(l) == 0 || l[0] == nil {
935+
return nil, nil
936+
}
937+
raw := l[0]
938+
original := raw.(map[string]interface{})
939+
transformed := make(map[string]interface{})
940+
941+
transformedDeadLetterTopic, err := expandPubsubSubscriptionDeadLetterPolicyDeadLetterTopic(original["dead_letter_topic"], d, config)
942+
if err != nil {
943+
return nil, err
944+
} else if val := reflect.ValueOf(transformedDeadLetterTopic); val.IsValid() && !isEmptyValue(val) {
945+
transformed["deadLetterTopic"] = transformedDeadLetterTopic
946+
}
947+
948+
transformedMaxDeliveryAttempts, err := expandPubsubSubscriptionDeadLetterPolicyMaxDeliveryAttempts(original["max_delivery_attempts"], d, config)
949+
if err != nil {
950+
return nil, err
951+
} else if val := reflect.ValueOf(transformedMaxDeliveryAttempts); val.IsValid() && !isEmptyValue(val) {
952+
transformed["maxDeliveryAttempts"] = transformedMaxDeliveryAttempts
953+
}
954+
955+
return transformed, nil
956+
}
957+
958+
func expandPubsubSubscriptionDeadLetterPolicyDeadLetterTopic(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
959+
return v, nil
960+
}
961+
962+
func expandPubsubSubscriptionDeadLetterPolicyMaxDeliveryAttempts(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
963+
return v, nil
964+
}
965+
829966
func resourcePubsubSubscriptionEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
830967
delete(obj, "name")
831968
return obj, nil

google-beta/resource_pubsub_subscription_generated_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,52 @@ resource "google_pubsub_subscription" "example" {
7575
`, context)
7676
}
7777

78+
func TestAccPubsubSubscription_pubsubSubscriptionDeadLetterExample(t *testing.T) {
79+
t.Parallel()
80+
81+
context := map[string]interface{}{
82+
"random_suffix": acctest.RandString(10),
83+
}
84+
85+
resource.Test(t, resource.TestCase{
86+
PreCheck: func() { testAccPreCheck(t) },
87+
Providers: testAccProviders,
88+
CheckDestroy: testAccCheckPubsubSubscriptionDestroy,
89+
Steps: []resource.TestStep{
90+
{
91+
Config: testAccPubsubSubscription_pubsubSubscriptionDeadLetterExample(context),
92+
},
93+
{
94+
ResourceName: "google_pubsub_subscription.example",
95+
ImportState: true,
96+
ImportStateVerify: true,
97+
},
98+
},
99+
})
100+
}
101+
102+
func testAccPubsubSubscription_pubsubSubscriptionDeadLetterExample(context map[string]interface{}) string {
103+
return Nprintf(`
104+
resource "google_pubsub_topic" "example" {
105+
name = "tf-test-example-topic%{random_suffix}"
106+
}
107+
108+
resource "google_pubsub_topic" "example_dead_letter" {
109+
name = "tf-test-example-topic%{random_suffix}-dead-letter"
110+
}
111+
112+
resource "google_pubsub_subscription" "example" {
113+
name = "tf-test-example-subscription%{random_suffix}"
114+
topic = google_pubsub_topic.example.name
115+
116+
dead_letter_policy {
117+
dead_letter_topic = google_pubsub_topic.example_dead_letter.id
118+
max_delivery_attempts = 10
119+
}
120+
}
121+
`, context)
122+
}
123+
78124
func testAccCheckPubsubSubscriptionDestroy(s *terraform.State) error {
79125
for name, rs := range s.RootModule().Resources {
80126
if rs.Type != "google_pubsub_subscription" {

website/docs/r/pubsub_subscription.html.markdown

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,33 @@ resource "google_pubsub_subscription" "example" {
107107
topic = google_pubsub_topic.example.name
108108
}
109109
```
110+
<div class = "oics-button" style="float: right; margin: 0 0 -15px">
111+
<a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=pubsub_subscription_dead_letter&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">
112+
<img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">
113+
</a>
114+
</div>
115+
## Example Usage - Pubsub Subscription Dead Letter
116+
117+
118+
```hcl
119+
resource "google_pubsub_topic" "example" {
120+
name = "example-topic"
121+
}
122+
123+
resource "google_pubsub_topic" "example_dead_letter" {
124+
name = "example-topic-dead-letter"
125+
}
126+
127+
resource "google_pubsub_subscription" "example" {
128+
name = "example-subscription"
129+
topic = google_pubsub_topic.example.name
130+
131+
dead_letter_policy {
132+
dead_letter_topic = google_pubsub_topic.example_dead_letter.id
133+
max_delivery_attempts = 10
134+
}
135+
}
136+
```
110137

111138
## Argument Reference
112139

@@ -181,6 +208,16 @@ The following arguments are supported:
181208
resource never expires. The minimum allowed value for expirationPolicy.ttl
182209
is 1 day. Structure is documented below.
183210

211+
* `dead_letter_policy` -
212+
(Optional)
213+
A policy that specifies the conditions for dead lettering messages in
214+
this subscription. If dead_letter_policy is not set, dead lettering
215+
is disabled.
216+
The Cloud Pub/Sub service account associated with this subscriptions's
217+
parent project (i.e.,
218+
service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have
219+
permission to Acknowledge() messages on this subscription. Structure is documented below.
220+
184221
* `project` - (Optional) The ID of the project in which the resource belongs.
185222
If it is not provided, the provider project is used.
186223

@@ -248,6 +285,31 @@ The `expiration_policy` block supports:
248285
A duration in seconds with up to nine fractional digits, terminated by 's'.
249286
Example - "3.5s".
250287

288+
The `dead_letter_policy` block supports:
289+
290+
* `dead_letter_topic` -
291+
(Optional)
292+
The name of the topic to which dead letter messages should be published.
293+
Format is `projects/{project}/topics/{topic}`.
294+
The Cloud Pub/Sub service\naccount associated with the enclosing subscription's
295+
parent project (i.e.,
296+
service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have
297+
permission to Publish() to this topic.
298+
The operation will fail if the topic does not exist.
299+
Users should ensure that there is a subscription attached to this topic
300+
since messages published to a topic with no subscriptions are lost.
301+
302+
* `max_delivery_attempts` -
303+
(Optional)
304+
The maximum number of delivery attempts for any message. The value must be
305+
between 5 and 100.
306+
The number of delivery attempts is defined as 1 + (the sum of number of
307+
NACKs and number of times the acknowledgement deadline has been exceeded for the message).
308+
A NACK is any call to ModifyAckDeadline with a 0 deadline. Note that
309+
client libraries may automatically extend ack_deadlines.
310+
This field will be honored on a best effort basis.
311+
If this parameter is 0, a default value of 5 is used.
312+
251313
## Attributes Reference
252314

253315
In addition to the arguments listed above, the following computed attributes are exported:

0 commit comments

Comments
 (0)