skip to Main Content

My terraform security local ec2 module looks like so

resource "aws_instance" "mysql" {
  ami           = data.aws_ami.latest_amazon_linux.id
  instance_type = var.instance_type                # override this at module call
  key_name = aws_key_pair.my_local_pubkey.key_name # override this at module call
  vpc_security_group_ids = [var.default_sg]        # override security group at module call

}

and when i reference it in main.tf to override the vpc_security_group_ids like so

module "ec2" {
  source                 = "./modules/ec2"
  instance_type          = "t2.medium"
  vpc_security_group_ids = [module.security_group.sg_id]
}

I get an error saying vpc_security_group_ids not expected here.

2

Answers


  1. If you are creating Instances in a VPC, you will use vpc_security_group_ids.
    if you are using default VPC, then the entry should be just security_groups.
    so that line should be
    security_groups = [var.default_sg] in the resource and security_groups = [module.security_group.sg_id] in the module.

    Login or Signup to reply.
  2. There are at least two issues with the current code:

    1. the variable name you defined in the module is not provided a value with the module call, i.e., that is why terraform is telling you that it is not expecting an argument called vpc_security_group_ids, since the argument name is actually default_sg
    2. you have probably defined the default_sg variable as a string, and you are trying to pass a list. This is how you are passing the default_sg to vpc_security_group_ids: vpc_security_group_ids = [var.default_sg]. And in the module call you are using vpc_security_group_ids = [module.security_group.sg_id], which means the value passed to whatever is the module argument will already be a list.

    To fix these issues, you need the following:

    module "ec2" {
      source        = "./modules/ec2"
      instance_type = "t2.medium"
      default_sg    = module.security_group.sg_id
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search