Terraform: Connecting Resources using Remote State

  • To create a AWS Security Group using a terraform script and have the state stored in a AWS S3 bucket.
  • Create an EC2 instance using another terraform script and link it to the Security Group created in previous script via the Remote State from S3.
provider "aws" {
region = "us-east-2"
}

#configure the created S3 bucket to save the remote storage.
terraform {
backend "s3" {
bucket = "gpm-tfstatestorage-s3"
key = "global/s3/sg.terraform.tfstate"
region = "us-east-2"
}
}

resource "aws_security_group" "Web_Srv_SG" {
name = "Web_Srv_SG"
#to utilize the varaiables make sure that variable.tf file is created
ingress {
from_port = "8080"
to_port = "8080"
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}

output "Web_Srv_SG_id" {
description = "output Id of the service plan"
value = aws_security_group.Web_Srv_SG.id
}
provider "aws" {
region = "us-east-2"
}

locals {
instanceName = "test-instance"
}

data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "gpm-tfstatestorage-s3"
key = "global/s3/sg.terraform.tfstate"
region = "us-east-2"
}
}

resource "aws_instance" "example-ec2"{
ami = "ami-028f0daffc74d96ee"
instance_type = "t2.micro"
vpc_security_group_ids = [data.terraform_remote_state.network.outputs.Web_Srv_SG_id]
tags = {
Name = local.instanceName
Sg = data.terraform_remote_state.network.outputs.Web_Srv_SG_id
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why I chose to study Software Engineering

Why Use an External Cron Job, Not WordPress Cron Job

How are 79.34% codes of double 11 modules generated intelligently

ESP32: TLS (Transport Layer Security) And IoT Devices

How To Start Using Hostinger Web Hosting

What is recursion in programming ?

Open Source 100: George Goldberg, Mattermost Core Committer

How to deploy a Rails 5.2 PostgreSQL app on AWS Elastic Beanstalk

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Godfrey Menezes

Godfrey Menezes

More from Medium

Terraform Basics

Executing Terraform Scripts on CI/CD Pipeline using Self-Hosted Runners

How to Deploy Amazon WorkSpaces in AWS using Terraform