How can you reference the primary network interface of an EC2 instance in AWS CDK?

1k Views Asked by At

In AWS-CDK I am trying to create a Traffic Mirroring Session. The EC2 machines are created in previous stacks and passed down as props to the new stack. However, while I am able to reference an ENI that was created explicitly (sniffing interface), I cannot find a way of referencing the EC2 primary network interface as the traffic mirror source

 class TrafficMirringStack extends cdk.Stack {
    constructor(scope, id, props) {
        super(scope,id,props)

        const {
            suricataInstance,
            sniffingInterface,
            targetInstance
        } = props;


    const mirrorTarget = new ec2.CfnTrafficMirrorTarget(this, 'TrafficMirrorTarget', {
      description:' This is the traffic mirror target',
      networkInterfaceId: sniffingInterface.ref,
    });

    const mirrorFilter = new ec2.CfnTrafficMirrorFilter(this, 'TrafficMirrorFilter', {
      description: 'This filter allows all traffic from the target machine to be redirected to the sniffing interface',
      networkServices:[],
    });

    const allowAllInboundRule = new ec2.CfnTrafficMirrorFilterRule(this, 'InboundMirrorFilter', {
      destinationCidrBlock : '0.0.0.0/0',
      sourceCidrBlock:'0.0.0.0/0',
      trafficDirection: 'ingress',
      ruleAction: 'accept',
      ruleNumber:100,
      trafficMirrorFilterId: mirrorFilter.ref
    });

    const allowAllOutboundRule = new ec2.CfnTrafficMirrorFilterRule(this, 'OutboundMirrorFilter', {
      destinationCidrBlock : '0.0.0.0/0',
      sourceCidrBlock:'0.0.0.0/0',
      trafficDirection: 'egress',
      ruleAction: 'accept',
      ruleNumber:200,
      trafficMirrorFilterId: mirrorFilter.ref
    });

    
    const mirrorSession = new ec2.CfnTrafficMirrorSession(this, 'TrafficMirrorSession', {
      sessionNumber: 1,
      networkInterfaceId: targetInstance.instance.networkInterfaceId,
      trafficMirrorFilterId: mirrorFilter.ref,
      trafficMirrorTargetId: mirrorTarget.ref
    })
    }
}

and I get the following error

Error: TrafficMirroringStack/TrafficMirrorSession [AWS::EC2::TrafficMirrorSession] is missing required property: networkInterfaceId
1

There are 1 best solutions below

0
y. bs On

try to use:

instance.networkInterfaces

and find the interface you want.

see docs: networkInterfaces - aws cdk doc