Example usage for com.amazonaws.services.ec2.model Instance getSecurityGroups

List of usage examples for com.amazonaws.services.ec2.model Instance getSecurityGroups

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model Instance getSecurityGroups.

Prototype


public java.util.List<GroupIdentifier> getSecurityGroups() 

Source Link

Document

The security groups for the instance.

Usage

From source file:com.chimpler.example.hazelcast.AccountClient.java

License:Apache License

public static HazelcastInstance initHazelcastClient() throws Exception {
    ClientConfig hazelCastClientConfig = new ClientConfig();
    hazelCastClientConfig.getGroupConfig().setName("dev").setPassword("dev-pass");

    AWSCredentialsProvider awsCredentialProvider = new ClasspathPropertiesFileCredentialsProvider(
            "aws.properties");
    AmazonEC2Client ec2 = new AmazonEC2Client(awsCredentialProvider);
    DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
    System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
            + " Availability Zones.");

    DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();

    for (Reservation reservation : describeInstancesRequest.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            for (GroupIdentifier group : instance.getSecurityGroups()) {
                if (group.getGroupName().equals("jclouds#hazelcast")) {
                    System.out.println("EC2 instance " + instance.getPublicIpAddress());
                    hazelCastClientConfig.addAddress(instance.getPublicIpAddress(),
                            instance.getPublicIpAddress() + ":5701");
                }/* w ww .  j  a v a 2 s .  c  o  m*/
            }
        }
    }
    HazelcastInstance hazelCastClient = HazelcastClient.newHazelcastClient(hazelCastClientConfig);

    return hazelCastClient;
}

From source file:com.clouck.model.aws.ec2.Ec2Instance.java

@Override
@SuppressWarnings("rawtypes")
protected boolean isEqual(AbstractResource newResource) {
    Instance oldInstance = this.getResource();
    Ec2Instance newEc2Instance = (Ec2Instance) newResource;
    Instance newInstance = newEc2Instance.getResource();

    if (notEqual(oldInstance.getInstanceId(), newInstance.getInstanceId()))
        return false;
    if (notEqual(oldInstance.getImageId(), newInstance.getImageId()))
        return false;
    if (notEqual(oldInstance.getState(), newInstance.getState()))
        return false;
    if (notEqual(oldInstance.getPrivateDnsName(), newInstance.getPrivateDnsName()))
        return false;
    if (notEqual(oldInstance.getPublicDnsName(), newInstance.getPublicDnsName()))
        return false;
    if (notEqual(oldInstance.getStateTransitionReason(), newInstance.getStateTransitionReason()))
        return false;
    if (notEqual(oldInstance.getKeyName(), newInstance.getKeyName()))
        return false;
    if (notEqual(oldInstance.getAmiLaunchIndex(), newInstance.getAmiLaunchIndex()))
        return false;
    if (notEqualCollection(oldInstance.getProductCodes(), newInstance.getProductCodes()))
        return false;
    if (notEqual(oldInstance.getInstanceType(), newInstance.getInstanceType()))
        return false;
    if (notEqual(oldInstance.getLaunchTime(), newInstance.getLaunchTime()))
        return false;
    if (notEqual(oldInstance.getPlacement(), newInstance.getPlacement()))
        return false;
    if (notEqual(oldInstance.getKernelId(), newInstance.getKernelId()))
        return false;
    if (notEqual(oldInstance.getRamdiskId(), newInstance.getRamdiskId()))
        return false;
    if (notEqual(oldInstance.getPlatform(), newInstance.getPlatform()))
        return false;
    if (notEqual(oldInstance.getMonitoring(), newInstance.getMonitoring()))
        return false;
    if (notEqual(oldInstance.getSubnetId(), newInstance.getSubnetId()))
        return false;
    if (notEqual(oldInstance.getVpcId(), newInstance.getVpcId()))
        return false;
    if (notEqual(oldInstance.getPrivateIpAddress(), newInstance.getPrivateIpAddress()))
        return false;
    if (notEqual(oldInstance.getPublicIpAddress(), newInstance.getPublicIpAddress()))
        return false;
    if (notEqual(oldInstance.getStateReason(), newInstance.getStateReason()))
        return false;
    if (notEqual(oldInstance.getArchitecture(), newInstance.getArchitecture()))
        return false;
    if (notEqual(oldInstance.getRootDeviceType(), newInstance.getRootDeviceType()))
        return false;
    if (notEqual(oldInstance.getRootDeviceName(), newInstance.getRootDeviceName()))
        return false;
    if (notEqualCollection(oldInstance.getBlockDeviceMappings(), newInstance.getBlockDeviceMappings()))
        return false;
    if (notEqual(oldInstance.getVirtualizationType(), newInstance.getVirtualizationType()))
        return false;
    if (notEqual(oldInstance.getInstanceLifecycle(), newInstance.getInstanceLifecycle()))
        return false;
    if (notEqual(oldInstance.getSpotInstanceRequestId(), newInstance.getSpotInstanceRequestId()))
        return false;
    if (notEqual(oldInstance.getLicense(), newInstance.getLicense()))
        return false;
    if (notEqual(oldInstance.getClientToken(), newInstance.getClientToken()))
        return false;
    if (notEqualCollection(oldInstance.getTags(), newInstance.getTags()))
        return false;
    if (notEqualCollection(oldInstance.getSecurityGroups(), newInstance.getSecurityGroups()))
        return false;
    if (notEqual(oldInstance.getSourceDestCheck(), newInstance.getSourceDestCheck()))
        return false;
    if (notEqual(oldInstance.getHypervisor(), newInstance.getHypervisor()))
        return false;
    if (notEqualNetworkInterfaces(oldInstance.getNetworkInterfaces(), newInstance.getNetworkInterfaces()))
        return false;
    if (notEqual(oldInstance.getIamInstanceProfile(), newInstance.getIamInstanceProfile()))
        return false;
    if (notEqual(oldInstance.getEbsOptimized(), newInstance.getEbsOptimized()))
        return false;
    if (notEqual(this.getTerminationProtection(), newEc2Instance.getTerminationProtection()))
        return false;
    if (notEqual(this.getShutdownBehavior(), newEc2Instance.getShutdownBehavior()))
        return false;
    if (notEqual(this.getUserData(), newEc2Instance.getUserData()))
        return false;

    return true;/*from   w w  w .j  ava 2 s .c  o  m*/
}

From source file:com.netflix.simianarmy.aws.conformity.rule.InstanceInSecurityGroup.java

License:Apache License

/**
 * Gets the security groups for a list of instance ids of the same region. The default implementation
 * is using an AWS client. The method can be overridden in subclasses to get the security groups differently.
 * @param region/* w w w  .j a  va2 s. c  om*/
 *      the region of the instances
 * @param instanceIds
 *      the instance ids, all instances should be in the same region.
 * @return
 *      the map from instance id to the list of security group names the instance has
 */
protected Map<String, List<String>> getInstanceSecurityGroups(String region, String... instanceIds) {
    Map<String, List<String>> result = Maps.newHashMap();
    if (instanceIds == null || instanceIds.length == 0) {
        return result;
    }
    AWSClient awsClient = new AWSClient(region, awsCredentialsProvider);
    for (Instance instance : awsClient.describeInstances(instanceIds)) {
        // Ignore instances that are in VPC
        if (StringUtils.isNotEmpty(instance.getVpcId())) {
            LOGGER.info(String.format("Instance %s is in VPC and is ignored.", instance.getInstanceId()));
            continue;
        }

        if (!"running".equals(instance.getState().getName())) {
            LOGGER.info(String.format("Instance %s is not running, state is %s.", instance.getInstanceId(),
                    instance.getState().getName()));
            continue;
        }

        List<String> sgs = Lists.newArrayList();
        for (GroupIdentifier groupId : instance.getSecurityGroups()) {
            sgs.add(groupId.getGroupName());
        }
        result.put(instance.getInstanceId(), sgs);
    }
    return result;
}

From source file:com.urbancode.terraform.tasks.aws.InstanceTask.java

License:Apache License

private boolean verifySecurityGroups(Instance instance) {
    boolean result = false;
    List<String> expectedIds = new ArrayList<String>();
    for (SecurityGroupRefTask group : getSecurityGroupRefs()) {
        expectedIds.add(group.fetchSecurityGroup().getId());
    }//from  w w w  . j  av  a  2 s  .c om
    List<String> foundIds = new ArrayList<String>();
    List<GroupIdentifier> gids = instance.getSecurityGroups();
    if (gids != null && !gids.isEmpty()) {
        for (GroupIdentifier gid : gids) {
            foundIds.add(gid.getGroupId());
        }
    }

    return result;
}

From source file:jp.aws.test.ec2.EC2Instance.java

License:Apache License

/**
 * ?/* w ww  .  ja  v  a 2 s.  co  m*/
 *
 * @note - ????????
 * @return
 * @throws Exception
 */
public List<EC2Item> list() {

    List<EC2Item> ec2ItemList = new ArrayList<EC2Item>();

    // 
    this.clientManager.changeRegion();

    // Reservation?List?
    List<Reservation> reservationList = this.clientManager.ec2().describeInstances().getReservations();

    for (Reservation reservation : reservationList) {
        // EC2?Instance?List?
        List<Instance> instanceList = reservation.getInstances();

        for (Instance instance : instanceList) {
            EC2Item ec2Item = new EC2Item();

            // com.amazonaws.services.ec2.model.Instance
            // http://docs.amazonwebservices.com/AWSAndroidSDK/latest/javadoc/com/amazonaws/services/ec2/model/Instance.html
            ec2Item.architecture = instance.getArchitecture(); // i386,
            // x86_64
            ec2Item.instanceId = instance.getInstanceId(); // i-xxxxxxxx
            ec2Item.instanceType = instance.getInstanceType(); // t1.micro
            ec2Item.keyName = instance.getKeyName(); //
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ec2Item.launchTime = sdf.format(instance.getLaunchTime()); // 2012-01-01
            // 01:02:03
            // +9:00
            ec2Item.privateDnsName = instance.getPrivateDnsName(); // domU-xxx.compute-1.internal
            ec2Item.privateIpAddress = instance.getPrivateIpAddress(); // 10.xxx.xxx.xxx
            ec2Item.publicDnsName = instance.getPublicDnsName(); // ec2-xxx.compute-1.amazonaws.com
            ec2Item.publicIpAddress = instance.getPublicIpAddress(); // 201.xxx.xxx.xxx
            ec2Item.rootDeviceType = instance.getRootDeviceType(); // ebs /
            // s3
            ec2Item.rootDeviceName = instance.getRootDeviceName(); // /dev/sda1)
            StringBuilder builder = new StringBuilder();
            List<GroupIdentifier> sgs = instance.getSecurityGroups(); // default
            for (GroupIdentifier sg : sgs) {
                builder.append(sg.getGroupName());
                builder.append(", ");
            }
            ec2Item.securityGroups = builder.toString();
            ec2Item.stateName = instance.getState().getName(); // Runnning
            ec2Item.imageId = instance.getImageId(); // ami-xxxxxxxx
            ec2Item.platform = instance.getPlatform(); // Windows
            builder.setLength(0); // ?
            List<Tag> tags = instance.getTags(); // tag
            for (Tag tag : tags) {
                builder.append(tag.getValue());
                builder.append(", ");
            }
            ec2Item.availabilityZone = instance.getPlacement().getAvailabilityZone(); // AvailabilityZone

            // ?
            ec2ItemList.add(ec2Item);
        }
    }

    return ec2ItemList;
}

From source file:org.apache.airavata.gfac.ec2.EC2Provider.java

License:Apache License

/**
 * Checks whether the port 22 of the Amazon instance is accessible.
 *
 * @param instance Amazon instance id./*from  w w w  .  j  ava  2  s . c om*/
 * @param ec2client AmazonEC2Client object
 */
private void checkConnection(Instance instance, AmazonEC2Client ec2client) {
    /* Make sure port 22 is connectible */
    for (GroupIdentifier g : instance.getSecurityGroups()) {
        IpPermission ip = new IpPermission();
        ip.setIpProtocol("tcp");
        ip.setFromPort(SSH_PORT);
        ip.setToPort(SSH_PORT);
        AuthorizeSecurityGroupIngressRequest r = new AuthorizeSecurityGroupIngressRequest();
        r = r.withIpPermissions(ip.withIpRanges("0.0.0.0/0"));
        r.setGroupId(g.getGroupId());
        try {
            ec2client.authorizeSecurityGroupIngress(r);
        } catch (AmazonServiceException as) {
            /* If exception is from duplicate room, ignore it. */
            if (!as.getErrorCode().equals("InvalidPermission.Duplicate"))
                throw as;
        }
    }
}

From source file:org.elasticsearch.discovery.ec2.AwsEc2UnicastHostsProvider.java

License:Apache License

@Override
public List<DiscoveryNode> buildDynamicNodes() {
    List<DiscoveryNode> discoNodes = Lists.newArrayList();

    DescribeInstancesResult descInstances;
    try {/* w  w w.j  a  va2 s .  c o m*/
        // Query EC2 API based on AZ, instance state, and tag.

        // NOTE: we don't filter by security group during the describe instances request for two reasons:
        // 1. differences in VPCs require different parameters during query (ID vs Name)
        // 2. We want to use two different strategies: (all security groups vs. any security groups)
        descInstances = client.describeInstances(buildDescribeInstancesRequest());
    } catch (AmazonClientException e) {
        logger.info("Exception while retrieving instance list from AWS API: {}", e.getMessage());
        logger.debug("Full exception:", e);
        return discoNodes;
    }

    logger.trace("building dynamic unicast discovery nodes...");
    for (Reservation reservation : descInstances.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            // lets see if we can filter based on groups
            if (!groups.isEmpty()) {
                List<GroupIdentifier> instanceSecurityGroups = instance.getSecurityGroups();
                ArrayList<String> securityGroupNames = new ArrayList<String>();
                ArrayList<String> securityGroupIds = new ArrayList<String>();
                for (GroupIdentifier sg : instanceSecurityGroups) {
                    securityGroupNames.add(sg.getGroupName());
                    securityGroupIds.add(sg.getGroupId());
                }
                if (bindAnyGroup) {
                    // We check if we can find at least one group name or one group id in groups.
                    if (Collections.disjoint(securityGroupNames, groups)
                            && Collections.disjoint(securityGroupIds, groups)) {
                        logger.trace("filtering out instance {} based on groups {}, not part of {}",
                                instance.getInstanceId(), instanceSecurityGroups, groups);
                        // continue to the next instance
                        continue;
                    }
                } else {
                    // We need tp match all group names or group ids, otherwise we ignore this instance
                    if (!(securityGroupNames.containsAll(groups) || securityGroupIds.containsAll(groups))) {
                        logger.trace("filtering out instance {} based on groups {}, does not include all of {}",
                                instance.getInstanceId(), instanceSecurityGroups, groups);
                        // continue to the next instance
                        continue;
                    }
                }
            }

            String address = null;
            switch (hostType) {
            case PRIVATE_DNS:
                address = instance.getPrivateDnsName();
                break;
            case PRIVATE_IP:
                address = instance.getPrivateIpAddress();
                break;
            case PUBLIC_DNS:
                address = instance.getPublicDnsName();
                break;
            case PUBLIC_IP:
                address = instance.getPublicDnsName();
                break;
            }
            if (address != null) {
                try {
                    TransportAddress[] addresses = transportService.addressesFromString(address);
                    // we only limit to 1 addresses, makes no sense to ping 100 ports
                    for (int i = 0; (i < addresses.length && i < UnicastZenPing.LIMIT_PORTS_COUNT); i++) {
                        logger.trace("adding {}, address {}, transport_address {}", instance.getInstanceId(),
                                address, addresses[i]);
                        discoNodes.add(new DiscoveryNode("#cloud-" + instance.getInstanceId() + "-" + i,
                                addresses[i], Version.CURRENT));
                    }
                } catch (Exception e) {
                    logger.warn("failed ot add {}, address {}", e, instance.getInstanceId(), address);
                }
            } else {
                logger.trace("not adding {}, address is null, host_type {}", instance.getInstanceId(),
                        hostType);
            }
        }
    }

    logger.debug("using dynamic discovery nodes {}", discoNodes);

    return discoNodes;
}

From source file:org.occiware.clouddriver.util.InstanceDataFactory.java

License:Apache License

public static InstanceDO buildInstanceDataFromModel(Instance instance) {
    InstanceDO instanceDO = new InstanceDO();
    buildBasicInstanceData(instance, instanceDO);

    Placement placement = instance.getPlacement();
    if (placement != null) {
        PlacementDO placementDO = buildPlacementDO(instanceDO, placement);
        instanceDO.setPlacement(placementDO);
    }//from   w ww  .j a  v a2  s .  c  o m

    // Ebs volumes attached on instance.
    if (instance.getBlockDeviceMappings() != null && !instance.getBlockDeviceMappings().isEmpty()) {
        List<InstanceVolumeDO> instanceVolumeDOs = BuildInstanceVolumeDOs(instance);
        instanceDO.setVolumes(instanceVolumeDOs);
    }

    if (instance.getIamInstanceProfile() != null) {
        IamInstanceProfileDO profileDO = buildIamInstanceProfileDO(instance);
        instanceDO.setIamInstanceProfile(profileDO);
    }

    if (instance.getMonitoring() != null) {
        Monitoring monitoring = instance.getMonitoring();
        instanceDO.setMonitoringState(monitoring.getState());
    }

    // Network part.
    if (instance.getNetworkInterfaces() != null && !instance.getNetworkInterfaces().isEmpty()) {
        List<NetworkInterfaceDO> networkInterfaceDOs = buildNetworkInterfacesDatas(instance);
        instanceDO.setNetworkAdapters(networkInterfaceDOs);
    }

    List<ProductCode> productCodes = instance.getProductCodes();
    if (productCodes != null && !productCodes.isEmpty()) {
        List<ProductCodeDO> productCodeDOs = buildProductCodesDatas(productCodes);
        instanceDO.setProductCodes(productCodeDOs);
    }

    List<GroupIdentifier> groups = instance.getSecurityGroups();
    if (groups != null && !groups.isEmpty()) {
        List<GroupIdentifierDO> groupIdentifierDOs = buildSecurityGroupsDatas(groups);
        instanceDO.setSecurityGroups(groupIdentifierDOs);
    }

    InstanceState state = instance.getState();
    if (state != null) {
        instanceDO.setInstanceState(state.getName());
        instanceDO.setInstanceStateCode(state.getCode());
        StateReason stateReason = instance.getStateReason();
        if (stateReason != null) {
            instanceDO.setInstanceStateReasonMessage(stateReason.getMessage());
            instanceDO.setInstanceStateReasonCode(stateReason.getCode());
        }
    }

    List<Tag> tags = instance.getTags();
    if (tags != null && !tags.isEmpty()) {
        List<TagDO> tagDOs = buildTagsDatas(tags);
        instanceDO.setTags(tagDOs);
    }
    return instanceDO;
}