1. Packages
  2. AWS
  3. API Docs
  4. ec2
  5. getInstances
AWS v6.60.0 published on Tuesday, Nov 19, 2024 by Pulumi

aws.ec2.getInstances

Explore with Pulumi AI

aws logo
AWS v6.60.0 published on Tuesday, Nov 19, 2024 by Pulumi

    Use this data source to get IDs or IPs of Amazon EC2 instances to be referenced elsewhere, e.g., to allow easier migration from another management solution or to make it easier for an operator to connect through bastion host(s).

    Note: It’s strongly discouraged to use this data source for querying ephemeral instances (e.g., managed via autoscaling group), as the output may change at any time and you’d need to re-run apply every time an instance comes up or dies.

    Example Usage

    import * as pulumi from "@pulumi/pulumi";
    import * as aws from "@pulumi/aws";
    
    export = async () => {
        const test = await aws.ec2.getInstances({
            instanceTags: {
                Role: "HardWorker",
            },
            filters: [{
                name: "instance.group-id",
                values: ["sg-12345678"],
            }],
            instanceStateNames: [
                "running",
                "stopped",
            ],
        });
        const testEip: aws.ec2.Eip[] = [];
        for (const range = {value: 0}; range.value < test.ids.length; range.value++) {
            testEip.push(new aws.ec2.Eip(`test-${range.value}`, {instance: test.ids[range.value]}));
        }
    }
    
    import pulumi
    import pulumi_aws as aws
    
    test = aws.ec2.get_instances(instance_tags={
            "Role": "HardWorker",
        },
        filters=[{
            "name": "instance.group-id",
            "values": ["sg-12345678"],
        }],
        instance_state_names=[
            "running",
            "stopped",
        ])
    test_eip = []
    for range in [{"value": i} for i in range(0, len(test.ids))]:
        test_eip.append(aws.ec2.Eip(f"test-{range['value']}", instance=test.ids[range["value"]]))
    
    package main
    
    import (
    	"github.com/pulumi/pulumi-aws/sdk/v6/go/aws/ec2"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		test, err := ec2.GetInstances(ctx, &ec2.GetInstancesArgs{
    			InstanceTags: map[string]interface{}{
    				"Role": "HardWorker",
    			},
    			Filters: []ec2.GetInstancesFilter{
    				{
    					Name: "instance.group-id",
    					Values: []string{
    						"sg-12345678",
    					},
    				},
    			},
    			InstanceStateNames: []string{
    				"running",
    				"stopped",
    			},
    		}, nil)
    		if err != nil {
    			return err
    		}
    		var testEip []*ec2.Eip
    		for index := 0; index < int(len(test.Ids)); index++ {
    			key0 := index
    			val0 := index
    			__res, err := ec2.NewEip(ctx, fmt.Sprintf("test-%v", key0), &ec2.EipArgs{
    				Instance: pulumi.String(test.Ids[val0]),
    			})
    			if err != nil {
    				return err
    			}
    			testEip = append(testEip, __res)
    		}
    		return nil
    	})
    }
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Pulumi;
    using Aws = Pulumi.Aws;
    
    return await Deployment.RunAsync(async() => 
    {
        var test = await Aws.Ec2.GetInstances.InvokeAsync(new()
        {
            InstanceTags = 
            {
                { "Role", "HardWorker" },
            },
            Filters = new[]
            {
                new Aws.Ec2.Inputs.GetInstancesFilterInputArgs
                {
                    Name = "instance.group-id",
                    Values = new[]
                    {
                        "sg-12345678",
                    },
                },
            },
            InstanceStateNames = new[]
            {
                "running",
                "stopped",
            },
        });
    
        var testEip = new List<Aws.Ec2.Eip>();
        for (var rangeIndex = 0; rangeIndex < test.Ids.Length; rangeIndex++)
        {
            var range = new { Value = rangeIndex };
            testEip.Add(new Aws.Ec2.Eip($"test-{range.Value}", new()
            {
                Instance = test.Ids[range.Value],
            }));
        }
    });
    
    package generated_program;
    
    import com.pulumi.Context;
    import com.pulumi.Pulumi;
    import com.pulumi.core.Output;
    import com.pulumi.aws.ec2.Ec2Functions;
    import com.pulumi.aws.ec2.inputs.GetInstancesArgs;
    import com.pulumi.aws.ec2.Eip;
    import com.pulumi.aws.ec2.EipArgs;
    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 test = Ec2Functions.getInstances(GetInstancesArgs.builder()
                .instanceTags(Map.of("Role", "HardWorker"))
                .filters(GetInstancesFilterArgs.builder()
                    .name("instance.group-id")
                    .values("sg-12345678")
                    .build())
                .instanceStateNames(            
                    "running",
                    "stopped")
                .build());
    
            for (var i = 0; i < test.applyValue(getInstancesResult -> getInstancesResult.ids()).length(); i++) {
                new Eip("testEip-" + i, EipArgs.builder()
                    .instance(test.applyValue(getInstancesResult -> getInstancesResult.ids())[range.value()])
                    .build());
    
            
    }
        }
    }
    
    Coming soon!
    

    Using getInstances

    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 getInstances(args: GetInstancesArgs, opts?: InvokeOptions): Promise<GetInstancesResult>
    function getInstancesOutput(args: GetInstancesOutputArgs, opts?: InvokeOptions): Output<GetInstancesResult>
    def get_instances(filters: Optional[Sequence[GetInstancesFilter]] = None,
                      instance_state_names: Optional[Sequence[str]] = None,
                      instance_tags: Optional[Mapping[str, str]] = None,
                      opts: Optional[InvokeOptions] = None) -> GetInstancesResult
    def get_instances_output(filters: Optional[pulumi.Input[Sequence[pulumi.Input[GetInstancesFilterArgs]]]] = None,
                      instance_state_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
                      instance_tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
                      opts: Optional[InvokeOptions] = None) -> Output[GetInstancesResult]
    func GetInstances(ctx *Context, args *GetInstancesArgs, opts ...InvokeOption) (*GetInstancesResult, error)
    func GetInstancesOutput(ctx *Context, args *GetInstancesOutputArgs, opts ...InvokeOption) GetInstancesResultOutput

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

    public static class GetInstances 
    {
        public static Task<GetInstancesResult> InvokeAsync(GetInstancesArgs args, InvokeOptions? opts = null)
        public static Output<GetInstancesResult> Invoke(GetInstancesInvokeArgs args, InvokeOptions? opts = null)
    }
    public static CompletableFuture<GetInstancesResult> getInstances(GetInstancesArgs args, InvokeOptions options)
    // Output-based functions aren't available in Java yet
    
    fn::invoke:
      function: aws:ec2/getInstances:getInstances
      arguments:
        # arguments dictionary

    The following arguments are supported:

    Filters List<GetInstancesFilter>
    One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out [describe-instances in the AWS CLI reference][1].
    InstanceStateNames List<string>
    List of instance states that should be applicable to the desired instances. The permitted values are: pending, running, shutting-down, stopped, stopping, terminated. The default value is running.
    InstanceTags Dictionary<string, string>
    Map of tags, each pair of which must exactly match a pair on desired instances.
    Filters []GetInstancesFilter
    One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out [describe-instances in the AWS CLI reference][1].
    InstanceStateNames []string
    List of instance states that should be applicable to the desired instances. The permitted values are: pending, running, shutting-down, stopped, stopping, terminated. The default value is running.
    InstanceTags map[string]string
    Map of tags, each pair of which must exactly match a pair on desired instances.
    filters List<GetInstancesFilter>
    One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out [describe-instances in the AWS CLI reference][1].
    instanceStateNames List<String>
    List of instance states that should be applicable to the desired instances. The permitted values are: pending, running, shutting-down, stopped, stopping, terminated. The default value is running.
    instanceTags Map<String,String>
    Map of tags, each pair of which must exactly match a pair on desired instances.
    filters GetInstancesFilter[]
    One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out [describe-instances in the AWS CLI reference][1].
    instanceStateNames string[]
    List of instance states that should be applicable to the desired instances. The permitted values are: pending, running, shutting-down, stopped, stopping, terminated. The default value is running.
    instanceTags {[key: string]: string}
    Map of tags, each pair of which must exactly match a pair on desired instances.
    filters Sequence[GetInstancesFilter]
    One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out [describe-instances in the AWS CLI reference][1].
    instance_state_names Sequence[str]
    List of instance states that should be applicable to the desired instances. The permitted values are: pending, running, shutting-down, stopped, stopping, terminated. The default value is running.
    instance_tags Mapping[str, str]
    Map of tags, each pair of which must exactly match a pair on desired instances.
    filters List<Property Map>
    One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out [describe-instances in the AWS CLI reference][1].
    instanceStateNames List<String>
    List of instance states that should be applicable to the desired instances. The permitted values are: pending, running, shutting-down, stopped, stopping, terminated. The default value is running.
    instanceTags Map<String>
    Map of tags, each pair of which must exactly match a pair on desired instances.

    getInstances Result

    The following output properties are available:

    Id string
    The provider-assigned unique ID for this managed resource.
    Ids List<string>
    IDs of instances found through the filter
    InstanceTags Dictionary<string, string>
    Ipv6Addresses List<string>
    IPv6 addresses of instances found through the filter
    PrivateIps List<string>
    Private IP addresses of instances found through the filter
    PublicIps List<string>
    Public IP addresses of instances found through the filter
    Filters List<GetInstancesFilter>
    InstanceStateNames List<string>
    Id string
    The provider-assigned unique ID for this managed resource.
    Ids []string
    IDs of instances found through the filter
    InstanceTags map[string]string
    Ipv6Addresses []string
    IPv6 addresses of instances found through the filter
    PrivateIps []string
    Private IP addresses of instances found through the filter
    PublicIps []string
    Public IP addresses of instances found through the filter
    Filters []GetInstancesFilter
    InstanceStateNames []string
    id String
    The provider-assigned unique ID for this managed resource.
    ids List<String>
    IDs of instances found through the filter
    instanceTags Map<String,String>
    ipv6Addresses List<String>
    IPv6 addresses of instances found through the filter
    privateIps List<String>
    Private IP addresses of instances found through the filter
    publicIps List<String>
    Public IP addresses of instances found through the filter
    filters List<GetInstancesFilter>
    instanceStateNames List<String>
    id string
    The provider-assigned unique ID for this managed resource.
    ids string[]
    IDs of instances found through the filter
    instanceTags {[key: string]: string}
    ipv6Addresses string[]
    IPv6 addresses of instances found through the filter
    privateIps string[]
    Private IP addresses of instances found through the filter
    publicIps string[]
    Public IP addresses of instances found through the filter
    filters GetInstancesFilter[]
    instanceStateNames string[]
    id str
    The provider-assigned unique ID for this managed resource.
    ids Sequence[str]
    IDs of instances found through the filter
    instance_tags Mapping[str, str]
    ipv6_addresses Sequence[str]
    IPv6 addresses of instances found through the filter
    private_ips Sequence[str]
    Private IP addresses of instances found through the filter
    public_ips Sequence[str]
    Public IP addresses of instances found through the filter
    filters Sequence[GetInstancesFilter]
    instance_state_names Sequence[str]
    id String
    The provider-assigned unique ID for this managed resource.
    ids List<String>
    IDs of instances found through the filter
    instanceTags Map<String>
    ipv6Addresses List<String>
    IPv6 addresses of instances found through the filter
    privateIps List<String>
    Private IP addresses of instances found through the filter
    publicIps List<String>
    Public IP addresses of instances found through the filter
    filters List<Property Map>
    instanceStateNames List<String>

    Supporting Types

    GetInstancesFilter

    Name string
    Values List<string>
    Name string
    Values []string
    name String
    values List<String>
    name string
    values string[]
    name str
    values Sequence[str]
    name String
    values List<String>

    Package Details

    Repository
    AWS Classic pulumi/pulumi-aws
    License
    Apache-2.0
    Notes
    This Pulumi package is based on the aws Terraform Provider.
    aws logo
    AWS v6.60.0 published on Tuesday, Nov 19, 2024 by Pulumi