Bootstrap FreeKB - Amazon Web Services (AWS) - List Security Groups using Terraform
Amazon Web Services (AWS) - List Security Groups using Terraform


A Security Group is used to allow or deny requests coming in (ingress) and/or requests going out (egress). For example, a Security Group could be used to only allow requests within a certain IP address range to come in (ingress) and go out (egress) of an EC2 Instance.

 

Let's say you have a Security Group named "security group for port 443".

 

Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── security_groups (directory)
│   ├── data.tf
│   ├── outputs.tf
│   ├── provider.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

data.tf could have something like this.

data "aws_security_group" "default-security-group" {
  filter {
    name = "group-name"
    values = ["default"]
  }
  filter {
    name = "tag:Name"
    values = ["default"]
  }
}

 

outputs.tf could then have the following.

output "default_security_group" {
  value = data.aws_security_group.default-security-group
}

 

The terraform refresh command should then output something like this.

default-security-group-id = "sg-05c4058e9f135e234"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 2e92c1 in the box below so that we can be sure you are a human.