Home > Mobile >  failed to create ec2 instance using terraform if set security group
failed to create ec2 instance using terraform if set security group

Time:10-01

I tried to create an EC2 instance. When I don't set security group, it's good, but when set security group it failed with the following message:

│ Error: creating EC2 Instance: InvalidParameterValue: Value () for parameter groupId is invalid. The value cannot be empty
│   status code: 400, request id: 2935799e-2364-4676-ba02-457740336cd1
│
│   with aws_instance.my_first_instance,
│   on main.tf line 44, in resource "aws_instance" "my_first_instance":
│   44: resource "aws_instance" "my_first_instance" {

The code is

 variable "ecs_cluster_name" {
  type    = string
  default = "production"
}

data "aws_ami" "ecs_ami" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-ecs-hvm-2.0.202*-x86_64-ebs"]
  }
}

output "ami_name" {
  value       = data.aws_ami.ecs_ami.name
  description = "the name of ecs ami"
}

output "security_group_id" {
  value       = aws_security_group.default.id
  description = "id of security group"
}


resource "aws_security_group" "default" {
  name = "terraform_Security_group"
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "my_first_instance" {
  ami           = data.aws_ami.ecs_ami.id
  instance_type = "t2.micro"

  # security_groups = ["sg-06e91dae98b2c44c6"]
  security_groups = [aws_security_group.default.id]

  user_data = <<-EOF
                #!/bin/bash
                echo ECS_CLUSTER={cluster_name} >> /etc/ecs/ecs.config
                EOF
}

CodePudding user response:

You should be using vpc_security_group_ids:

  vpc_security_group_ids = [aws_security_group.default.id]
  • Related