NetworkInterfaceSecurityGroupAttachment class

This resource attaches a security group to an Elastic Network Interface (ENI). It can be used to attach a security group to any existing ENI, be it a secondary ENI or one attached as the primary interface on an instance.

> NOTE on instances, interfaces, and security groups: This provider currently provides the capability to assign security groups via the aws.ec2.Instance and the aws.ec2.NetworkInterface resources. Using this resource in conjunction with security groups provided in-line in those resources will cause conflicts, and will lead to spurious diffs and undefined behavior - please use one or the other.

Example Usage

The following provides a very basic example of setting up an instance (provided by instance) in the default security group, creating a security group (provided by sg) and then attaching the security group to the instance's primary network interface via the aws.ec2.NetworkInterfaceSecurityGroupAttachment resource, named sgAttachment:

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

const ami = aws.ec2.getAmi({
    filters: [{
        name: "name",
        values: ["amzn-ami-hvm-*"],
    }],
    mostRecent: true,
    owners: ["amazon"],
});
const instance = new aws.ec2.Instance("instance", {
    instanceType: aws.ec2.InstanceType.T2_Micro,
    ami: ami.then(ami => ami.id),
    tags: {
        type: "test-instance",
    },
});
const sg = new aws.ec2.SecurityGroup("sg", {tags: {
    type: "test-security-group",
}});
const sgAttachment = new aws.ec2.NetworkInterfaceSecurityGroupAttachment("sg_attachment", {
    securityGroupId: sg.id,
    networkInterfaceId: instance.primaryNetworkInterfaceId,
});
import pulumi
import pulumi_aws as aws

ami = aws.ec2.get_ami(filters=[{
        "name": "name",
        "values": ["amzn-ami-hvm-*"],
    }],
    most_recent=True,
    owners=["amazon"])
instance = aws.ec2.Instance("instance",
    instance_type=aws.ec2.InstanceType.T2_MICRO,
    ami=ami.id,
    tags={
        "type": "test-instance",
    })
sg = aws.ec2.SecurityGroup("sg", tags={
    "type": "test-security-group",
})
sg_attachment = aws.ec2.NetworkInterfaceSecurityGroupAttachment("sg_attachment",
    security_group_id=sg.id,
    network_interface_id=instance.primary_network_interface_id)
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Aws = Pulumi.Aws;

return await Deployment.RunAsync(() =>
{
    var ami = Aws.Ec2.GetAmi.Invoke(new()
    {
        Filters = new[]
        {
            new Aws.Ec2.Inputs.GetAmiFilterInputArgs
            {
                Name = "name",
                Values = new[]
                {
                    "amzn-ami-hvm-*",
                },
            },
        },
        MostRecent = true,
        Owners = new[]
        {
            "amazon",
        },
    });

    var instance = new Aws.Ec2.Instance("instance", new()
    {
        InstanceType = Aws.Ec2.InstanceType.T2_Micro,
        Ami = ami.Apply(getAmiResult => getAmiResult.Id),
        Tags =
        {
            { "type", "test-instance" },
        },
    });

    var sg = new Aws.Ec2.SecurityGroup("sg", new()
    {
        Tags =
        {
            { "type", "test-security-group" },
        },
    });

    var sgAttachment = new Aws.Ec2.NetworkInterfaceSecurityGroupAttachment("sg_attachment", new()
    {
        SecurityGroupId = sg.Id,
        NetworkInterfaceId = instance.PrimaryNetworkInterfaceId,
    });

});
package main

import (
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/ec2"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		ami, err := ec2.LookupAmi(ctx, &ec2.LookupAmiArgs{
			Filters: []ec2.GetAmiFilter{
				{
					Name: "name",
					Values: []string{
						"amzn-ami-hvm-*",
					},
				},
			},
			MostRecent: pulumi.BoolRef(true),
			Owners: []string{
				"amazon",
			},
		}, nil)
		if err != nil {
			return err
		}
		instance, err := ec2.NewInstance(ctx, "instance", &ec2.InstanceArgs{
			InstanceType: pulumi.String(ec2.InstanceType_T2_Micro),
			Ami:          pulumi.String(ami.Id),
			Tags: pulumi.StringMap{
				"type": pulumi.String("test-instance"),
			},
		})
		if err != nil {
			return err
		}
		sg, err := ec2.NewSecurityGroup(ctx, "sg", &ec2.SecurityGroupArgs{
			Tags: pulumi.StringMap{
				"type": pulumi.String("test-security-group"),
			},
		})
		if err != nil {
			return err
		}
		_, err = ec2.NewNetworkInterfaceSecurityGroupAttachment(ctx, "sg_attachment", &ec2.NetworkInterfaceSecurityGroupAttachmentArgs{
			SecurityGroupId:    sg.ID().ToIDOutput().ToStringOutput(),
			NetworkInterfaceId: instance.PrimaryNetworkInterfaceId,
		})
		if err != nil {
			return err
		}
		return nil
	})
}
pulumi {
  required_providers {
    aws = {
      source = "pulumi/aws"
    }
  }
}

data "aws_ec2_getami" "ami" {
  filters {
    name   = "name"
    values = ["amzn-ami-hvm-*"]
  }
  most_recent = true
  owners      = ["amazon"]
}

resource "aws_ec2_instance" "instance" {
  instance_type = "t2.micro"
  ami           = data.aws_ec2_getami.ami.id
  tags = {
    "type" = "test-instance"
  }
}
resource "aws_ec2_securitygroup" "sg" {
  tags = {
    "type" = "test-security-group"
  }
}
resource "aws_ec2_networkinterfacesecuritygroupattachment" "sg_attachment" {
  security_group_id    = aws_ec2_securitygroup.sg.id
  network_interface_id = aws_ec2_instance.instance.primary_network_interface_id
}
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.GetAmiArgs;
import com.pulumi.aws.ec2.inputs.GetAmiFilterArgs;
import com.pulumi.aws.ec2.Instance;
import com.pulumi.aws.ec2.InstanceArgs;
import com.pulumi.aws.ec2.SecurityGroup;
import com.pulumi.aws.ec2.SecurityGroupArgs;
import com.pulumi.aws.ec2.NetworkInterfaceSecurityGroupAttachment;
import com.pulumi.aws.ec2.NetworkInterfaceSecurityGroupAttachmentArgs;
import java.util.ArrayList;
import java.util.Arrays;
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 ami = Ec2Functions.getAmi(GetAmiArgs.builder()
            .filters(GetAmiFilterArgs.builder()
                .name("name")
                .values("amzn-ami-hvm-*")
                .build())
            .mostRecent(true)
            .owners("amazon")
            .build());

        var instance = new Instance("instance", InstanceArgs.builder()
            .instanceType("t2.micro")
            .ami(ami.id())
            .tags(Map.of("type", "test-instance"))
            .build());

        var sg = new SecurityGroup("sg", SecurityGroupArgs.builder()
            .tags(Map.of("type", "test-security-group"))
            .build());

        var sgAttachment = new NetworkInterfaceSecurityGroupAttachment("sgAttachment", NetworkInterfaceSecurityGroupAttachmentArgs.builder()
            .securityGroupId(sg.id())
            .networkInterfaceId(instance.primaryNetworkInterfaceId())
            .build());

    }
}
resources:
  instance:
    type: aws:ec2:Instance
    properties:
      instanceType: t2.micro
      ami: ${ami.id}
      tags:
        type: test-instance
  sg:
    type: aws:ec2:SecurityGroup
    properties:
      tags:
        type: test-security-group
  sgAttachment:
    type: aws:ec2:NetworkInterfaceSecurityGroupAttachment
    name: sg_attachment
    properties:
      securityGroupId: ${sg.id}
      networkInterfaceId: ${instance.primaryNetworkInterfaceId}
variables:
  ami:
    fn::invoke:
      function: aws:ec2:getAmi
      arguments:
        filters:
          - name: name
            values:
              - amzn-ami-hvm-*
        mostRecent: true
        owners:
          - amazon

In this example, instance is provided by the aws.ec2.Instance data source, fetching an external instance, possibly not managed by this provider. sgAttachment then attaches to the output instance's networkInterfaceId:

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

const instance = aws.ec2.getInstance({
    instanceId: "i-1234567890abcdef0",
});
const sg = new aws.ec2.SecurityGroup("sg", {tags: {
    type: "test-security-group",
}});
const sgAttachment = new aws.ec2.NetworkInterfaceSecurityGroupAttachment("sg_attachment", {
    securityGroupId: sg.id,
    networkInterfaceId: instance.then(instance => instance.networkInterfaceId),
});
import pulumi
import pulumi_aws as aws

instance = aws.ec2.get_instance(instance_id="i-1234567890abcdef0")
sg = aws.ec2.SecurityGroup("sg", tags={
    "type": "test-security-group",
})
sg_attachment = aws.ec2.NetworkInterfaceSecurityGroupAttachment("sg_attachment",
    security_group_id=sg.id,
    network_interface_id=instance.network_interface_id)
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Aws = Pulumi.Aws;

return await Deployment.RunAsync(() =>
{
    var instance = Aws.Ec2.GetInstance.Invoke(new()
    {
        InstanceId = "i-1234567890abcdef0",
    });

    var sg = new Aws.Ec2.SecurityGroup("sg", new()
    {
        Tags =
        {
            { "type", "test-security-group" },
        },
    });

    var sgAttachment = new Aws.Ec2.NetworkInterfaceSecurityGroupAttachment("sg_attachment", new()
    {
        SecurityGroupId = sg.Id,
        NetworkInterfaceId = instance.Apply(getInstanceResult => getInstanceResult.NetworkInterfaceId),
    });

});
package main

import (
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/ec2"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		instance, err := ec2.LookupInstance(ctx, &ec2.LookupInstanceArgs{
			InstanceId: pulumi.StringRef("i-1234567890abcdef0"),
		}, nil)
		if err != nil {
			return err
		}
		sg, err := ec2.NewSecurityGroup(ctx, "sg", &ec2.SecurityGroupArgs{
			Tags: pulumi.StringMap{
				"type": pulumi.String("test-security-group"),
			},
		})
		if err != nil {
			return err
		}
		_, err = ec2.NewNetworkInterfaceSecurityGroupAttachment(ctx, "sg_attachment", &ec2.NetworkInterfaceSecurityGroupAttachmentArgs{
			SecurityGroupId:    sg.ID().ToIDOutput().ToStringOutput(),
			NetworkInterfaceId: pulumi.String(instance.NetworkInterfaceId),
		})
		if err != nil {
			return err
		}
		return nil
	})
}
pulumi {
  required_providers {
    aws = {
      source = "pulumi/aws"
    }
  }
}

data "aws_ec2_getinstance" "instance" {
  instance_id = "i-1234567890abcdef0"
}

resource "aws_ec2_securitygroup" "sg" {
  tags = {
    "type" = "test-security-group"
  }
}
resource "aws_ec2_networkinterfacesecuritygroupattachment" "sg_attachment" {
  security_group_id    = aws_ec2_securitygroup.sg.id
  network_interface_id = data.aws_ec2_getinstance.instance.network_interface_id
}
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.GetInstanceArgs;
import com.pulumi.aws.ec2.SecurityGroup;
import com.pulumi.aws.ec2.SecurityGroupArgs;
import com.pulumi.aws.ec2.NetworkInterfaceSecurityGroupAttachment;
import com.pulumi.aws.ec2.NetworkInterfaceSecurityGroupAttachmentArgs;
import java.util.ArrayList;
import java.util.Arrays;
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 instance = Ec2Functions.getInstance(GetInstanceArgs.builder()
            .instanceId("i-1234567890abcdef0")
            .build());

        var sg = new SecurityGroup("sg", SecurityGroupArgs.builder()
            .tags(Map.of("type", "test-security-group"))
            .build());

        var sgAttachment = new NetworkInterfaceSecurityGroupAttachment("sgAttachment", NetworkInterfaceSecurityGroupAttachmentArgs.builder()
            .securityGroupId(sg.id())
            .networkInterfaceId(instance.networkInterfaceId())
            .build());

    }
}
resources:
  sg:
    type: aws:ec2:SecurityGroup
    properties:
      tags:
        type: test-security-group
  sgAttachment:
    type: aws:ec2:NetworkInterfaceSecurityGroupAttachment
    name: sg_attachment
    properties:
      securityGroupId: ${sg.id}
      networkInterfaceId: ${instance.networkInterfaceId}
variables:
  instance:
    fn::invoke:
      function: aws:ec2:getInstance
      arguments:
        instanceId: i-1234567890abcdef0

Import

Using pulumi import, import Network Interface Security Group attachments using the associated network interface ID and security group ID, separated by an underscore (_). For example:

$ pulumi import aws:ec2/networkInterfaceSecurityGroupAttachment:NetworkInterfaceSecurityGroupAttachment sg_attachment eni-1234567890abcdef0_sg-1234567890abcdef0

Constructors

NetworkInterfaceSecurityGroupAttachment(String name, {NetworkInterfaceSecurityGroupAttachmentArgs? args, CustomResourceOptions? options})
Creates a new NetworkInterfaceSecurityGroupAttachment. name The Pulumi resource name. args Arguments used to configure this NetworkInterfaceSecurityGroupAttachment. The set of arguments for NetworkInterfaceSecurityGroupAttachment. options Resource options controlling this resource's behavior.
NetworkInterfaceSecurityGroupAttachment.reference(String urn)
Creates a typed reference to an existing NetworkInterfaceSecurityGroupAttachment resource.

Properties

childResources Set<Resource>
finalinherited
completionSources Map<String, IOutputCompletionSource>
latefinalinherited
hashCode int
The hash code for this object.
no setterinherited
id ↔ Output<String>
getter/setter pairinherited
isCustom bool
Returns whether this resource is provider-managed.
no setterinherited
isProtected bool
Returns whether this resource is protected from deletion.
no setterinherited
isRemote bool
Whether this resource is registered as remote.
no setterinherited
isResourceReference bool
Whether this instance represents a resource value returned over RPC.
finalinherited
networkInterfaceId ↔ Output<String>
The ID of the network interface to attach to.
latefinal
region ↔ Output<String>
Region where this resource will be managed. Defaults to the Region set in the provider configuration.
latefinal
resourceTransforms List<ResourceTransform>
Inherited/explicit async transforms.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
securityGroupId ↔ Output<String>
The ID of the security group.
latefinal
transformations List<ResourceTransformation>
Inherited/explicit legacy transformations.
no setterinherited
urn ↔ Output<String>
latefinalinherited

Methods

failId(Object error) → void
Completes this resource ID with an error when registration fails.
inherited
failOutputs(Object error) → void
Completes all output properties with error.
inherited
failUrn(Object error) → void
Completes this resource URN with an error when registration fails.
inherited
getProvider(String moduleMember) → ProviderResource?
Returns provider for moduleMember's package, if configured.
inherited
getResourceName() String
Returns this resource's logical name.
inherited
getResourceType() String
Returns this resource's Pulumi type token.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
registerOutput<T>(String propertyName, {Object? decoder(Object?)?, bool isSecret = false}) → Output<T>
Registers a dynamic output property for this resource.
inherited
resolveId(String? value, {required bool isKnown}) → void
Resolves the provider-assigned ID for this resource.
inherited
resolveOutputs(Struct outputs) → void
Resolves all output properties from a monitor response payload.
inherited
resolveUrn(String value) → void
Resolves this resource's URN once assigned by the engine.
inherited
serializeProperties(Map<String, dynamic> properties) Future<Struct>
Serializes resource properties for RPC transmission.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

get(String name, Input<String> id, {NetworkInterfaceSecurityGroupAttachmentState? state, CustomResourceOptions? options}) NetworkInterfaceSecurityGroupAttachment
Gets an existing NetworkInterfaceSecurityGroupAttachment resource's state with the given name and id.