Ejemplos de Amazon ECS usando SDK para Java 2.x - Ejemplos de código de AWS SDK

Hay más ejemplos de AWS SDK disponibles en el GitHub repositorio de ejemplos de AWS Doc SDK.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Ejemplos de Amazon ECS usando SDK para Java 2.x

En los ejemplos de código siguientes se muestra cómo ejecutar acciones e implementar escenarios comunes usando AWS SDK for Java 2.x con Amazon ECS.

Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las funciones de servicio individuales, es posible ver las acciones en contexto en los escenarios relacionados y en los ejemplos entre servicios.

Los escenarios son ejemplos de código que muestran cómo llevar a cabo una tarea específica llamando a varias funciones dentro del mismo servicio.

Cada ejemplo incluye un enlace a GitHub, donde puedes encontrar instrucciones sobre cómo configurar y ejecutar el código en su contexto.

Acciones

El ejemplo de código siguiente muestra cómo crear un clúster de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.ExecuteCommandConfiguration; import software.amazon.awssdk.services.ecs.model.ExecuteCommandLogging; import software.amazon.awssdk.services.ecs.model.ClusterConfiguration; import software.amazon.awssdk.services.ecs.model.CreateClusterResponse; import software.amazon.awssdk.services.ecs.model.EcsException; import software.amazon.awssdk.services.ecs.model.CreateClusterRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateCluster { public static void main(String[] args) { final String usage = """ Usage: <clusterName>\s Where: clusterName - The name of the ECS cluster to create. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); String clusterArn = createGivenCluster(ecsClient, clusterName); System.out.println("The cluster ARN is " + clusterArn); ecsClient.close(); } public static String createGivenCluster(EcsClient ecsClient, String clusterName) { try { ExecuteCommandConfiguration commandConfiguration = ExecuteCommandConfiguration.builder() .logging(ExecuteCommandLogging.DEFAULT) .build(); ClusterConfiguration clusterConfiguration = ClusterConfiguration.builder() .executeCommandConfiguration(commandConfiguration) .build(); CreateClusterRequest clusterRequest = CreateClusterRequest.builder() .clusterName(clusterName) .configuration(clusterConfiguration) .build(); CreateClusterResponse response = ecsClient.createCluster(clusterRequest); return response.cluster().clusterArn(); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para obtener más información sobre la API, consulta CreateClusterla Referencia AWS SDK for Java 2.x de la API.

El ejemplo de código siguiente muestra cómo crear un servicio de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.AwsVpcConfiguration; import software.amazon.awssdk.services.ecs.model.NetworkConfiguration; import software.amazon.awssdk.services.ecs.model.CreateServiceRequest; import software.amazon.awssdk.services.ecs.model.LaunchType; import software.amazon.awssdk.services.ecs.model.CreateServiceResponse; import software.amazon.awssdk.services.ecs.model.EcsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateService { public static void main(String[] args) { final String usage = """ Usage: <clusterName> <serviceName> <securityGroups> <subnets> <taskDefinition> Where: clusterName - The name of the ECS cluster. serviceName - The name of the ECS service to create. securityGroups - The name of the security group. subnets - The name of the subnet. taskDefinition - The name of the task definition. """; if (args.length != 5) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; String serviceName = args[1]; String securityGroups = args[2]; String subnets = args[3]; String taskDefinition = args[4]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); String serviceArn = createNewService(ecsClient, clusterName, serviceName, securityGroups, subnets, taskDefinition); System.out.println("The ARN of the service is " + serviceArn); ecsClient.close(); } public static String createNewService(EcsClient ecsClient, String clusterName, String serviceName, String securityGroups, String subnets, String taskDefinition) { try { AwsVpcConfiguration vpcConfiguration = AwsVpcConfiguration.builder() .securityGroups(securityGroups) .subnets(subnets) .build(); NetworkConfiguration configuration = NetworkConfiguration.builder() .awsvpcConfiguration(vpcConfiguration) .build(); CreateServiceRequest serviceRequest = CreateServiceRequest.builder() .cluster(clusterName) .networkConfiguration(configuration) .desiredCount(1) .launchType(LaunchType.FARGATE) .serviceName(serviceName) .taskDefinition(taskDefinition) .build(); CreateServiceResponse response = ecsClient.createService(serviceRequest); return response.service().serviceArn(); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para obtener más información sobre la API, consulta CreateServicela Referencia AWS SDK for Java 2.x de la API.

El ejemplo de código siguiente muestra cómo eliminar un servicio de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.DeleteServiceRequest; import software.amazon.awssdk.services.ecs.model.EcsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteService { public static void main(String[] args) { final String usage = """ Usage: <clusterName> <serviceArn>\s Where: clusterName - The name of the ECS cluster. serviceArn - The ARN of the ECS service. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; String serviceArn = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); deleteSpecificService(ecsClient, clusterName, serviceArn); ecsClient.close(); } public static void deleteSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) { try { DeleteServiceRequest serviceRequest = DeleteServiceRequest.builder() .cluster(clusterName) .service(serviceArn) .build(); ecsClient.deleteService(serviceRequest); System.out.println("The Service was successfully deleted"); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para obtener más información sobre la API, consulta DeleteServicela Referencia AWS SDK for Java 2.x de la API.

El ejemplo de código siguiente muestra cómo describir sus clústeres de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.DescribeClustersRequest; import software.amazon.awssdk.services.ecs.model.DescribeClustersResponse; import software.amazon.awssdk.services.ecs.model.Cluster; import software.amazon.awssdk.services.ecs.model.EcsException; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DescribeClusters { public static void main(String[] args) { final String usage = """ Usage: <clusterArn> \s Where: clusterArn - The ARN of the ECS cluster to describe. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String clusterArn = args[0]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); descCluster(ecsClient, clusterArn); } public static void descCluster(EcsClient ecsClient, String clusterArn) { try { DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder() .clusters(clusterArn) .build(); DescribeClustersResponse response = ecsClient.describeClusters(clustersRequest); List<Cluster> clusters = response.clusters(); for (Cluster cluster : clusters) { System.out.println("The cluster name is " + cluster.clusterName()); } } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para obtener más información sobre la API, consulta DescribeClustersla Referencia AWS SDK for Java 2.x de la API.

En el ejemplo de código siguiente se muestra cómo describir sus tareas de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest; import software.amazon.awssdk.services.ecs.model.DescribeTasksResponse; import software.amazon.awssdk.services.ecs.model.EcsException; import software.amazon.awssdk.services.ecs.model.Task; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListTaskDefinitions { public static void main(String[] args) { final String usage = """ Usage: <clusterArn> <taskId>\s Where: clusterArn - The ARN of an ECS cluster. taskId - The task Id value. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clusterArn = args[0]; String taskId = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); getAllTasks(ecsClient, clusterArn, taskId); ecsClient.close(); } public static void getAllTasks(EcsClient ecsClient, String clusterArn, String taskId) { try { DescribeTasksRequest tasksRequest = DescribeTasksRequest.builder() .cluster(clusterArn) .tasks(taskId) .build(); DescribeTasksResponse response = ecsClient.describeTasks(tasksRequest); List<Task> tasks = response.tasks(); for (Task task : tasks) { System.out.println("The task ARN is " + task.taskDefinitionArn()); } } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para obtener más información sobre la API, consulta DescribeTasksla Referencia AWS SDK for Java 2.x de la API.

En el ejemplo de código siguiente se muestra cómo enumerar clústeres de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.ListClustersResponse; import software.amazon.awssdk.services.ecs.model.EcsException; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); listAllClusters(ecsClient); ecsClient.close(); } public static void listAllClusters(EcsClient ecsClient) { try { ListClustersResponse response = ecsClient.listClusters(); List<String> clusters = response.clusterArns(); for (String cluster : clusters) { System.out.println("The cluster arn is " + cluster); } } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para obtener más información sobre la API, consulta ListClustersla Referencia AWS SDK for Java 2.x de la API.

El ejemplo de código siguiente muestra cómo actualizar un servicio de Amazon ECS.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.EcsException; import software.amazon.awssdk.services.ecs.model.UpdateServiceRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class UpdateService { public static void main(String[] args) { final String usage = """ Usage: <clusterName> <serviceArn>\s Where: clusterName - The cluster name. serviceArn - The service ARN value. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; String serviceArn = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); updateSpecificService(ecsClient, clusterName, serviceArn); ecsClient.close(); } public static void updateSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) { try { UpdateServiceRequest serviceRequest = UpdateServiceRequest.builder() .cluster(clusterName) .service(serviceArn) .desiredCount(0) .build(); ecsClient.updateService(serviceRequest); System.out.println("The service was modified"); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para obtener más información sobre la API, consulta UpdateServicela Referencia AWS SDK for Java 2.x de la API.