简体   繁体   中英

Using Terraform to add OpenStack Security Group to instance not managed by Terraform

I'm trying to add security groups and new rules to an instance by using Terraform. Note that this instance is not being managed by Terraform. The issue I run into is that when I apply it it creates a new instance.

My Terraform code is as follows:

resource "openstack_compute_secgroup_v2" "secgroup_1" {
  name = "my_secgroup"
  region = "${var.region}"
  description = "my security group"

  rule {
    from_port = 22
    to_port = 22
    ip_protocol = "tcp"
    cidr = "x.x.x.x/x"
  }

  rule {
    from_port = 80
    to_port = 80
    ip_protocol = "tcp"
    cidr = "x.x.x.x/x"
  }
}

resource "openstack_compute_instance_v2" "myresource" {
  name = "<Name of MY Instance>"
  flavor_name = "m1.medium"
  region = "${var.region}"
  image_id = "<Image I.D of existing instance>"
  security_groups = ["${openstack_compute_secgroup_v2.secgroup_1.name}"]
}

Your Terraform code is meant to be creating a new instance on your OpenStack cluster. To have Terraform manage a resource it must be included in its state file. When you create a resource with Terraform then Terraform will automatically put it inside the state file and then begin to manage that resource.

Since Terraform 0.7 many resources can now be imported into the state file like this:

$ terraform import aws_instance.web i-12345678

If you had some Terraform code like this (from the aws_instance documentation ):

provider "aws" {
    region = "us-west-2"
}

data "aws_ami" "ubuntu" {
  most_recent = true
  filter {
    name = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
  }
  filter {
    name = "virtualization-type"
    values = ["hvm"]
  }
  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
    ami = "${data.aws_ami.ubuntu.id}"
    instance_type = "t2.micro"
    tags {
        Name = "HelloWorld"
    }
}

And already had a pre-existing instance with an instance id of i-12345678 then Terraform would have imported that instance and now running a plan of the above code should show no changes instead of creating the web instance.

Unfortunately it looks like OpenStack support isn't as mature as AWS and so (as of 0.7.7) there is not currently any support for importing OpenStack instance resources directly using the import command. However, the import command is simply making it easier to manipulate the state file without breaking things and so you can just edit the state file to include the resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM