software.amazon.awssdk.services.ec2.Ec2Client Java Examples

The following examples show how to use software.amazon.awssdk.services.ec2.Ec2Client. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AwsEc2VolumeScannerTest.java    From clouditor with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void setUpOnce() throws IOException {
  discoverAssets(
      Ec2Client.class,
      AwsEc2VolumeScanner::new,
      api ->
          when(api.describeVolumes())
              .thenReturn(
                  DescribeVolumesResponse.builder()
                      .volumes(
                          Volume.builder()
                              .volumeId(NOT_ENCRYPTED_VOLUME_ID)
                              .encrypted(false)
                              .state(VolumeState.AVAILABLE)
                              .build(),
                          Volume.builder()
                              .volumeId(ENCRYPTED_VOLUME_ID)
                              .encrypted(true)
                              .state(VolumeState.AVAILABLE)
                              .build())
                      .build()));
}
 
Example #2
Source File: AllocateAddress.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply an instance id that you can obtain from the AWS Console\n" +
                    "Ex: AllocateAddress <instance_id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String instanceId = args[0];

    Region region = Region.US_EAST_1;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    System.out.println(getAllocateAddress(ec2, instanceId));
}
 
Example #3
Source File: DescribeReservedInstances.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void describeReservedEC2Instances( Ec2Client ec2, String instanceID) {
      try {
          DescribeReservedInstancesRequest request = DescribeReservedInstancesRequest.builder().reservedInstancesIds(instanceID).build();

          DescribeReservedInstancesResponse response =
              ec2.describeReservedInstances(request);

          for (ReservedInstances instance : response.reservedInstances()) {
              System.out.printf(
                  "Found a reserved instance with id %s, " +
                          "in AZ %s, " +
                          "type %s, " +
                          "state %s " +
                          "and monitoring state %s",
                  instance.reservedInstancesId(),
                  instance.availabilityZone(),
                  instance.instanceType(),
                  instance.state().name());
      }

      } catch (Ec2Exception e) {
          System.err.println(e.awsErrorDetails().errorMessage());
          System.exit(1);
  }
    // snippet-end:[ec2.java2.describe_reserved_instances.main]
}
 
Example #4
Source File: DescribeReservedInstances.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply a group id\n" +
                    "Ex: DescribeReservedInstances <vpc-id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String instanceID = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    describeReservedEC2Instances(ec2, instanceID);
}
 
Example #5
Source File: CreateKeyPair.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply a key pair name\n" +
                    "Ex: CreateKeyPair <key-pair-name>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String keyName = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    createEC2KeyPair(ec2, keyName) ;
}
 
Example #6
Source File: CreateKeyPair.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void createEC2KeyPair(Ec2Client ec2,String keyName ) {

        try {
            CreateKeyPairRequest request = CreateKeyPairRequest.builder()
                .keyName(keyName).build();

            CreateKeyPairResponse response = ec2.createKeyPair(request);
            System.out.printf(
                "Successfully created key pair named %s",
                keyName);

        } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        // snippet-end:[ec2.java2.create_key_pair.main]
      }
 
Example #7
Source File: MonitorInstance.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply an instance id and a monitoring " +
                    "status\n" +
                    "Ex: MonitorInstance <instance-id> <true|false>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String instanceId = args[0];
    boolean monitor = Boolean.valueOf(args[1]);

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    if (monitor) {
        monitorInstance(ec2, instanceId);
    } else {
        unmonitorInstance(ec2, instanceId);
    }
}
 
Example #8
Source File: DescribeAddresses.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void describeEC2Address(Ec2Client ec2 ) {

        DescribeAddressesResponse response = ec2.describeAddresses();

        for(Address address : response.addresses()) {
            System.out.printf(
                    "Found address with public IP %s, " +
                            "domain %s, " +
                            "allocation id %s " +
                            "and NIC id %s",
                    address.publicIp(),
                    address.domain(),
                    address.allocationId(),
                    address.networkInterfaceId());
        }
        // snippet-end:[ec2.java2.describe_addresses.main]
    }
 
Example #9
Source File: DescribeSecurityGroups.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void describeEC2SecurityGroups(Ec2Client ec2, String groupId) {

        try {

            DescribeSecurityGroupsRequest request =
                DescribeSecurityGroupsRequest.builder()
                        .groupIds(groupId).build();

            DescribeSecurityGroupsResponse response =
                ec2.describeSecurityGroups(request);

             for(SecurityGroup group : response.securityGroups()) {
                System.out.printf(
                    "Found security group with id %s, " +
                            "vpc id %s " +
                            "and description %s",
                    group.groupId(),
                    group.vpcId(),
                    group.description());
            }
        } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
         // snippet-end:[ec2.java2.describe_security_groups.main]
    }
 
Example #10
Source File: DescribeSecurityGroups.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply a group id\n" +
                    "Ex: DescribeSecurityGroups <group-id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String groupId = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    describeEC2SecurityGroups(ec2, groupId);

}
 
Example #11
Source File: DescribeKeyPairs.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void describeEC2Keys( Ec2Client ec2){

        try {
            DescribeKeyPairsResponse response = ec2.describeKeyPairs();

            for(KeyPairInfo keyPair : response.keyPairs()) {
                System.out.printf(
                    "Found key pair with name %s " +
                            "and fingerprint %s",
                    keyPair.keyName(),
                    keyPair.keyFingerprint());
             System.out.println("");
            }
        } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
         }
        // snippet-end:[ec2.java2.describe_key_pairs.main]
    }
 
Example #12
Source File: DeleteSecurityGroup.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void deleteEC2SecGroup(Ec2Client ec2,String groupId) {

        try {
            DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()
                .groupId(groupId)
                .build();

            DeleteSecurityGroupResponse response = ec2.deleteSecurityGroup(request);

            System.out.printf(
                "Successfully deleted security group with id %s", groupId);

        } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        // snippet-end:[ec2.java2.delete_security_group.main]
    }
 
Example #13
Source File: DeleteSecurityGroup.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply a security group id\n" +
                    "Ex: DeleteSecurityGroup <security-group-id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String groupId = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    deleteEC2SecGroup(ec2,groupId);
}
 
Example #14
Source File: TerminateInstance.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void terminateEC2( Ec2Client ec2, String instanceID) {

            try{
                TerminateInstancesRequest ti = TerminateInstancesRequest.builder()
                    .instanceIds(instanceID)
                    .build();

                TerminateInstancesResponse response = ec2.terminateInstances(ti);

                List<InstanceStateChange> list = response.terminatingInstances();

                for (int i = 0; i < list.size(); i++) {
                    InstanceStateChange sc = (list.get(i));
                    System.out.println("The ID of the terminated instance is "+sc.instanceId());
                }
            } catch (Ec2Exception e) {
                System.err.println(e.awsErrorDetails().errorMessage());
                System.exit(1);
            }
         }
 
Example #15
Source File: TerminateInstance.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply an instance id \n" +
                     "Ex: TerminateInstance <instance-id>\n";

    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String instanceID = args[0];

    // Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    terminateEC2(ec2, instanceID) ;
}
 
Example #16
Source File: ReleaseAddress.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply an allocation ID.\n" +
                    "Ex: ReleaseAddress <allocation_id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String allocId = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();
}
 
Example #17
Source File: CreateInstance.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply an instance name and AMI image id\n" +
                    "Both values can be obtained from the AWS Console\n" +
                    "Ex: CreateInstance <instance-name> <ami-image-id>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String name = args[0];
    String amiId = args[1];

    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    String instanceId = createEC2Instance(ec2,name, amiId) ;
    System.out.println("The instance ID is "+instanceId);
}
 
Example #18
Source File: RebootInstance.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply an instance id\n" +
                    "Ex: RebootInstance <instance_id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String instanceId = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    rebootEC2Instance(ec2, instanceId);
}
 
Example #19
Source File: AwsEc2VpcScannerTest.java    From clouditor with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void setUpOnce() throws IOException {
  discoverAssets(
      Ec2Client.class,
      AwsEc2VpcScanner::new,
      api -> {
        when(api.describeVpcs())
            .thenReturn(
                DescribeVpcsResponse.builder()
                    .vpcs(Vpc.builder().vpcId("vpc-1").build())
                    .build());

        when(api.describeStaleSecurityGroups(
                DescribeStaleSecurityGroupsRequest.builder().vpcId("vpc-1").build()))
            .thenReturn(
                DescribeStaleSecurityGroupsResponse.builder()
                    .staleSecurityGroupSet(
                        StaleSecurityGroup.builder().groupId("some-group").build())
                    .build());
      });
}
 
Example #20
Source File: ElbIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the AWS account info for the integration tests and creates an EC2
 * client for tests to use.
 */
@BeforeClass
public static void setUp() throws IOException {
    elb = ElasticLoadBalancingClient.builder()
            .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
            .region(REGION)
            .build();
    ec2 = Ec2Client.builder()
            .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
            .region(REGION)
            .build();
    iam = IamClient.builder()
            .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
            .region(Region.AWS_GLOBAL)
            .build();

    List<ServerCertificateMetadata> serverCertificates = iam.listServerCertificates(
            ListServerCertificatesRequest.builder().build()).serverCertificateMetadataList();
    if (!serverCertificates.isEmpty()) {
        certificateArn = serverCertificates.get(0).arn();
    }
}
 
Example #21
Source File: DeleteKeyPair.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply a key pair name\n" +
                    "Ex: DeleteKeyPair <key-pair-name>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String keyName = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    deleteKeys(ec2,keyName);
}
 
Example #22
Source File: GeneratePreSignUrlInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private URI createEndpoint(String regionName, String serviceName) {

        Region region = Region.of(regionName);

        if (region == null) {
            throw SdkClientException.builder()
                                    .message("{" + serviceName + ", " + regionName + "} was not "
                                             + "found in region metadata. Update to latest version of SDK and try again.")
                                    .build();
        }

        URI endpoint = Ec2Client.serviceMetadata().endpointFor(region);
        if (endpoint.getScheme() == null) {
            return URI.create("https://" + endpoint);
        }
        return endpoint;
    }
 
Example #23
Source File: DescribeVPCs.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void describeEC2Vpcs(Ec2Client ec2, String vpcId) {

        try {
            DescribeVpcsRequest request = DescribeVpcsRequest.builder()
                .vpcIds(vpcId)
                .build();

            DescribeVpcsResponse response =
                ec2.describeVpcs(request);

            for (Vpc vpc : response.vpcs()) {
                System.out.printf(
                    "Found vpc with id %s, " +
                            "vpc state %s " +
                            "and tennancy %s",
                    vpc.vpcId(),
                    vpc.stateAsString(),
                    vpc.instanceTenancyAsString());
                }
            } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        // snippet-end:[ec2.java2.describe_vpc.main]
    }
 
Example #24
Source File: DeleteKeyPair.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void deleteKeys(Ec2Client ec2, String keyName) {

       try {

           DeleteKeyPairRequest request = DeleteKeyPairRequest.builder()
                .keyName(keyName)
                .build();

           DeleteKeyPairResponse response = ec2.deleteKeyPair(request);

            // snippet-end:[ec2.java2.delete_key_pair.main]
            System.out.printf(
                "Successfully deleted key pair named %s", keyName);

        } catch (Ec2Exception e) {
           System.err.println(e.awsErrorDetails().errorMessage());
           System.exit(1);
        }
    }
 
Example #25
Source File: DescribeVPCs.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
            "To run this example, supply a group id\n" +
                    "Ex: DescribeVPCs <vpc-id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String vpcId = args[0];

    //Create an Ec2Client object
    Region region = Region.US_WEST_2;
    Ec2Client ec2 = Ec2Client.builder()
            .region(region)
            .build();

    describeEC2Vpcs(ec2, vpcId);
}
 
Example #26
Source File: AwsInstanceImageService.java    From greenbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("CodeBlock2Expr")
@Override
@Cacheable("AwsInstanceImageService")
public boolean isGreaterThanThreshold(int threshold, Tag includedTag, Tag excludedTag) {

    List<Image> images = regionService.regions()
            .stream()
            .map(region -> Ec2Client.builder().region(region).build())
            .map(client -> query(includedTag, client))
            .flatMap(Collection::stream)
            .filter(image -> {
                if (excludedTag == null)
                    return true;
                return image.tags().stream()
                        .noneMatch(tag -> tag.key().contentEquals(excludedTag.getKey()) && tag.value().contentEquals(excludedTag.getValue()));
            })
            .limit(threshold + 1)
            .collect(Collectors.toList());

    return images.size() > threshold;
}
 
Example #27
Source File: AwsComputeService.java    From greenbot with Apache License 2.0 6 votes vote down vote up
private List<Compute> list(List<Predicate<Compute>> predicates, Region region) {
    Ec2Client ec2Client = Ec2Client.builder().region(region).build();
    DescribeInstancesIterable describeInstancesResponses = ec2Client.describeInstancesPaginator();
    return describeInstancesResponses.reservations()
            .stream()
            .map(Reservation::instances)
            .flatMap(Collection::stream)
            .filter(instance -> {
                String name = instance.state().nameAsString();
                return equalsAnyIgnoreCase(name, "stopped", "running");
            })
            .map(instance -> convert(instance, region))
            .filter(Objects::nonNull)
            .filter(compute -> predicates.stream().allMatch(predicate -> predicate.test(compute)))
            .collect(toList());
}
 
Example #28
Source File: StartStopInstance.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void stopInstance(Ec2Client ec2, String instanceId) {

        StopInstancesRequest request = StopInstancesRequest.builder()
                .instanceIds(instanceId)
                .build();

        ec2.stopInstances(request);

        // snippet-end:[ec2.java2.start_stop_instance.stop]
        System.out.printf("Successfully stop instance %s", instanceId);
    }
 
Example #29
Source File: ReleaseAddress.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void releaseEC2Address(Ec2Client ec2,String allocId) {

        try {
            ReleaseAddressRequest request = ReleaseAddressRequest.builder()
                .allocationId(allocId).build();

            ReleaseAddressResponse response = ec2.releaseAddress(request);

         System.out.printf(
                "Successfully released elastic IP address %s", allocId);
        } catch (Ec2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
     }
 
Example #30
Source File: AWSEC2ServiceIntegrationTest.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setUp() throws IOException {


    Region region = Region.US_WEST_2;
    ec2 = Ec2Client.builder()
            .region(region)
            .build();

    try (InputStream input = AWSEC2ServiceIntegrationTest.class.getClassLoader().getResourceAsStream("config.properties")) {

        Properties prop = new Properties();

        if (input == null) {
            System.out.println("Sorry, unable to find config.properties");
            return;
        }

        //load a properties file from class path, inside static method
        prop.load(input);
        ami = prop.getProperty("ami");
        instanceName = prop.getProperty("instanceName");
        keyName = prop.getProperty("keyPair");
        groupName= prop.getProperty("groupName");
        groupDesc= prop.getProperty("groupDesc");
        vpcId= prop.getProperty("vpcId");

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}