使用 Terraform 创建 Memorystore for Redis 实例
本页介绍如何使用 Terraform 创建新的 Memorystore for Redis 实例,以及如何在 Google Cloud 中使用 SSH 连接到实例。
本快速入门使用 Terraform 的 Google Cloud Platform 提供程序。
准备工作
- 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
-
在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目。
-
在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目。
- 如果您尚未安装 Google Cloud SDK,请先安装。
出现提示时,请选择您在上面选择或创建的项目。
如果您已安装 Google Cloud SDK,请进行更新。
gcloud components update
-
启用 Memorystore for Redis API
Memorystore for Redis - 具有可向其添加 Memorystore 资源的 Terraform 文件。如需了解如何使用 Google Cloud 设置 Terraform,请参阅 Google Cloud 提供程序使用入门。
创建 Memorystore for Redis 实例
以下 Terraform 资源示例在基本层级的 us-central1
区域中创建一个 2 GiB 的基本层级 Redis 实例。如需详细了解层级,请参阅 Redis 层级功能。
将以下资源添加到 Terraform 配置文件中:
resource "google_redis_instance" "my_memorystore_redis_instance" { name = "myinstance" tier = "BASIC" memory_size_gb = 2 region = "us-central1" redis_version = "REDIS_6_X" }
(可选)将以下输出值添加到 Terraform 配置文件中,以输出 Redis 实例的 IP 地址,本快速入门稍后会用到此地址:
output "host" { description = "The IP address of the instance." value = "${google_redis_instance.my_memorystore_redis_instance.host}" }
运行
terraform init
。运行
terraform plan
,并查看要创建的资源。运行
terraform apply
以创建。
从 Compute Engine 虚拟机连接到 Redis 实例
接下来,连接到新创建的 Redis 实例。
您可以从任何具有支持的 RFC 1918 IP 地址且使用 Redis 实例的授权网络的 Compute Engine 虚拟机连接到 Redis 实例。
如果您还没有与 Redis 实例使用同一授权网络的 Compute Engine 虚拟机,请创建一个虚拟机并按照 Linux 虚拟机使用快速入门中的说明连接到该虚拟机。
使用
apt-get
安装telnet
:sudo apt-get install telnet
从该终端通过 telnet 连接到 Redis 实例的 IP 地址,并将 variables 替换为适当的值。
telnet instance-ip-address 6379
如果成功,该命令将返回以下结果:
Trying instance-ip-address… Connected to instance-ip-address
在 telnet 会话中,输入一些 Redis 命令:
输入:
PING
结果:
PONG
输入
SET HELLO WORLD
结果:
+OK
请输入:
GET HELLO
结果:
$5 WORLD
清理
为避免系统因本快速入门中使用的资源向您的 Google Cloud 账号收取费用,请按照以下步骤删除 Redis 实例:
- 从 Terraform 配置文件中移除
google_redis_instance
资源。 - 运行 Terraform
init
、plan
和apply
以销毁 Redis 资源。 - 删除您为本快速入门创建的任何 Compute Engine 虚拟机。
后续步骤
- 详细了解如何创建和管理实例。
- 了解其他连接到 Redis 实例的方式。
- 了解 Redis 实例的特性。