简体   繁体   中英

Is it possible to execute a CloudFormation file in Terraform?

One team has already written a cloudformation template as a .yml file that provisions a stack of resources.

Is it possible to leverage this file by executing it from within Terraform? Or does it have to be rewritten?

I'm new to terraform and just getting started.

If I were using the AWS CLI I would execute a command like this,

aws cloudformation create-stack --stack-name my-new-stack --template-body file://mystack.yml --parameters ParameterKey=AmiId

I'd like to include the equivalent of this command in my terraform configuration.

If it is possible and you can point me to an example, I would really appreciate that.

Thanks!

The aws_cloudformation_stack resource serves as a bridge from Terraform into CloudFormation, which can be used either as an aid for migration from CloudFormation to Terraform (as you're apparently doing here) or to make use of some of CloudFormation's features that Terraform doesn't currently handle, such as rolling deployments of new instances into an ASG .

resource "aws_cloudformation_stack" "example" {
  name = "example"
  parameters = {
    VpcId = var.vpc_id
  }
  template_body = file("${path.module}/example.yml")
}

The parameters argument allows passing data from Terraform into the Cloudformation stack. It's also possible to use the outputs attribute to make use of the results of the CloudFormation stack elsewhere in Terraform, for a two-way integration:

resource "aws_route_53_record" "example" {
  name = "service.example.com"
  type = "CNAME"
  ttl  = 300

  records = [
    aws_cloudformation_stack.example.outputs["ElbHostname"],
  ]
}

If you have a pre-existing CloudFormation stack that isn't managed by Terraform, you can still make use of its outputs using the aws_cloudformation_stack data source :

data "aws_cloudformation_stack" "example" {
  name = "example"
}

resource "aws_route_53_record" "example" {
  name = "service.example.com"
  type = "CNAME"
  ttl  = 300

  records = [
    data.aws_cloudformation_stack.example.outputs["ElbHostname"],
  ]
}

These features together allow you to effectively mix CloudFormation and Terraform in a single system in different combinations, whether it's as a temporary measure while migrating or permanently in situations where a hybrid solution is desired.

I can confirm that template_body with a file reference to a cloudformation template works. I assume template_url will also work great. Example

resource "aws_cloudformation_stack" "my-new-stack" {
  name = "my-new-stack"
  parameters {
    Name="my-new-stack"
    Port="22"
    VpcId = "${var.vpc_id}"
  }
  template_body = "${file("${path.module}/mystack.yml")}"
}

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