anothernewbiecoder
anothernewbiecoder

Reputation: 65

How to create ECR Repo before ECS with Terraform

Current Issue:

I am working with Terraform, and I am deploying AWS ECS with Fargate. I have all the applicable .tf files to do all of this, and they work, but I am also automating the deployment. So, first I would need to apply the ecr.tf file to create the ECR repo, then push the docker image to the repo, and then I get the repository_url attribute from the ECR resource to build the infrastructure for the ECS and Fargate. The issue I am having is that I have a deployment folder with all the .tf files, and I only want to apply my network/ecs/fargate files after I have set up my ecr resource by applying my ecr.tf and provider.tf. None of the things I have tried below are working so if anyone has any help they could provide that would be great.

Files:

root main.tf

variable "aws_region" {
  description = "Which region should the resources be deployed into?"
}

provider "aws" {
  shared_credentials_files = ["~/.aws/credentials"]
  shared_config_files = ["~/.aws/config"]
}

module "ecr" {
  source = "./ecr"
}

module "ecs" {
  source = "./ecs"
  aws_region = var.aws_region
  repository_url = module.ecr.repository_url
}

ecr.tf

resource "aws_ecr_repository" "ecr_repo" {
  name = "ecr-automation"
}

output "repository_url" {
  value = aws_ecr_repository.ecr_repo.repository_url
}

provider.tf

variable "aws_region" {
  description = "Which region should the resources be deployed into?"
}

provider "aws" {
  shared_credentials_files = *****
  shared_config_files = ****
}

Solutions I have tried:

  1. Using terraform apply -target=file. This didn't throw errors but the ECR repo was also not created.

  2. Create a main module with a main.tf file. Separate the ECR files and ECS files into their own separate modules, and include them in the main.tf file. Outputting the repository_url from the ecr.tf file, and accessing that from the main.tf file within the ecs module so that I can pass it to the files that need it. This is shown in my code example above, and is giving me the unsupported argument error. I assume I am doing it wrong, but I don't know how to fix it.

Upvotes: 3

Views: 1199

Answers (1)

Arunas Bart
Arunas Bart

Reputation: 2678

try to use depends_on = [module.ecr] inside ecs module:

module "ecs" {
  source = "./ecs"
  aws_region = var.aws_region
  repository_url = module.ecr.repository_url
  depends_on = [module.ecr]
}

Note: Module support for depends_on was added in Terraform version 0.13, and prior versions can only use it with resources.

https://developer.hashicorp.com/terraform/language/meta-arguments/depends_on

Upvotes: 1

Related Questions