Is it possible to execute a CloudFormation file in Terraform?

user1521567 picture user1521567 · Apr 7, 2017 · Viewed 10.1k times · Source

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!

Answer

Martin Atkins picture Martin Atkins · Apr 7, 2017

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.