Skip to content

Provision Infrastructure 使用 Terraform

入门 约 25 分钟

你将构建什么

Terraform 配置那个创建 AWS S3 bucket 使用 versioning 启用, using declarative Infrastructure as Code.

学习目标

  • 理解 Terraform 配置语法 (HCL)
  • 编写 Terraform 配置到 创建 S3 bucket
  • 运行 terraform 计划 and apply 到 provision resources
  • 理解 Terraform 状态 management

前置要求

  • Terraform 安装 on 你的 machine
  • AWS account 使用 access 键配置
  • 基础理解的 cloud resources

步骤

  1. 1

    配置 AWS provider

    创建 主要.tf file 那个配置 AWS provider and 设置区域. 这个 tells Terraform 哪个 cloud 到 use.

    代码
    provider "aws" {
      region = "us-east-1"
    }

    预期结果

    主要.tf file 使用 AWS provider 配置.

  2. 2

    定义 S3 bucket resource

    添加 resource 块那个创建 S3 bucket 使用唯一 name and versioning 启用.

    代码
    resource "aws_s3_bucket" "my_bucket" {
      bucket = "my-terraform-bucket-12345"
    }
    
    resource "aws_s3_bucket_versioning" "my_bucket" {
      bucket = aws_s3_bucket.my_bucket.id
      versioning_configuration {
        status = "Enabled"
      }
    }

    预期结果

    Terraform 配置现在定义 S3 bucket 使用 versioning.

  3. 3

    计划 and apply

    运行 terraform init 到 initialize, terraform 计划 到 see 什么将 是创建, 然后 terraform apply 到创建 bucket.

    代码
    terraform init
    terraform plan
    terraform apply

    预期结果

    Terraform 创建 S3 bucket in 你的 AWS account. 验证 in AWS console.

  4. 4

    Clean 上

    当你 是做, 运行 terraform destroy 到移除 bucket and avoid charges.

    代码
    terraform destroy

    预期结果

    S3 bucket 是删除从 你的 AWS account.

  5. 5

    添加健康检查端点

    为应用添加 /health 端点返回 200 OK,供编排系统(Kubernetes、负载均衡器)探测存活。健康检查是生产部署的基础设施。

    代码
    # app.py (Flask example)
    from flask import Flask, jsonify
    app = Flask(__name__)
    
    @app.route("/health")
    def health():
        return jsonify({"status": "ok"}), 200
    
    @app.route("/ready")
    def ready():
        # Check DB connection etc.
        return jsonify({"ready": True}), 200

    预期结果

    curl localhost:5000/health 返回 {"status":"ok"} 和 200 状态码。

自己动手试试

你学到了什么

你 used Terraform 到 provision cloud infrastructure as code. 这个方法制作 infrastructure reproducible, version-controlled, and 简单到 manage.

相关资源

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题