乐趣区

关于java:通过Terraform创建GCP-Pubsub

1 简介

Terraform 是治理许多平台的基础设施的工具,如 AWS、GCP 和 Azure。这篇文章将解说如何通过 Terraform 来治理 GCP Pub/Sub。

创立 GCP 我的项目请参考:初始化一个 GCP 我的项目并用 gcloud 拜访操作

2 Terraform 创立 Pub/Sub

2.1 下载 Terraform 插件

咱们须要装置 GCP 的 Terraform 插件来治理 GCP 资源:

# 设置插件目录
$ export TERRAFORM_PLUGIN=/Users/larry/Software/terraform/plugins
# 创立目录
$ mkdir -p ${TERRAFORM_PLUGIN}/registry.terraform.io/hashicorp/google/4.0.0/darwin_amd64
$ cd ${TERRAFORM_PLUGIN}/registry.terraform.io/hashicorp/google/4.0.0/darwin_amd64
# 下载
$ wget https://releases.hashicorp.com/terraform-provider-google/4.0.0/terraform-provider-google_4.0.0_darwin_amd64.zip
# 解压
$ unzip terraform-provider-google_4.0.0_darwin_amd64.zip

2.2 筹备 Terraform 代码

须要提供 Terraform 代码理治理 Pub/Sub,更多细节请参考:Terrafrom GCP.

版本文件 version.tf:

terraform {
  required_version = "= 1.0.11"
  required_providers {

    google = {
      source  = "hashicorp/google"
      version = "= 4.0.0"
    }
  }
}

主文件 main.tf:

provider "google" {project     = "pkslow"}

resource "google_pubsub_topic" "pkslow-poc" {name = "pkslow-poc"}

resource "google_pubsub_subscription" "pkslow-poc" {
  name  = "pkslow-poc"
  topic = google_pubsub_topic.pkslow-poc.name

  labels = {foo = "bar"}

  # 20 minutes
  message_retention_duration = "1200s"
  retain_acked_messages      = true

  ack_deadline_seconds = 20

  expiration_policy {ttl = "300000.5s"}
  retry_policy {minimum_backoff = "10s"}

  enable_message_ordering    = true
}

2.3 初始化和变更

指定插件目录初始化:

$ terraform init -plugin-dir=${TERRAFORM_PLUGIN}

使变更失效,就会在 GCP 上创立对应的资源:

$ terraform apply -auto-approve

如果没有产生谬误,则意味着创立胜利,咱们检查一下:

$ gcloud pubsub topics list
---
name: projects/pkslow/topics/pkslow-poc

$ gcloud pubsub subscriptions list
---
ackDeadlineSeconds: 20
enableMessageOrdering: true
expirationPolicy:
  ttl: 300000.500s
labels:
  foo: bar
messageRetentionDuration: 1200s
name: projects/pkslow/subscriptions/pkslow-poc
pushConfig: {}
retainAckedMessages: true
retryPolicy:
  maximumBackoff: 600s
  minimumBackoff: 10s
topic: projects/pkslow/topics/pkslow-poc

留神:咱们并没有提供任何明码或密钥,那 Terraform 怎么能够间接操作我的 GCP 资源呢?因为它会依据环境变量 GOOGLE_APPLICATION_CREDENTIALS 来获取。

3 发送和接管音讯

咱们通过 gcloud 来发送音讯到 Pub/Sub 上:

$ gcloud pubsub topics publish pkslow-poc --message="www.pkslow.com"
messageIds:
- '3491736520339885'

$ gcloud pubsub topics publish pkslow-poc --message="Larry Deng"
messageIds:
- '3491738650256958'

$ gcloud pubsub topics publish pkslow-poc --message="Hi, pkslower"
messageIds:
- '3491739306095970'

从 Pub/Sub 拉取音讯:

$ gcloud pubsub subscriptions pull pkslow-poc --auto-ack

咱们还能在 GCP 界面上监控对应的队列,非常不便:

4 代码

代码在 GitHub 上:https://github.com/LarryDpk/p…

退出移动版