'Access a private docker registry with ECS Fargate and Terraform

I need my ECS Task definition to contain the credentials of my private Docker registry, using if possible a simple token, or, a user:password.

Below is my code:

resource "aws_secretsmanager_secret" "docker_registry_secret" {
  name_prefix = "/my_environment/registry/pwd"
}

resource "aws_secretsmanager_secret_version" "docker_registry_secret_version" {
  secret_id     = aws_secretsmanager_secret.docker_registry_secret.id
  secret_string = xxxMYTOKENxxx
}

resource "aws_iam_role_policy" "password_policy_secretsmanager" {
  name = "${var.task_name}-secretsmanager"
  role = aws_iam_role.MY_ECS_ROLE.id

  policy = <<-EOF
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": [
          "secretsmanager:GetSecretValue"
        ],
        "Effect": "Allow",
        "Resource": [
          "${aws_secretsmanager_secret.docker_registry_secret.arn}",
        ]
      }
    ]
  }
  EOF
}

resource "aws_ecs_task_definition" "task_to_be_scheduled" {
  .....
  ....
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  container_definitions = jsonencode([
    {
      "repositoryCredentials" : {
        "credentialsParameter" : aws_secretsmanager_secret.docker_registry_secret.arn
      },
      ....
      ....
  ])
}

However, when I launch my task, I have the following error on my ECS: unable to unmarshal secret value of authorization data from asm

I'm pretty sure the error is related to secret manager, but not sure where exactly. Any idea what I'm doing wrong?



Solution 1:[1]

I hope this answer can help someone else. I did two mistakes:

  1. In my task definition, I only had the execution_role_arn field set. I forgot to add the task_role_arn.
# before

resource "aws_ecs_task_definition" "task_to_be_scheduled" {
  execution_role_arn       = aws_iam_role.ecs_role.arn
  ....
}

# after

resource "aws_ecs_task_definition" "task_to_be_scheduled" {
  execution_role_arn       = aws_iam_role.ecs_role.arn
  task_role_arn            = aws_iam_role.ecs_role.arn
  ....
}
  1. I was using a token as the credentialsParameter instead of something such as {"username" : "gitlab-ci-token", "password" : "your-password"}
# before

container_definitions = jsonencode([
    {
      "repositoryCredentials" : {
        "credentialsParameter" : "any-token-as-string"
      },
   ....
}]

# after

container_definitions = jsonencode([
    {
      "repositoryCredentials" : {
        "credentialsParameter" : {"username" : "gitlab-ci-token", "password" : "your-password"}
      },
   ....
}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nolw38