List of usage examples for com.amazonaws.services.ec2 AmazonEC2 authorizeSecurityGroupIngress
AuthorizeSecurityGroupIngressResult authorizeSecurityGroupIngress( AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest);
Adds the specified ingress rules to a security group.
From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java
License:Apache License
/** * Creates the app specific security group, or returns the ID of one if it already exists * * @param appGroups list of existing security groups in which to look for existing app security group * @param elbGroup the elb specific security group, which will allow ingress permission from the * app specific security group *//* w ww .j av a 2 s . co m*/ protected void buildApplicationSecurityGroup(LoadBalancerDescription sourceDescription, List<SecurityGroup> appGroups, MigrateSecurityGroupResult elbGroup) { if (getDeployDefaults().getAddAppGroupToServerGroup()) { AmazonEC2 targetAmazonEC2 = getAmazonClientProvider().getAmazonEC2(target.getCredentials(), target.getRegion(), true); Optional<SecurityGroup> existing = appGroups.stream().filter(isAppSecurityGroup()).findFirst(); MigrateSecurityGroupReference appGroupReference = new MigrateSecurityGroupReference(); appGroupReference.setAccountId(target.getCredentials().getAccountId()); appGroupReference.setVpcId(target.getVpcId()); appGroupReference.setTargetName(applicationName); if (existing.isPresent()) { elbGroup.getReused().add(appGroupReference); } else { elbGroup.getCreated().add(appGroupReference); if (!dryRun) { UpsertSecurityGroupDescription upsertDescription = new UpsertSecurityGroupDescription(); upsertDescription.setDescription("Application security group for " + applicationName); upsertDescription.setName(applicationName); upsertDescription.setVpcId(target.getVpcId()); upsertDescription.setRegion(target.getRegion()); upsertDescription.setCredentials(target.getCredentials()); getTask().updateStatus(LoadBalancerMigrator.BASE_PHASE, "Creating security group " + upsertDescription.getName() + " in " + target.getCredentialAccount() + "/" + target.getRegion() + "/" + target.getVpcId()); String newGroupId = targetLookup.createSecurityGroup(upsertDescription).getSecurityGroup() .getGroupId(); // After the create request completes, there is a brief period where the security group might not be // available and subsequent operations on it will fail, so make sure it's there OperationPoller.retryWithBackoff(o -> appGroups.addAll(targetAmazonEC2 .describeSecurityGroups(new DescribeSecurityGroupsRequest().withGroupIds(newGroupId)) .getSecurityGroups()), 200, 5); } } if (!dryRun) { String elbGroupId = elbGroup.getTarget().getTargetId(); SecurityGroup appGroup = appGroups.stream().filter(isAppSecurityGroup()).findFirst().get(); if (allowIngressFromClassic) { addClassicLinkIngress(targetLookup, getDeployDefaults().getClassicLinkSecurityGroupName(), appGroup.getGroupId(), target.getCredentials(), target.getVpcId()); } boolean hasElbIngressPermission = appGroup.getIpPermissions().stream().anyMatch( p -> p.getUserIdGroupPairs().stream().anyMatch(u -> u.getGroupId().equals(elbGroupId))); if (!hasElbIngressPermission) { sourceDescription.getListenerDescriptions().forEach(l -> { Listener listener = l.getListener(); IpPermission newPermission = new IpPermission().withIpProtocol("tcp") .withFromPort(listener.getInstancePort()).withToPort(listener.getInstancePort()) .withUserIdGroupPairs( new UserIdGroupPair().withGroupId(elbGroupId).withVpcId(target.getVpcId())); targetAmazonEC2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() .withGroupId(appGroup.getGroupId()).withIpPermissions(newPermission)); }); } } } }
From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java
License:Apache License
private void addPublicIngress(AmazonEC2 targetAmazonEC2, String elbGroupId, LoadBalancerDescription sourceDescription) { List<IpPermission> permissions = sourceDescription.getListenerDescriptions().stream() .map(l -> new IpPermission().withIpProtocol("tcp") .withFromPort(l.getListener().getLoadBalancerPort()) .withToPort(l.getListener().getLoadBalancerPort()).withIpRanges("0.0.0.0/0")) .collect(Collectors.toList()); targetAmazonEC2.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest().withGroupId(elbGroupId).withIpPermissions(permissions)); }
From source file:com.urbancode.terraform.tasks.aws.helpers.AWSHelper.java
License:Apache License
/** * * @param groupId//from ww w.j a v a 2 s . c o m * @param protocol * @param startPort * @param endPort * @param cidr * @param inbound * @param ec2Client */ public void createRuleForSecurityGroup(String groupId, String protocol, int startPort, int endPort, String cidr, boolean inbound, AmazonEC2 ec2Client) { try { // protocol should be lowercase protocol = protocol.toLowerCase(); // create container for request // we need to use IpPermission object here because the other (old) way // is deprecated and no longer works IpPermission perm = new IpPermission().withFromPort(startPort).withToPort(endPort) .withIpProtocol(protocol).withIpRanges(cidr); if (inbound) { // inbound rule AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest() .withGroupId(groupId).withIpPermissions(perm); ec2Client.authorizeSecurityGroupIngress(request); } else { // outbound rule AuthorizeSecurityGroupEgressRequest request = new AuthorizeSecurityGroupEgressRequest() .withGroupId(groupId).withIpPermissions(perm); ec2Client.authorizeSecurityGroupEgress(request); } } catch (AmazonServiceException e) { log.error("Failed to create Rule on Security Group " + groupId, e); if (!"InvalidGroup.NotFound".equalsIgnoreCase(e.getErrorCode())) { throw e; } } }
From source file:datameer.awstasks.ant.ec2.Ec2LaunchTask.java
License:Apache License
@Override public void doExecute(AmazonEC2 ec2) throws BuildException { LOG.info("executing " + getClass().getSimpleName() + " with groupName '" + _groupName + "'"); try {/* ww w. j a v a2 s. co m*/ boolean instancesRunning = Ec2Util.findByGroup(ec2, _groupName, false, InstanceStateName.Pending, InstanceStateName.Running) != null; if (!isReuseRunningInstances() && instancesRunning) { throw new IllegalStateException("found already running instances for group '" + _groupName + "'"); } if (!Ec2Util.groupExists(ec2, _groupName)) { LOG.info("group '" + _groupName + "' does not exists - creating it"); String groupDescription = getGroupDescription(); if (groupDescription == null) { throw new BuildException("must specify groupDescription"); } ec2.createSecurityGroup(new CreateSecurityGroupRequest(_groupName, groupDescription)); } List<String> securityGroups = Arrays.asList("default", _groupName); List<IpPermission> existingPermissions = Ec2Util.getPermissions(ec2, securityGroups); for (GroupPermission groupPermission : _groupPermissions) { if (groupPermission.getToPort() == -1) { groupPermission.setToPort(groupPermission.getFromPort()); } if (!permissionExists(groupPermission, existingPermissions)) { LOG.info("did not found permission '" + groupPermission + "' - creating it..."); ec2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() .withGroupName(_groupName).withIpPermissions(groupPermission.toIpPermission())); } } InstanceGroup instanceGroup = new InstanceGroupImpl(ec2); RunInstancesRequest launchConfiguration = new RunInstancesRequest(_ami, _instanceCount, _instanceCount); if (_kernelId != null) { launchConfiguration.setKernelId(_kernelId); } if (_ramDiskId != null) { launchConfiguration.setKernelId(_ramDiskId); } launchConfiguration.setKeyName(_privateKeyName); launchConfiguration.setSecurityGroups(securityGroups); if (_userData != null) { launchConfiguration.setUserData(Base64.encodeBase64String(_userData.getBytes())); } if (_instanceType != null) { launchConfiguration.setInstanceType(_instanceType); } launchConfiguration.setPlacement(new Placement(_availabilityZone)); if (instancesRunning) { instanceGroup.connectTo(_groupName); } else { instanceGroup.launch(launchConfiguration, TimeUnit.MINUTES, _maxStartTime); if (_instanceName != null) { LOG.info("tagging instances with name '" + _instanceName + " [<idx>]'"); int idx = 1; for (Instance instance : instanceGroup.getInstances(false)) { CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.withResources(instance.getInstanceId()) // .withTags(new Tag("Name", _instanceName + " [" + idx + "]")); ec2.createTags(createTagsRequest); idx++; } } } } catch (Exception e) { LOG.error("execution " + getClass().getSimpleName() + " with groupName '" + _groupName + "' failed: " + e.getMessage()); throw new BuildException(e); } }
From source file:DynamicProvisioning.SecGroupCreate.java
License:Open Source License
public static void main(String[] args) { AWSCredentials credentials = null;//from ww w.j a v a2 s . c om try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (/home/jay2106/.aws/credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); ec2.setRegion(usWest2); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("launch-wizard-3", "launch-wizard-3"); CreateSecurityGroupResult result = ec2.createSecurityGroup(securityGroupRequest); System.out.println(String.format("Security group created: [%s]", result.getGroupId())); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList(ipAddr); List<IpPermission> ipPermission = new ArrayList<IpPermission>(); ipPermission.add(new IpPermission().withIpProtocol("tcp").withFromPort(new Integer(0)) .withToPort(new Integer(65535)).withIpRanges(ipRanges)); ipPermission.add(new IpPermission().withIpProtocol("tcp").withFromPort(new Integer(22)) .withToPort(new Integer(22)).withIpRanges(ipRanges)); ipPermission.add(new IpPermission().withIpProtocol("udp").withFromPort(new Integer(0)) .withToPort(new Integer(65535)).withIpRanges(ipRanges)); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). // IpPermission ipPermission = new IpPermission() //ipPermission. List<IpPermission> ipPermissions = new ArrayList<IpPermission>(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "launch-wizard-3", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString())); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } }
From source file:ec2.CreateSecurityGroup.java
License:Open Source License
public static void main(String[] args) { final String USAGE = "To run this example, supply a group name, group description and vpc id\n" + "Ex: CreateSecurityGroup <group-name> <group-description> <vpc-id>\n"; if (args.length != 3) { System.out.println(USAGE); System.exit(1);/*from w w w .ja va 2 s.c o m*/ } String groupName = args[0]; String groupDescription = args[1]; String vpcId = args[2]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest() .withGroupName(groupName).withDescription(groupDescription).withVpcId(vpcId); CreateSecurityGroupResult createSecurityGroupResponse = ec2.createSecurityGroup(createSecurityGroupRequest); System.out.printf("Successfully created security group named %s", groupName); IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0"); IpPermission ipPermission = new IpPermission().withIpProtocol("tcp").withToPort(80).withFromPort(80) .withIpv4Ranges(ipRange); IpPermission ipPermission2 = new IpPermission().withIpProtocol("tcp").withToPort(22).withFromPort(22) .withIpv4Ranges(ipRange); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName(groupName).withIpPermissions(ipPermission, ipPermission2); AuthorizeSecurityGroupIngressResult authorizeSecurityGroupIngressResponse = ec2 .authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); System.out.printf("Successfully added ingress policy to security group %s", groupName); }
From source file:ec2_device_manager.CreateSecurityGroupApp.java
License:Open Source License
/** * @param args//from w ww .j a va2s. co m */ public static void main(String[] args) { // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( CreateSecurityGroupApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("GettingStartedGroup", "Getting Started Security Group"); ec2.createSecurityGroup(securityGroupRequest); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { InetAddress addr = InetAddress.getLocalHost(); // Get IP Address ipAddr = addr.getHostAddress() + "/10"; } catch (UnknownHostException e) { } //System.exit(-1); // Create a range that you would like to populate. ArrayList<String> ipRanges = new ArrayList<String>(); ipRanges.add(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). ArrayList<IpPermission> ipPermissions = new ArrayList<IpPermission>(); IpPermission ipPermission = new IpPermission(); ipPermission.setIpProtocol("tcp"); ipPermission.setFromPort(new Integer(22)); ipPermission.setToPort(new Integer(22)); ipPermission.setIpRanges(ipRanges); ipPermissions.add(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } }
From source file:edu.umass.cs.aws.support.AWSEC2.java
License:Apache License
/** * Create a New Security Group with our standard permissions * * @param ec2/*from w w w. j av a 2 s. c om*/ * @param name * @return the name of the new group */ public static String createSecurityGroup(AmazonEC2 ec2, String name) { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(name, name + " security group"); ec2.createSecurityGroup(securityGroupRequest); AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(); ingressRequest.setGroupName(name); List<IpPermission> permissions = new ArrayList<>(); // open up ping (echo request) permissions.add(new IpPermission().withIpProtocol(ICMPPROTOCOL).withFromPort(ECHOTYPE) .withToPort(WILDCARDCODE).withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(TCPPROTOCOL).withFromPort(SSHPORT).withToPort(SSHPORT) .withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(TCPPROTOCOL).withFromPort(HTTPPORT).withToPort(HTTPPORT) .withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(TCPPROTOCOL).withFromPort(HTTPNONROOTPORT) .withToPort(HTTPNONROOTPORT).withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(TCPPROTOCOL).withFromPort(HTTPSPORT).withToPort(HTTPSPORT) .withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(TCPPROTOCOL).withFromPort(MYSQLPORT).withToPort(MYSQLPORT) .withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(TCPPROTOCOL).withFromPort(20000).withToPort(30000) .withIpRanges(IPRANGESALL)); permissions.add(new IpPermission().withIpProtocol(UDPPROTOCOL).withFromPort(20000).withToPort(30000) .withIpRanges(IPRANGESALL)); ingressRequest.setIpPermissions(permissions); ec2.authorizeSecurityGroupIngress(ingressRequest); return name; }
From source file:getting_started.CreateSecurityGroupApp.java
License:Open Source License
/** * @param args/*w ww . j a v a 2 s . c o m*/ */ public static void main(String[] args) { // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( InlineGettingStartedCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("GettingStartedGroup", "Getting Started Security Group"); ec2.createSecurityGroup(securityGroupRequest); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { InetAddress addr = InetAddress.getLocalHost(); // Get IP Address ipAddr = addr.getHostAddress() + "/10"; } catch (UnknownHostException e) { } //System.exit(-1); // Create a range that you would like to populate. ArrayList<String> ipRanges = new ArrayList<String>(); ipRanges.add(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). ArrayList<IpPermission> ipPermissions = new ArrayList<IpPermission>(); IpPermission ipPermission = new IpPermission(); ipPermission.setIpProtocol("tcp"); ipPermission.setFromPort(new Integer(22)); ipPermission.setToPort(new Integer(22)); ipPermission.setIpRanges(ipRanges); ipPermissions.add(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } }
From source file:gobblin.aws.AWSSdkClient.java
License:Apache License
/*** * Open firewall for a security group//from w ww . ja va 2 s .c om * * @param groupName Open firewall for this security group * @param ipRanges Open firewall for this IP range * @param ipProtocol Open firewall for this protocol type (eg. tcp, udp) * @param fromPort Open firewall for port range starting at this port * @param toPort Open firewall for port range ending at this port */ public void addPermissionsToSecurityGroup(String groupName, String ipRanges, String ipProtocol, Integer fromPort, Integer toPort) { final AmazonEC2 amazonEC2 = getEc2Client(); final IpPermission ipPermission = new IpPermission().withIpRanges(ipRanges).withIpProtocol(ipProtocol) .withFromPort(fromPort).withToPort(toPort); final AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName(groupName).withIpPermissions(ipPermission); amazonEC2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); LOGGER.info("Added permissions: " + ipPermission + " to security group: " + groupName); }