Is it possible to execute a CloudFormation file in Terraform?

浪尽此生 提交于 2020-12-29 03:23:43

问题


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!


回答1:


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.




回答2:


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")}"
}


来源:https://stackoverflow.com/questions/43266506/is-it-possible-to-execute-a-cloudformation-file-in-terraform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!