Skip to content

Latest commit

 

History

History
128 lines (90 loc) · 2.96 KB

LAB06-Data-Sources-EC2.md

File metadata and controls

128 lines (90 loc) · 2.96 KB

LAB-06: Data Sources with Depends_on => Provision EC2

This scenario shows:

  • how to use Data Source to fetch/retrieve data (existed resource information) from AWS

Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/data-sources/main.tf

Prerequisite

Steps

  • With data sources, existed resource information can be fetched/retrieved.
  • "filter" provide to select/filter the existed instances
  • "depends_on" provide to run the data block after resource created
...
data "aws_instance" "data_instance" {
    filter {
      name = "tag:Name"
      values = ["Basic Instance"]
    }

    depends_on = [
      aws_instance.instance
    ]
} 

output "instance_info" {
  value = data.aws_instance.data_instance
}
...

image

  • Create main.tf:
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
	region = "eu-central-1"
}

resource "aws_instance" "instance" {
	ami           = "ami-0d1ddd83282187d18" # Ubuntu 22.04 eu-central-1 Frankfurt
	instance_type = "t2.nano"

	tags = {
		Name = "Basic Instance"
	}
}

# filter/select the existed instances
# depends_on if aws_instance.instance is created

data "aws_instance" "data_instance" {
    filter {
      name = "tag:Name"
      values = ["Basic Instance"]
    }

    depends_on = [
      aws_instance.instance
    ]
} 

output "instance_info" {
  value = data.aws_instance.data_instance
}

output "instance_public_ip" {
  value = data.aws_instance.data_instance.public_ip
}

Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/data-sources/main.tf

image

  • Run init, validate command:
terraform init
terraform validate
  • Run plan, apply command:
terraform plan
terraform apply

image

image

  • With output, details can be viewed:

image

image

  • Destroy infrastructure:
terraform destroy 

image

image