com.amazonaws.services.ec2.model.DescribeKeyPairsRequest Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.DescribeKeyPairsRequest. 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: AwsIaasGatewayScriptService.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void importKeyPair(String keyName, String publicKey) throws AutoException {
    // キーペアがすでに登録されていたら何もしない
    DescribeKeyPairsRequest request = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult result = ec2Client.describeKeyPairs(request);
    List<KeyPairInfo> keyPairs = result.getKeyPairs();

    for (KeyPairInfo keyPair : keyPairs) {
        if (keyPair.getKeyName().equals(keyName)) {
            log.info(platform.getPlatformName() + " の " + keyName + " はすでに登録されている為、キーのインポートをスキップします");
            System.out.println("IMPORT_SKIPPED");
            return;
        }
    }

    // インポート
    ImportKeyPairRequest request2 = new ImportKeyPairRequest();
    request2.withKeyName(keyName);
    request2.withPublicKeyMaterial(publicKey);
    ec2Client.importKeyPair(request2);

    log.info(keyName + "のキーをインポートしました。");
}
 
Example #2
Source File: AwsSetup.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void validateExistingKeyPair(InstanceAuthentication instanceAuthentication, AwsCredentialView credentialView, String region,
        AuthenticatedContext ac) {
    String keyPairName = awsClient.getExistingKeyPairName(instanceAuthentication);
    if (StringUtils.isNotEmpty(keyPairName)) {
        boolean keyPairIsPresentOnEC2 = false;
        try {
            AmazonEC2Client client = new AuthenticatedContextView(ac).getAmazonEC2Client();
            DescribeKeyPairsResult describeKeyPairsResult = client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName));
            keyPairIsPresentOnEC2 = describeKeyPairsResult.getKeyPairs().stream().findFirst().isPresent();
        } catch (RuntimeException e) {
            String errorMessage = String.format("Failed to get the key pair [name: '%s'] from EC2 [roleArn:'%s'], detailed message: %s.",
                    keyPairName, credentialView.getRoleArn(), e.getMessage());
            LOGGER.info(errorMessage, e);
        }
        if (!keyPairIsPresentOnEC2) {
            throw new CloudConnectorException(String.format("The key pair '%s' could not be found in the '%s' region of EC2.", keyPairName, region));
        }
    }
}
 
Example #3
Source File: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<KeyPairInfo> getKeyPairs(Long userNo, Long platformNo) {
    // キーペアを取得
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo);
    DescribeKeyPairsRequest request = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult result = awsProcessClient.getEc2Client().describeKeyPairs(request);
    List<KeyPairInfo> keyPairs = result.getKeyPairs();

    // ソート
    Collections.sort(keyPairs, Comparators.COMPARATOR_KEY_PAIR_INFO);

    return keyPairs;
}
 
Example #4
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public KeyPairCollection getKeyPairs(DescribeKeyPairsRequest request) {
    ResourceCollectionImpl result = service.getCollection("KeyPairs",
            request);

    if (result == null) return null;
    return new KeyPairCollectionImpl(result);
}
 
Example #5
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudSshKeys sshKeys(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSshKey>> result = new HashMap<>();
    for (Region actualRegion : regions(cloudCredential, region, new HashMap<>(), true).getCloudRegions().keySet()) {
        // If region is provided then should filter for those region
        if (regionMatch(actualRegion, region)) {
            Set<CloudSshKey> cloudSshKeys = new HashSet<>();
            AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), actualRegion.value());

            //create sshkey filter view
            PlatformResourceSshKeyFilterView filter = new PlatformResourceSshKeyFilterView(filters);

            DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();

            // If the filtervalue is provided then we should filter only for those securitygroups
            if (!Strings.isNullOrEmpty(filter.getKeyName())) {
                describeKeyPairsRequest.withKeyNames(filter.getKeyName());
            }

            for (KeyPairInfo keyPairInfo : ec2Client.describeKeyPairs(describeKeyPairsRequest).getKeyPairs()) {
                Map<String, Object> properties = new HashMap<>();
                properties.put("fingerPrint", keyPairInfo.getKeyFingerprint());
                cloudSshKeys.add(new CloudSshKey(keyPairInfo.getKeyName(), properties));
            }
            result.put(actualRegion.value(), cloudSshKeys);
        }
    }
    return new CloudSshKeys(result);
}
 
Example #6
Source File: AwsPublicKeyConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private boolean exists(AmazonEC2Client client, String publicKeyId) {
    try {
        client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(publicKeyId));
        LOGGER.debug("Key-pair already exists: {}", publicKeyId);
        return true;
    } catch (AmazonServiceException e) {
        LOGGER.debug("Key-pair does not exist: {}", publicKeyId);
    }
    return false;
}
 
Example #7
Source File: KeyPairImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public boolean load(DescribeKeyPairsRequest request) {
    return load(request, null);
}
 
Example #8
Source File: KeyPairImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public boolean load(DescribeKeyPairsRequest request,
        ResultCapture<DescribeKeyPairsResult> extractor) {

    return resource.load(request, extractor);
}
 
Example #9
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public KeyPairCollection getKeyPairs() {
    return getKeyPairs((DescribeKeyPairsRequest)null);
}
 
Example #10
Source File: EC2Application.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {
   
    // Set up the client
    AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion(Regions.US_EAST_1)
        .build();

    // Create a security group
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
        .withDescription("Baeldung Security Group");
    ec2Client.createSecurityGroup(createSecurityGroupRequest);

    // Allow HTTP and SSH traffic
    IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");

    IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(80)
        .withToPort(80);

    IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(22)
        .withToPort(22);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
        .withGroupName("BaeldungSecurityGroup")
        .withIpPermissions(ipPermission1, ipPermission2);

    ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    // Create KeyPair
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
        .withKeyName("baeldung-key-pair");
    CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
    String privateKey = createKeyPairResult
        .getKeyPair()
        .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key

    // See what key-pairs you've got
    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);

    // Launch an Amazon Instance
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
        .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
        .withSecurityGroups("BaeldungSecurityGroup");

    String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();

    // Start an Instance
    StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.startInstances(startInstancesRequest);

    // Monitor Instances
    MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.monitorInstances(monitorInstancesRequest);

    UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.unmonitorInstances(unmonitorInstancesRequest);

    // Reboot an Instance

    RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.rebootInstances(rebootInstancesRequest);

    // Stop an Instance
    StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.stopInstances(stopInstancesRequest)
        .getStoppingInstances()
        .get(0)
        .getPreviousState()
        .getName();

    // Describe an Instance
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
    System.out.println(response.getReservations()
        .get(0)
        .getInstances()
        .get(0)
        .getKernelId());
}
 
Example #11
Source File: EC2.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves the KeyPairs collection referenced by this resource.
 */
KeyPairCollection getKeyPairs(DescribeKeyPairsRequest request);
 
Example #12
Source File: KeyPair.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet.
 * The following request parameters will be populated from the data of this
 * <code>KeyPair</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>KeyNames.0</code></b>
 *         - mapped from the <code>Name</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see DescribeKeyPairsRequest
 */
boolean load(DescribeKeyPairsRequest request);
 
Example #13
Source File: KeyPair.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet, and use a ResultCapture to retrieve the low-level
 * client response
 * The following request parameters will be populated from the data of this
 * <code>KeyPair</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>KeyNames.0</code></b>
 *         - mapped from the <code>Name</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see DescribeKeyPairsRequest
 */
boolean load(DescribeKeyPairsRequest request,
        ResultCapture<DescribeKeyPairsResult> extractor);