def groupWithTags()

in magenta-lib/src/main/scala/magenta/tasks/AWS.scala [546:591]


  def groupWithTags(
      tagRequirements: List[TagRequirement],
      client: AutoScalingClient,
      reporter: DeployReporter,
      strategy: Strategy = Strategy.MostlyHarmless
  ): Option[AutoScalingGroup] = {
    case class ASGMatch(app: App, matches: List[AutoScalingGroup])

    def hasExactTagRequirements(
        asg: AutoScalingGroup,
        requirements: List[TagRequirement]
    ): Boolean = {
      val tags = asg.tags.asScala
      requirements.forall {
        case TagMatch(key, value) =>
          tags.exists(t => t.key == key && t.value == value)
        case TagExists(key) => tags.exists(_.key == key)
        case TagAbsent(key) => tags.forall(_.key != key)
      }
    }

    def listAutoScalingGroups(): List[AutoScalingGroup] = {
      val result = client.describeAutoScalingGroupsPaginator()
      result.autoScalingGroups.asScala.toList
    }

    val groups = listAutoScalingGroups()

    val matches = groups.filter(hasExactTagRequirements(_, tagRequirements))
    matches match {
      case Nil if strategy == Strategy.Dangerous =>
        reporter.info(
          s"Unable to locate an autoscaling group AND living dangerously - we'll assume you're creating a new stack"
        )
        None
      case Nil =>
        reporter.fail(
          s"No autoscaling group found with tags $tagRequirements. Creating a new stack? Initially choose the ${Strategy.Dangerous} strategy."
        )
      case List(singleGroup) => Some(singleGroup)
      case groupList =>
        reporter.fail(
          s"More than one autoscaling group match for $tagRequirements (${groupList.map(_.autoScalingGroupARN).mkString(", ")}). Failing fast since this may be non-deterministic."
        )
    }
  }