Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terraform > forces new resource on security group

Tags:

terraform

I've got a very simple piece of Terraform code:

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

module ec2 {
  source = "./ec2_instance"
  name = "EC2 Instance 1"
} 

where the module is:

variable "name" {
    default = "Default Name from ec2_instance.tf"
}

resource "aws_instance" "example" {
  ami = "ami-e5083683"
  instance_type = "t2.nano"
  subnet_id = "subnet-3e976259"
  associate_public_ip_address = true
  security_groups = [ "sg-7310e10b" ]
  tags {
    Name = "${var.name}"
  }
}

When I first run it I get this output:

security_groups.#:            "" => "1"
security_groups.1642973399:   "" => "sg-7310e10b"

However, the next time I try a plan I get:

  security_groups.#:            "0" => "1" (forces new resource)
  security_groups.1642973399:   "" => "sg-7310e10b" (forces new resource)

What gives?!

like image 355
Snowcrash Avatar asked Jul 24 '18 11:07

Snowcrash


People also ask

How do you prevent force replacement in Terraform?

With VPC based instances AWS allowed users to modify instance security groups without replacing the instance and so exposed a different way of specifying this in the API. If you move to using vpc_security_group_ids instead of security_groups then you will be able to modify these without replacing your instances.

How do you allow all traffic in a security group in Terraform?

In your ingress rule specification set self = true to allow traffic inside your Security Group. To allow traffic from a different Security Group, use the security_groups parameter. In both cases you can leave out the cidr_blocks parameter.

How do I add an EC2 instance to a security group in Terraform?

To enable access to the EC2 instance's web server, you must define a security group that allows ingress traffic on port 80 and all egress traffic, and associate the security group with your instance. Open the AWS Provider documentation page. Search for security_group and select the aws_security_group resource.

What is force replacement in Terraform?

Using Terraform replace command If you want to force replacement of an object even though there are no configuration changes, use the terraform plan or terraform apply command with the -replace option instead. If you are using an older version of Terraform, continue using the terraform taint command.


1 Answers

You are incorrectly assigning a vpc_security_group_id into security_groups, instead of into vpc_security_group_ids.

Change

security_groups = [ "sg-7310e10b" ]

to

vpc_security_group_ids = [ "sg-7310e10b" ]

and everything will be ok.

like image 123
Don Avatar answered Sep 25 '22 15:09

Don