terraform import for AWS security_group_rule

618 views
Skip to first unread message

YM

unread,
Oct 18, 2017, 11:01:58 AM10/18/17
to Terraform
When I "terraform import" a security_group, "terraform plan" with original tf config file implies that its security_group_rules("sgr") will be re-built instead of seeing no changes.
I found it is because "terraform import" imports sgrs under different resource names when importing a security-group.
(confirmed tf-versions: 0.10.7/0.9.6)

Here's a configuration example

$ cat main.tf
resource
"aws_security_group" "group" {
  name          
= "simple-security"
  description  
=  "Managed by TF"
  vpc_id        
= "vpc-XXXXXXXX"

  tags
{
   
ResourceTag = "simple-security"
 
}
}

resource
"aws_security_group_rule" "ingress" {
  security_group_id
= "${aws_security_group.group.id}"
  type
= "ingress"
  protocol
= "-1"
  from_port
= 0
  to_port
= 0
  cidr_blocks
= ["10.0.0.0/8"]
}

resource
"aws_security_group_rule" "ingress_self" {
  security_group_id
= "${aws_security_group.group.id}"
  type
= "ingress"
  from_port
= 0
  to_port
= 0
  protocol
= "-1"
 
self = true
}

resource
"aws_security_group_rule" "egress_all" {
  security_group_id
= "${aws_security_group.group.id}"
  type
= "egress"
  from_port
= 0
  to_port
= 0
  protocol
= "-1"
  cidr_blocks
= ["0.0.0.0/0"]
}

After terraform apply, the resource names are:

$ terraform state list
aws_security_group
.group
aws_security_group_rule
.egress_all
aws_security_group_rule
.ingress
aws_security_group_rule
.ingress_self

Then (after moving original terraform.state and) run "terraform import":

$ terraform import aws_security_group.group sg-a8ca50d5

aws_security_group.group: Importing from ID "sg-a8ca50d5"...
aws_security_group.group: Import complete!
 Imported aws_security_group (ID: sg-a8ca50d5)
 Imported aws_security_group_rule (ID: sgrule-91562506)
 Imported aws_security_group_rule (ID: sgrule-3322330390)
 Imported aws_security_group_rule (ID: sgrule-913295028)
aws_security_group_rule.group: Refreshing state... (ID: sgrule-91562506)
aws_security_group.group: Refreshing state... (ID: sg-a8ca50d5)
aws_security_group_rule.group-2: Refreshing state... (ID: sgrule-913295028)
aws_security_group_rule.group-1: Refreshing state... (ID: sgrule-3322330390)

And as you can see the output above sgr names are now different from the original
$ terraform state list
aws_security_group
.group
aws_security_group_rule
.group
aws_security_group_rule
.group-1
aws_security_group_rule
.group-2

So the question is,
Is there a way to import sgrs under correct(=intended) names when importing a security_group?
If it's not possible, what would be the best way to match imported sgrs in generated tfstate file
with sgr names in original config(.tf) file (I mean, I need to do it programatically)?

Thanks in advance!
Yukio

Reply all
Reply to author
Forward
0 new messages