providerBlock static method

Map<String, dynamic>? providerBlock(
  1. Stack stack
)

The top-level provider { ... } value, or null when no block is needed.

A provider name registered once, without an alias, keeps the map form ("google": {"project": ...}), omitted when it has no config args. A name with aliases takes the list form Terraform JSON uses for repeated provider blocks — one entry per registered configuration in registration order, the aliased ones carrying "alias"; a default configuration with no args is left out (Terraform supplies it).

Implementation

static Map<String, dynamic>? providerBlock(Stack stack) {
  final byName = <String, List<StackProvider>>{};
  for (final p in stack.providers) {
    // A configuration alias is declared on required_providers, not as a
    // provider block: the calling module passes the configuration. An
    // external configuration lives in a file beside main.tf.json.
    if (stack.isConfigurationAlias(p) || stack.isExternalProvider(p)) {
      continue;
    }
    byName.putIfAbsent(p.providerName, () => []).add(p);
  }
  final entries = <String, dynamic>{};
  for (final e in byName.entries) {
    final configs = e.value;
    if (configs.every((p) => p.alias == null)) {
      // Stack.validate: exactly one default configuration.
      final args = configs.single.configArgs;
      if (args.isEmpty) continue;
      entries[e.key] = Map<String, dynamic>.from(args);
      continue;
    }
    entries[e.key] = [
      for (final p in configs)
        if (p.alias != null || p.configArgs.isNotEmpty)
          <String, dynamic>{
            ...p.configArgs,
            if (p.alias != null) 'alias': p.alias,
          },
    ];
  }
  if (entries.isEmpty) return null;
  return entries;
}