1. Packages
  2. Consul Provider
  3. API Docs
  4. getDatacenters
Consul v3.13.3 published on Wednesday, Nov 19, 2025 by Pulumi
consul logo
Consul v3.13.3 published on Wednesday, Nov 19, 2025 by Pulumi

    The consul.getDatacenters data source returns the list of all knwown Consul datacenters.

    Example Usage

    import * as pulumi from "@pulumi/pulumi";
    import * as consul from "@pulumi/consul";
    import * as std from "@pulumi/std";
    
    export = async () => {
        const all = await consul.getDatacenters({});
        // Register a prepared query in each of the datacenters
        const myapp_query: consul.PreparedQuery[] = [];
        for (const range of std.toset({
            input: all.datacenters,
        }).result.map((v, k) => ({key: k, value: v}))) {
            myapp_query.push(new consul.PreparedQuery(`myapp-query-${range.key}`, {
                name: "myquery",
                datacenter: range.key,
                onlyPassing: true,
                near: "_agent",
                service: "myapp",
                tags: [
                    "active",
                    "!standby",
                ],
                failover: {
                    nearestN: 3,
                    datacenters: [
                        "us-west1",
                        "us-east-2",
                        "asia-east1",
                    ],
                },
                dns: {
                    ttl: "30s",
                },
            }));
        }
    }
    
    import pulumi
    import pulumi_consul as consul
    import pulumi_std as std
    
    all = consul.get_datacenters()
    # Register a prepared query in each of the datacenters
    myapp_query = []
    for range in [{"key": k, "value": v} for [k, v] in enumerate(std.toset(input=all.datacenters).result)]:
        myapp_query.append(consul.PreparedQuery(f"myapp-query-{range['key']}",
            name="myquery",
            datacenter=range["key"],
            only_passing=True,
            near="_agent",
            service="myapp",
            tags=[
                "active",
                "!standby",
            ],
            failover={
                "nearest_n": 3,
                "datacenters": [
                    "us-west1",
                    "us-east-2",
                    "asia-east1",
                ],
            },
            dns={
                "ttl": "30s",
            }))
    
    package main
    
    import (
    	"github.com/pulumi/pulumi-consul/sdk/v3/go/consul"
    	"github.com/pulumi/pulumi-std/sdk/go/std"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		all, err := consul.GetDatacenters(ctx, map[string]interface{}{}, nil)
    		if err != nil {
    			return err
    		}
    		// Register a prepared query in each of the datacenters
    		var myapp_query []*consul.PreparedQuery
    		for key0, _ := range interface{}(std.Toset(ctx, &std.TosetArgs{
    			Input: all.Datacenters,
    		}, nil).Result) {
    			__res, err := consul.NewPreparedQuery(ctx, fmt.Sprintf("myapp-query-%v", key0), &consul.PreparedQueryArgs{
    				Name:        pulumi.String("myquery"),
    				Datacenter:  pulumi.Float64(key0),
    				OnlyPassing: pulumi.Bool(true),
    				Near:        pulumi.String("_agent"),
    				Service:     pulumi.String("myapp"),
    				Tags: pulumi.StringArray{
    					pulumi.String("active"),
    					pulumi.String("!standby"),
    				},
    				Failover: &consul.PreparedQueryFailoverArgs{
    					NearestN: pulumi.Int(3),
    					Datacenters: pulumi.StringArray{
    						pulumi.String("us-west1"),
    						pulumi.String("us-east-2"),
    						pulumi.String("asia-east1"),
    					},
    				},
    				Dns: &consul.PreparedQueryDnsArgs{
    					Ttl: pulumi.String("30s"),
    				},
    			})
    			if err != nil {
    				return err
    			}
    			myapp_query = append(myapp_query, __res)
    		}
    		return nil
    	})
    }
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Pulumi;
    using Consul = Pulumi.Consul;
    using Std = Pulumi.Std;
    
    return await Deployment.RunAsync(async() => 
    {
        var all = await Consul.GetDatacenters.InvokeAsync();
    
        // Register a prepared query in each of the datacenters
        var myapp_query = new List<Consul.PreparedQuery>();
        foreach (var range in )
        {
            myapp_query.Add(new Consul.PreparedQuery($"myapp-query-{range.Key}", new()
            {
                Name = "myquery",
                Datacenter = range.Key,
                OnlyPassing = true,
                Near = "_agent",
                Service = "myapp",
                Tags = new[]
                {
                    "active",
                    "!standby",
                },
                Failover = new Consul.Inputs.PreparedQueryFailoverArgs
                {
                    NearestN = 3,
                    Datacenters = new[]
                    {
                        "us-west1",
                        "us-east-2",
                        "asia-east1",
                    },
                },
                Dns = new Consul.Inputs.PreparedQueryDnsArgs
                {
                    Ttl = "30s",
                },
            }));
        }
    });
    
    package generated_program;
    
    import com.pulumi.Context;
    import com.pulumi.Pulumi;
    import com.pulumi.core.Output;
    import com.pulumi.consul.ConsulFunctions;
    import com.pulumi.consul.PreparedQuery;
    import com.pulumi.consul.PreparedQueryArgs;
    import com.pulumi.consul.inputs.PreparedQueryFailoverArgs;
    import com.pulumi.consul.inputs.PreparedQueryDnsArgs;
    import com.pulumi.codegen.internal.KeyedValue;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.io.File;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class App {
        public static void main(String[] args) {
            Pulumi.run(App::stack);
        }
    
        public static void stack(Context ctx) {
            final var all = ConsulFunctions.getDatacenters(%!v(PANIC=Format method: runtime error: invalid memory address or nil pointer dereference);
    
            // Register a prepared query in each of the datacenters
            for (var range : KeyedValue.of(com.pulumi.std.StdFunctions(TosetArgs.builder()
                .input(all.datacenters())
                .build()).result())) {
                new PreparedQuery("myapp-query-" + range.key(), PreparedQueryArgs.builder()
                    .name("myquery")
                    .datacenter(range.key())
                    .onlyPassing(true)
                    .near("_agent")
                    .service("myapp")
                    .tags(                
                        "active",
                        "!standby")
                    .failover(PreparedQueryFailoverArgs.builder()
                        .nearestN(3)
                        .datacenters(                    
                            "us-west1",
                            "us-east-2",
                            "asia-east1")
                        .build())
                    .dns(PreparedQueryDnsArgs.builder()
                        .ttl("30s")
                        .build())
                    .build());
            }
    
        }
    }
    
    resources:
      # Register a prepared query in each of the datacenters
      myapp-query:
        type: consul:PreparedQuery
        properties:
          name: myquery
          datacenter: ${range.key}
          onlyPassing: true
          near: _agent
          service: myapp
          tags:
            - active
            - '!standby'
          failover:
            nearestN: 3
            datacenters:
              - us-west1
              - us-east-2
              - asia-east1
          dns:
            ttl: 30s
        options: {}
    variables:
      all:
        fn::invoke:
          function: consul:getDatacenters
          arguments: {}
    

    Using getDatacenters

    Two invocation forms are available. The direct form accepts plain arguments and either blocks until the result value is available, or returns a Promise-wrapped result. The output form accepts Input-wrapped arguments and returns an Output-wrapped result.

    function getDatacenters(opts?: InvokeOptions): Promise<GetDatacentersResult>
    function getDatacentersOutput(opts?: InvokeOptions): Output<GetDatacentersResult>
    def get_datacenters(opts: Optional[InvokeOptions] = None) -> GetDatacentersResult
    def get_datacenters_output(opts: Optional[InvokeOptions] = None) -> Output[GetDatacentersResult]
    func GetDatacenters(ctx *Context, opts ...InvokeOption) (*GetDatacentersResult, error)
    func GetDatacentersOutput(ctx *Context, opts ...InvokeOption) GetDatacentersResultOutput

    > Note: This function is named GetDatacenters in the Go SDK.

    public static class GetDatacenters 
    {
        public static Task<GetDatacentersResult> InvokeAsync(InvokeOptions? opts = null)
        public static Output<GetDatacentersResult> Invoke(InvokeOptions? opts = null)
    }
    public static CompletableFuture<GetDatacentersResult> getDatacenters(InvokeOptions options)
    public static Output<GetDatacentersResult> getDatacenters(InvokeOptions options)
    
    fn::invoke:
      function: consul:index/getDatacenters:getDatacenters
      arguments:
        # arguments dictionary

    getDatacenters Result

    The following output properties are available:

    Datacenters List<string>
    The list of datacenters known. The datacenters will be sorted in ascending order based on the estimated median round trip time from the server to the servers in that datacenter.
    Id string
    The provider-assigned unique ID for this managed resource.
    Datacenters []string
    The list of datacenters known. The datacenters will be sorted in ascending order based on the estimated median round trip time from the server to the servers in that datacenter.
    Id string
    The provider-assigned unique ID for this managed resource.
    datacenters List<String>
    The list of datacenters known. The datacenters will be sorted in ascending order based on the estimated median round trip time from the server to the servers in that datacenter.
    id String
    The provider-assigned unique ID for this managed resource.
    datacenters string[]
    The list of datacenters known. The datacenters will be sorted in ascending order based on the estimated median round trip time from the server to the servers in that datacenter.
    id string
    The provider-assigned unique ID for this managed resource.
    datacenters Sequence[str]
    The list of datacenters known. The datacenters will be sorted in ascending order based on the estimated median round trip time from the server to the servers in that datacenter.
    id str
    The provider-assigned unique ID for this managed resource.
    datacenters List<String>
    The list of datacenters known. The datacenters will be sorted in ascending order based on the estimated median round trip time from the server to the servers in that datacenter.
    id String
    The provider-assigned unique ID for this managed resource.

    Package Details

    Repository
    HashiCorp Consul pulumi/pulumi-consul
    License
    Apache-2.0
    Notes
    This Pulumi package is based on the consul Terraform Provider.
    consul logo
    Consul v3.13.3 published on Wednesday, Nov 19, 2025 by Pulumi
      Meet Neo: Your AI Platform Teammate