All Products
Search
Document Center

Elastic Compute Service:Create an ENI

Last Updated:Aug 14, 2023

This topic describes how to use Alibaba Cloud Elastic Compute Service (ECS) SDK for Java to create an elastic network interface (ENI).

Usage notes

Take note of the following items:

  • The operation is synchronous. An ENI enters the Available (Available) state and can be attached to an instance as soon as the ENI is created by this operation.

  • If the return value of networkInterfaceId is empty, no ENI is not created. Try again with the same ClientToken value to create an ENI.

Sample code

The following sample code applies when you create an ENI under a specified vSwitch and in a specified security group:

Note

In this example, Alibaba Cloud ECS SDK V2.0 is used.

import java.util.UUID;

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.CreateNetworkInterfaceRequest;
import com.aliyun.ecs20140526.models.CreateNetworkInterfaceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class CreateNetworkInterfaceExample {

    /**
     * Initialize the client by using your AccessKey ID and AccessKey secret. 
     *
     * In this example, the AccessKey pair that is used for authentication is retrieved from environment variables. Make modifications based on your production environment in actual scenarios. 
     * Do not store critical information, such as AccessKey IDs and AccessKey secrets, in plaintext in code. 
     *
     * @return Client
     * @throws Exception
     */
    public static Client createClient() throws Exception {
        Config config = new Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "<yourEcsEndPoint>";
        return new Client(config);
    }

    public static String CreateNetworkInterface(Client client, String regionId, String vSwitchId,
        String securityGroupId, String name, String description) {
        try {
            CreateNetworkInterfaceRequest request = new CreateNetworkInterfaceRequest();
            request.setRegionId(regionId);
            request.setVSwitchId(vSwitchId);
            request.setSecurityGroupId(securityGroupId);
            request.setNetworkInterfaceName(name);
            request.setDescription(description);
            request.setClientToken(UUID.randomUUID().toString());

            // Specify a custom policy.
            RuntimeOptions runtime = new RuntimeOptions();
            CreateNetworkInterfaceResponse response = client.createNetworkInterfaceWithOptions(request, runtime);

            if ("Available".equals(response.getBody().getStatus())) {
                System.out.println(
                    String.format("Instance.CreateNetworkInterface success, eni id:%s. Request is is %s.%n",
                        response.getBody().getNetworkInterfaceId(), response.getBody().getRequestId()));
                return response.getBody().getNetworkInterfaceId();
            }
        } catch (TeaException te) {
            System.out.println("ErrCode:" + te.getCode());
            System.out.println("ErrMsg:" + te.getMessage());
            System.out.println("RequestId:" + te.getData().get("RequestId"));
        } catch (Exception e) {
            System.out.println("ErrCode:" + e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String regionId = "<regionId>";
        String vSwitchId = "<yourVSwitchId>";
        String securityGroupId = "<yourSecurityGroupId>";

        Client client = createClient();
        CreateNetworkInterface(client, regionId, vSwitchId, securityGroupId, "test-eni", "description");
    }
}

Execution results

{
 "Description" : "testDescription",
 "Status" : "Available",
 "PrivateIpAddress" : "172.17.**.**",
 "ServiceManaged" : false,
 "RequestId" : "473469C7-AA6F-4DC5-B3DB-A3DC0DE3C83E",
 "ResourceGroupId" : "rg-2ze88m67qx5z****",
 "ZoneId" : "cn-hangzhou-e",
 "VSwitchId" : "vsw-bp16usj2p27htro3****",
 "NetworkInterfaceName" : "my-eni-name",
 "MacAddress" : "00:16:3e:12:**:**",
 "NetworkInterfaceId" : "eni-bp14v2sdd3v8htln****",
 "SecurityGroupIds" : {
 "SecurityGroupId" : [ "sg-bp18kz60mefsicfg****" ]
 },
 "Type" : "Secondary",
 "Ipv6Sets" : {
 "Ipv6Set" : [ {
 "Ipv6Address" : "2001:db8:1234:1a00::****" } ]
 },
 "VpcId" : "vpc-bp1j7w3gc1cexjqd****",
 "OwnerId" : "123456****",
 "Tags" : {
 "Tag" : [ {
 "TagKey" : "TestKey",
 "TagValue" : "TestValue" } ]
 },
 "PrivateIpSets" : {
 "PrivateIpSet" : [ {
 "PrivateIpAddress" : "172.17.**.**",
 "Primary" : true } ]
 }
}

References

CreateNetworkInterface