Search in sources :

Example 16 with SecurityGroup

use of software.amazon.awssdk.services.ec2.model.SecurityGroup in project photon-model by vmware.

the class TestAWSSetupUtils method tearDownTestVpc.

public static void tearDownTestVpc(AmazonEC2AsyncClient client, VerificationHost host, Map<String, Object> awsTestContext, boolean isMock) {
    // if we feel the need to delete resources on every test run.
    if (!isMock && awsTestContext.containsKey(DELETE_RESOURCES_KEY)) {
        final String vpcId = (String) awsTestContext.get(VPC_KEY);
        final String subnetId = (String) awsTestContext.get(SUBNET_KEY);
        final String internetGatewayId = (String) awsTestContext.get(INTERNET_GATEWAY_KEY);
        final String securityGroupId = (String) awsTestContext.get(SECURITY_GROUP_KEY);
        // clean up VPC and all its dependencies if creating one at setUp
        deleteSecurityGroupUsingEC2Client(client, host, securityGroupId);
        SecurityGroup securityGroup = new AWSSecurityGroupClient(client).getSecurityGroup(AWS_DEFAULT_GROUP_NAME, vpcId);
        if (securityGroup != null) {
            deleteSecurityGroupUsingEC2Client(client, host, securityGroup.getGroupId());
        }
        deleteSubnet(client, subnetId);
        detachInternetGateway(client, vpcId, internetGatewayId);
        deleteInternetGateway(client, internetGatewayId);
        deleteVPC(client, vpcId);
    }
}
Also used : AWSSecurityGroupClient(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSSecurityGroupClient) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup)

Example 17 with SecurityGroup

use of software.amazon.awssdk.services.ec2.model.SecurityGroup in project cloudbreak by hortonworks.

the class AwsPlatformResources method securityGroups.

@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
    Set<CloudSecurityGroup> cloudSecurityGroups = new HashSet<>();
    AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), region.value());
    // create securitygroup filter view
    PlatformResourceSecurityGroupFilterView filter = new PlatformResourceSecurityGroupFilterView(filters);
    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    // If the filtervalue is provided then we should filter only for those securitygroups
    if (!Strings.isNullOrEmpty(filter.getVpcId())) {
        describeSecurityGroupsRequest.withFilters(new Filter("vpc-id", singletonList(filter.getVpcId())));
    }
    if (!Strings.isNullOrEmpty(filter.getGroupId())) {
        describeSecurityGroupsRequest.withGroupIds(filter.getGroupId());
    }
    if (!Strings.isNullOrEmpty(filter.getGroupName())) {
        describeSecurityGroupsRequest.withGroupNames(filter.getGroupName());
    }
    for (SecurityGroup securityGroup : ec2Client.describeSecurityGroups(describeSecurityGroupsRequest).getSecurityGroups()) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("vpcId", securityGroup.getVpcId());
        properties.put("description", securityGroup.getDescription());
        properties.put("ipPermissions", securityGroup.getIpPermissions());
        properties.put("ipPermissionsEgress", securityGroup.getIpPermissionsEgress());
        cloudSecurityGroups.add(new CloudSecurityGroup(securityGroup.getGroupName(), securityGroup.getGroupId(), properties));
    }
    result.put(region.value(), cloudSecurityGroups);
    return new CloudSecurityGroups(result);
}
Also used : AmazonEC2Client(com.amazonaws.services.ec2.AmazonEC2Client) PlatformResourceSecurityGroupFilterView(com.sequenceiq.cloudbreak.cloud.model.view.PlatformResourceSecurityGroupFilterView) DescribeSecurityGroupsRequest(com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) CloudSecurityGroup(com.sequenceiq.cloudbreak.cloud.model.CloudSecurityGroup) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView) Filter(com.amazonaws.services.ec2.model.Filter) CloudSecurityGroups(com.sequenceiq.cloudbreak.cloud.model.CloudSecurityGroups) CloudSecurityGroup(com.sequenceiq.cloudbreak.cloud.model.CloudSecurityGroup) HashSet(java.util.HashSet)

Example 18 with SecurityGroup

use of software.amazon.awssdk.services.ec2.model.SecurityGroup in project aws-doc-sdk-examples by awsdocs.

the class DescribeSecurityGroups method main.

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 group_id = args[0];
    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupIds(group_id);
    DescribeSecurityGroupsResult response = ec2.describeSecurityGroups(request);
    for (SecurityGroup group : response.getSecurityGroups()) {
        System.out.printf("Found security group with id %s, " + "vpc id %s " + "and description %s", group.getGroupId(), group.getVpcId(), group.getDescription());
    }
}
Also used : DescribeSecurityGroupsRequest(com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) DescribeSecurityGroupsResult(com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup)

Example 19 with SecurityGroup

use of software.amazon.awssdk.services.ec2.model.SecurityGroup in project GNS by MobilityFirst.

the class AWSStatusCheck method main.

/**
   *
   * @param args
   * @throws Exception
   */
public static void main(String[] args) throws Exception {
    init();
    /*
     * Amazon EC2
     */
    for (String endpoint : endpoints) {
        try {
            ec2.setEndpoint(endpoint);
            System.out.println("**** Endpoint: " + endpoint);
            DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
            System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones.");
            for (AvailabilityZone zone : availabilityZonesResult.getAvailabilityZones()) {
                System.out.println(zone.getZoneName());
            }
            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            Set<Instance> instances = new HashSet<Instance>();
            System.out.println("Instances: ");
            for (Reservation reservation : reservations) {
                for (Instance instance : reservation.getInstances()) {
                    instances.add(instance);
                    System.out.println(instance.getPublicDnsName() + " is " + instance.getState().getName());
                }
            }
            System.out.println("Security groups: ");
            DescribeSecurityGroupsResult describeSecurityGroupsResult = ec2.describeSecurityGroups();
            for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) {
                System.out.println(securityGroup.getGroupName());
            }
        //System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }
        /*
       * Amazon SimpleDB
       *
       */
        try {
            ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100);
            ListDomainsResult sdbResult = sdb.listDomains(sdbRequest);
            int totalItems = 0;
            for (String domainName : sdbResult.getDomainNames()) {
                DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName);
                DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest);
                totalItems += domainMetadata.getItemCount();
            }
            System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)" + "containing a total of " + totalItems + " items.");
        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }
        /*
       * Amazon S3
       *.
       */
        try {
            List<Bucket> buckets = s3.listBuckets();
            long totalSize = 0;
            int totalItems = 0;
            for (Bucket bucket : buckets) {
                /*
           * In order to save bandwidth, an S3 object listing does not
           * contain every object in the bucket; after a certain point the
           * S3ObjectListing is truncated, and further pages must be
           * obtained with the AmazonS3Client.listNextBatchOfObjects()
           * method.
           */
                ObjectListing objects = s3.listObjects(bucket.getName());
                do {
                    for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                        totalSize += objectSummary.getSize();
                        totalItems++;
                    }
                    objects = s3.listNextBatchOfObjects(objects);
                } while (objects.isTruncated());
            }
            System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing " + totalItems + " objects with a total size of " + totalSize + " bytes.");
        } catch (AmazonServiceException ase) {
            /*
         * AmazonServiceExceptions represent an error response from an AWS
         * services, i.e. your request made it to AWS, but the AWS service
         * either found it invalid or encountered an error trying to execute
         * it.
         */
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            /*
         * AmazonClientExceptions represent an error that occurred inside
         * the client on the local host, either while trying to send the
         * request to AWS or interpret the response. For example, if no
         * network connection is available, the client won't be able to
         * connect to AWS to execute a request and will throw an
         * AmazonClientException.
         */
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}
Also used : ListDomainsResult(com.amazonaws.services.simpledb.model.ListDomainsResult) Instance(com.amazonaws.services.ec2.model.Instance) DomainMetadataResult(com.amazonaws.services.simpledb.model.DomainMetadataResult) AmazonClientException(com.amazonaws.AmazonClientException) AvailabilityZone(com.amazonaws.services.ec2.model.AvailabilityZone) ObjectListing(com.amazonaws.services.s3.model.ObjectListing) S3ObjectSummary(com.amazonaws.services.s3.model.S3ObjectSummary) DescribeAvailabilityZonesResult(com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) DomainMetadataRequest(com.amazonaws.services.simpledb.model.DomainMetadataRequest) Reservation(com.amazonaws.services.ec2.model.Reservation) Bucket(com.amazonaws.services.s3.model.Bucket) ListDomainsRequest(com.amazonaws.services.simpledb.model.ListDomainsRequest) AmazonServiceException(com.amazonaws.AmazonServiceException) DescribeSecurityGroupsResult(com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult) HashSet(java.util.HashSet)

Example 20 with SecurityGroup

use of software.amazon.awssdk.services.ec2.model.SecurityGroup in project GNS by MobilityFirst.

the class AWSEC2 method createAndInitInstance.

/**
   * Creates an EC2 instance in the region given. Timeout in milleseconds can be specified.
   *
   * @param ec2
   * @param region
   * @param amiRecord
   * @param instanceName
   * @param keyName
   * @param securityGroupName
   * @param script
   * @param tags
   * @param elasticIP
   * @param timeout
   * @return a new instance instance
   */
public static Instance createAndInitInstance(AmazonEC2 ec2, RegionRecord region, AMIRecord amiRecord, String instanceName, String keyName, String securityGroupName, String script, Map<String, String> tags, String elasticIP, int timeout) {
    try {
        // set the region (AKA endpoint)
        setRegion(ec2, region);
        // create the instance
        SecurityGroup securityGroup = findOrCreateSecurityGroup(ec2, securityGroupName);
        String keyPair = findOrCreateKeyPair(ec2, keyName);
        String instanceID = createInstanceAndWait(ec2, amiRecord, keyPair, securityGroup);
        if (instanceID == null) {
            return null;
        }
        System.out.println("Instance " + instanceName + " is running in " + region.name());
        // add a name to the instance
        addInstanceTag(ec2, instanceID, "Name", instanceName);
        if (tags != null) {
            addInstanceTags(ec2, instanceID, tags);
        }
        Instance instance = findInstance(ec2, instanceID);
        if (instance == null) {
            return null;
        }
        String hostname = instance.getPublicDnsName();
        System.out.println("Waiting " + timeout / 1000 + " seconds for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable.");
        long startTime = System.currentTimeMillis();
        while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
            ThreadUtils.sleep(1000);
            System.out.print(".");
            if (System.currentTimeMillis() - startTime > timeout) {
                System.out.println(instanceName + " (" + hostname + ")" + " timed out during reachability check.");
                return null;
            }
        }
        System.out.println();
        System.out.println(instanceName + " (" + hostname + ")" + " is reachable.");
        // associate the elasticIP if one is provided
        if (elasticIP != null) {
            System.out.println("Using ElasticIP " + elasticIP + " for instance " + instanceName + " (" + instanceID + ")");
            AWSEC2.associateAddress(ec2, elasticIP, instance);
            // get a new copy cuz things have changed
            instance = findInstance(ec2, instanceID);
            if (instance == null) {
                return null;
            }
            // recheck reachability
            hostname = instance.getPublicDnsName();
            System.out.println("Waiting " + timeout / 1000 + " s for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable after Elastic IP change.");
            startTime = System.currentTimeMillis();
            while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
                ThreadUtils.sleep(1000);
                System.out.print(".");
                if (System.currentTimeMillis() - startTime > timeout) {
                    // give it a minute and ahalf
                    System.out.println(instanceName + " (" + hostname + ")" + " timed out during second (elastic IP) reachability check.");
                    return null;
                }
            }
            System.out.println();
            System.out.println(instanceName + " (" + hostname + ")" + " is still reachable.");
        }
        if (script != null) {
            File keyFile = new File(KEYHOME + FILESEPARATOR + keyName + PRIVATEKEYFILEEXTENSION);
            ExecuteBash.executeBashScript("ec2-user", hostname, keyFile, true, "installScript.sh", script);
        }
        return instance;
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
    return null;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) AmazonServiceException(com.amazonaws.AmazonServiceException) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) File(java.io.File)

Aggregations

SecurityGroup (com.amazonaws.services.ec2.model.SecurityGroup)31 DescribeSecurityGroupsResult (com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult)12 DescribeSecurityGroupsRequest (com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest)11 Test (org.junit.Test)10 IpPermission (com.amazonaws.services.ec2.model.IpPermission)9 ArrayList (java.util.ArrayList)8 Instance (com.amazonaws.services.ec2.model.Instance)7 HashMap (java.util.HashMap)7 AmazonEC2AsyncClient (com.amazonaws.services.ec2.AmazonEC2AsyncClient)6 SecurityGroupState (com.vmware.photon.controller.model.resources.SecurityGroupService.SecurityGroupState)6 Operation (com.vmware.xenon.common.Operation)6 Utils (com.vmware.xenon.common.Utils)6 Map (java.util.Map)6 Filter (com.amazonaws.services.ec2.model.Filter)5 Collections (java.util.Collections)5 List (java.util.List)5 TimeUnit (java.util.concurrent.TimeUnit)5 Level (java.util.logging.Level)5 Collectors (java.util.stream.Collectors)5 Before (org.junit.Before)5