

There are more AWS SDK examples available in the [AWS Doc SDK Examples](https://github.com/awsdocs/aws-doc-sdk-examples) GitHub repo.

# Use `CreateComputeEnvironment` with an AWS SDK or CLI
<a name="batch_example_batch_CreateComputeEnvironment_section"></a>

The following code examples show how to use `CreateComputeEnvironment`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: 
+  [Learn the basics](batch_example_batch_Scenario_section.md) 
+  [Getting started with batch processing and serverless containers](batch_example_fargate_GettingStarted_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**Example 1: To create a managed compute environment with On-Demand instances**  
The following `create-compute-environment` example creates a managed compute environment with specific C4 instance types that are launched on demand. The compute environment is called C4OnDemand.  

```
aws batch create-compute-environment \
    --cli-input-json {{file://<path_to_json_file>/C4OnDemand.json}}
```
Contents of `C4OnDemand.json`:  

```
{
    "computeEnvironmentName": "C4OnDemand",
    "type": "MANAGED",
    "state": "ENABLED",
    "computeResources": {
        "type": "EC2",
        "minvCpus": 0,
        "maxvCpus": 128,
        "desiredvCpus": 48,
        "instanceTypes": [
            "c4.large",
            "c4.xlarge",
            "c4.2xlarge",
            "c4.4xlarge",
            "c4.8xlarge"
        ],
        "subnets": [
            "subnet-220c0e0a",
            "subnet-1a95556d",
            "subnet-978f6dce"
        ],
        "securityGroupIds": [
            "sg-cf5093b2"
        ],
        "ec2KeyPair": "id_rsa",
        "instanceRole": "ecsInstanceRole",
        "tags": {
            "Name": "Batch Instance - C4OnDemand"
        }
    },
    "serviceRole": "arn:aws:iam::123456789012:role/AWSBatchServiceRole"
}
```
Output:  

```
{
    "computeEnvironmentName": "C4OnDemand",
    "computeEnvironmentArn": "arn:aws:batch:us-west-2:123456789012:compute-environment/C4OnDemand"
}
```
For more information, see [Create a compute environment](https://docs.aws.amazon.com/batch/latest/userguide/create-compute-environment.html) in the *AWS Batch User Guide*.  
**Example 2: To create a managed compute environment with Spot Instances**  
The following `create-compute-environment` example creates a managed compute environment with the M4 instance type that is launched when the Spot bid price is at or below 20% of the On-Demand price for the instance type. The compute environment is called M4Spot.  

```
aws batch create-compute-environment \
    --cli-input-json {{file://<path_to_json_file>/M4Spot.json}}
```
Contents of `M4Spot.json`:  

```
{
    "computeEnvironmentName": "M4Spot",
    "type": "MANAGED",
    "state": "ENABLED",
    "computeResources": {
        "type": "SPOT",
        "spotIamFleetRole": "arn:aws:iam::123456789012:role/aws-ec2-spot-fleet-role",
        "minvCpus": 0,
        "maxvCpus": 128,
        "desiredvCpus": 4,
        "instanceTypes": [
            "m4"
        ],
        "bidPercentage": 20,
        "subnets": [
            "subnet-220c0e0a",
            "subnet-1a95556d",
            "subnet-978f6dce"
        ],
        "securityGroupIds": [
            "sg-cf5093b2"
        ],
        "ec2KeyPair": "id_rsa",
        "instanceRole": "ecsInstanceRole",
        "tags": {
            "Name": "Batch Instance - M4Spot"
        }
    },
    "serviceRole": "arn:aws:iam::123456789012:role/AWSBatchServiceRole"
}
```
Output:  

```
{
    "computeEnvironmentName": "M4Spot",
    "computeEnvironmentArn": "arn:aws:batch:us-west-2:123456789012:compute-environment/M4Spot"
}
```
For more information, see [Create a compute environment](https://docs.aws.amazon.com/batch/latest/userguide/create-compute-environment.html) in the *AWS Batch User Guide*.  
+  For API details, see [CreateComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/create-compute-environment.html) in *AWS CLI Command Reference*. 

------
#### [ Java ]

**SDK for Java 2.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples). 

```
    /**
     * Asynchronously creates a new compute environment in AWS Batch.
     *
     * @param computeEnvironmentName the name of the compute environment to create
     * @param batchIAMRole the IAM role to be used by the compute environment
     * @param subnet the subnet ID to be used for the compute environment
     * @param secGroup the security group ID to be used for the compute environment
     * @return a {@link CompletableFuture} representing the asynchronous operation, which will complete with the
     *         {@link CreateComputeEnvironmentResponse} when the compute environment has been created
     * @throws BatchException if there is an error creating the compute environment
     * @throws RuntimeException if there is an unexpected error during the operation
     */
    public CompletableFuture<CreateComputeEnvironmentResponse> createComputeEnvironmentAsync(
        String computeEnvironmentName, String batchIAMRole, String subnet, String secGroup) {
        CreateComputeEnvironmentRequest environmentRequest = CreateComputeEnvironmentRequest.builder()
            .computeEnvironmentName(computeEnvironmentName)
            .type(CEType.MANAGED)
            .state(CEState.ENABLED)
            .computeResources(ComputeResource.builder()
                .type(CRType.FARGATE)
                .maxvCpus(256)
                .subnets(Collections.singletonList(subnet))
                .securityGroupIds(Collections.singletonList(secGroup))
                .build())
            .serviceRole(batchIAMRole)
            .build();

        CompletableFuture<CreateComputeEnvironmentResponse> response = getAsyncClient().createComputeEnvironment(environmentRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               String errorMessage = "Unexpected error occurred: " + ex.getMessage();
               throw new RuntimeException(errorMessage, ex);
            }
        });

        return response;
    }
```
+  For API details, see [CreateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateComputeEnvironment) in *AWS SDK for Java 2.x API Reference*. 

------
#### [ Python ]

**SDK for Python (Boto3)**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/batch#code-examples). 

```
    def create_compute_environment(
        self,
        compute_environment_name: str,
        subnet_ids: list,
        security_group_ids: list,
        max_vcpus: int = 4,
    ) -> dict:
        """
        Creates a managed Fargate compute environment.

        :param compute_environment_name: The name for the compute environment.
        :param subnet_ids: A list of subnet IDs for the compute resources.
        :param security_group_ids: A list of security group IDs.
        :param max_vcpus: Maximum number of vCPUs (default 4).
        :return: A dictionary with the compute environment name and ARN.
        """
        try:
            response = self.batch_client.create_compute_environment(
                computeEnvironmentName=compute_environment_name,
                type="MANAGED",
                state="ENABLED",
                computeResources={
                    "type": "FARGATE",
                    "maxvCpus": max_vcpus,
                    "subnets": subnet_ids,
                    "securityGroupIds": security_group_ids,
                },
            )
            logger.info(
                "Created compute environment %s: %s",
                response["computeEnvironmentName"],
                response["computeEnvironmentArn"],
            )
            return response
        except ClientError as err:
            logger.error(
                "Error creating compute environment %s: %s",
                compute_environment_name,
                err.response["Error"]["Message"],
            )
            raise
```
+  For API details, see [CreateComputeEnvironment](https://docs.aws.amazon.com/goto/boto3/batch-2016-08-10/CreateComputeEnvironment) in *AWS SDK for Python (Boto3) API Reference*. 

------