第13天:Terraform 中的数据源

发布: (2025年12月8日 GMT+8 02:43)
2 min read
原文: Dev.to

Source: Dev.to

什么是数据源?

您可以使用数据源来获取现有 VPC、子网、AMI、安全组等信息。

data "data_source_type" "data_source_name" {
  # Configuration arguments
}

过滤器

filter {
  name   = "filter_name"
  values = ["value1", "value2"]
}

通过数据源获取 AMI ID 并通过数据源获取子网 ID 来创建 EC2 实例

// main.tf

# Fetch the latest Ubuntu AMI
data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  owners = ["amazon"] # Canonical
}

# Fetch existing VPC by Name tag
data "aws_vpc" "selected" {
  filter {
    name   = "tag:Name"
    values = ["shared-primary-vpc"]
  }
}

# Fetch existing Subnet by Name tag within the selected VPC
data "aws_subnet" "selected" {
  filter {
    name   = "tag:Name"
    values = ["shared-primary-subnet"]
  }
  vpc_id = data.aws_vpc.selected.id
}

# Create an EC2 instance using the fetched AMI and Subnet
resource "aws_instance" "example" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  subnet_id     = data.aws_subnet.selected.id

  tags = {
    Name = "day-13-instance"
  }
}

输出

// outputs.tf
output "instance_id" {
  value = aws_instance.example.id
}

output "instance_public_ip" {
  value = aws_instance.example.public_ip
}

该 Terraform 配置使用数据源获取最新的 Ubuntu AMI 和现有子网信息,以创建 EC2 实例。

Back to Blog

相关文章

阅读更多 »

Terraform 数据源 (AWS)

Terraform 数据源是什么?Terraform 中的数据源是对现有资源的只读查找。Terraform 并不是创建新资源,而是查询…

第13天:Terraform 数据源

数据源 将数据源想象成一个电话簿,其中用户名和电话号码以键值对的形式通过 API 访问。不要将值硬编码……