List of usage examples for com.amazonaws.services.ec2.model CreateSecurityGroupResult getGroupId
public String getGroupId()
The ID of the security group.
From source file:SecurityGroup.java
License:Open Source License
public void create(String groupName) { AWSCredentials credentials = null;// ww w. j av a 2s . c o m try { credentials = new ProfileCredentialsProvider("School").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 (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); ec2.setRegion(usEast1); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(groupName, "Security created for P2"); CreateSecurityGroupResult result = ec2.createSecurityGroup(securityGroupRequest); System.out.println(String.format("Security group created: [%s]", result.getGroupId())); groupId = result.getGroupId(); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList("0.0.0.0/0"); // Open all port IpPermission ipPermission = new IpPermission().withIpProtocol("-1").withFromPort(new Integer(0)) .withToPort(new Integer(65535)).withIpRanges(ipRanges); List<IpPermission> ipPermissions = Collections.singletonList(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( groupName, 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:CreateSecurityGroupApp.java
License:Open Source License
public static void main(String[] args) { /*//from w w w . ja v a 2s.c om * The ProfileCredentialsProvider will return your [New Profile] * credential profile by reading from the credentials file located at * (C:\\Users\\Accolite\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("New Profile").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 (C:\\Users\\Accolite\\.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("Muneer_SG", "My Security Group"); 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"; // 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) { } // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). IpPermission ipPermission = new IpPermission().withIpProtocol("tcp").withFromPort(new Integer(22)) .withToPort(new Integer(22)).withIpRanges(ipRanges); List<IpPermission> ipPermissions = Collections.singletonList(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", 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:com.axemblr.provisionr.amazon.activities.EnsureSecurityGroupExists.java
License:Apache License
@Override public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) { final String businessKey = execution.getProcessBusinessKey(); final String groupName = SecurityGroups.formatNameFromBusinessKey(businessKey); try {//from w w w . ja v a 2s. co m LOG.info(">> Creating Security Group with name {}", groupName); CreateSecurityGroupRequest request = new CreateSecurityGroupRequest().withGroupName(groupName) .withDescription("Security Group for " + businessKey); CreateSecurityGroupResult result = client.createSecurityGroup(request); LOG.info("<< Created Security Group with ID {}", result.getGroupId()); } catch (AmazonServiceException e) { if (e.getErrorCode().equals(ErrorCodes.DUPLICATE_SECURITY_GROUP)) { LOG.warn(String.format("<< Security Group %s already exists. " + "Synchronizing ingress rules.", groupName), e); } else { throw Throwables.propagate(e); } } synchronizeIngressRules(client, groupName, pool.getNetwork()); }
From source file:com.github.vatbub.awsvpnlauncher.Main.java
License:Apache License
/** * Launches a new VPN server on AWS EC2 if everything is configured * * @see PropertyNotConfiguredException/*from w w w . j a va 2 s . c om*/ * @see #terminate() */ private static void launch() { File privateKey = new File(prefs.getPreference(Property.privateKeyFile)); vpnPassword = prefs.getPreference(Property.openvpnPassword); if (!privateKey.exists() && !privateKey.isFile()) { throw new IllegalArgumentException("The file specified as " + Property.privateKeyFile.toString() + " does not exist or is not a file."); } FOKLogger.info(Main.class.getName(), "Preparing..."); try { // Check if our security group exists already FOKLogger.info(Main.class.getName(), "Checking for the required security group..."); DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest() .withGroupNames(securityGroupName); List<String> securityGroups = new ArrayList<>(); boolean created = false; // will become true if the security group had to be created to avoid duplicate logs String securityGroupId; try { DescribeSecurityGroupsResult describeSecurityGroupsResult = client .describeSecurityGroups(describeSecurityGroupsRequest); securityGroupId = describeSecurityGroupsResult.getSecurityGroups().get(0).getGroupId(); } catch (AmazonEC2Exception e) { // Security group does not exist, create the security group created = true; FOKLogger.info(Main.class.getName(), "Creating the required security group..."); CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest() .withGroupName(securityGroupName).withDescription( "This security group was automatically created to run a OpenVPN Access Server."); CreateSecurityGroupResult createSecurityGroupResult = client .createSecurityGroup(createSecurityGroupRequest); securityGroupId = createSecurityGroupResult.getGroupId(); IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0"); IpPermission sshPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp") .withFromPort(22).withToPort(22); IpPermission sshPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp") .withFromPort(943).withToPort(943); IpPermission httpsPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp") .withFromPort(443).withToPort(443); IpPermission httpsPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("udp") .withFromPort(1194).withToPort(1194); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName(securityGroupName).withIpPermissions(sshPermission1) .withIpPermissions(sshPermission2).withIpPermissions(httpsPermission1) .withIpPermissions(httpsPermission2); // retry while the security group is not yet ready int retries = 0; long lastPollTime = System.currentTimeMillis(); boolean requestIsFailing = true; do { // we're waiting if (System.currentTimeMillis() - lastPollTime >= Math.pow(2, retries) * 100) { retries = retries + 1; lastPollTime = System.currentTimeMillis(); try { client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); // no exception => we made it requestIsFailing = false; } catch (AmazonEC2Exception e2) { FOKLogger.info(Main.class.getName(), "Still waiting for the security group to be created, api error message is currently: " + e2.getMessage()); requestIsFailing = true; } } } while (requestIsFailing); FOKLogger.info(Main.class.getName(), "The required security group has been successfully created!"); } if (!created) { FOKLogger.info(Main.class.getName(), "The required security group already exists, we can continue"); } securityGroups.add(securityGroupId); securityGroups.add(securityGroupId); FOKLogger.info(Main.class.getName(), "Creating the RunInstanceRequest..."); RunInstancesRequest request = new RunInstancesRequest(getAmiId(awsRegion), 1, 1); request.setInstanceType(InstanceType.T2Micro); request.setKeyName(prefs.getPreference(Property.awsKeyPairName)); request.setSecurityGroupIds(securityGroups); FOKLogger.info(Main.class.getName(), "Starting the EC2 instance..."); RunInstancesResult result = client.runInstances(request); List<Instance> instances = result.getReservation().getInstances(); // SSH config FOKLogger.info(Main.class.getName(), "Configuring SSH..."); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); jsch.addIdentity(privateKey.getAbsolutePath()); int retries = 0; for (Instance instance : instances) { // write the instance id to a properties file to be able to terminate it later on again prefs.reload(); if (prefs.getPreference("instanceIDs", "").equals("")) { prefs.setPreference("instanceIDs", instance.getInstanceId()); } else { prefs.setPreference("instanceIDs", prefs.getPreference("instanceIDs", "") + ";" + instance.getInstanceId()); } // Connect to the instance using ssh FOKLogger.info(Main.class.getName(), "Waiting for the instance to boot..."); long lastPrintTime = System.currentTimeMillis(); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); List<String> instanceId = new ArrayList<>(1); instanceId.add(instance.getInstanceId()); describeInstancesRequest.setInstanceIds(instanceId); DescribeInstancesResult describeInstancesResult; newInstance = instance; do { // we're waiting if (System.currentTimeMillis() - lastPrintTime >= Math.pow(2, retries) * 100) { retries = retries + 1; describeInstancesResult = client.describeInstances(describeInstancesRequest); newInstance = describeInstancesResult.getReservations().get(0).getInstances().get(0); lastPrintTime = System.currentTimeMillis(); if (newInstance.getState().getCode() != 16) { FOKLogger.info(Main.class.getName(), "Still waiting for the instance to boot, current instance state is " + newInstance.getState().getName()); } } } while (newInstance.getState().getCode() != 16); FOKLogger.info(Main.class.getName(), "Instance is " + newInstance.getState().getName()); // generate the ssh ip of the instance String sshIp = newInstance.getPublicDnsName(); FOKLogger.info(Main.class.getName(), "The instance id is " + newInstance.getInstanceId()); FOKLogger.info(Main.class.getName(), "The instance ip is " + newInstance.getPublicIpAddress()); FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp); FOKLogger.info(Main.class.getName(), "The instance will need some time to configure ssh on its end so some connection timeouts are normal"); boolean retry; session = jsch.getSession(sshUsername, sshIp, 22); session.setConfig(sshConfig); do { try { session.connect(); retry = false; } catch (Exception e) { FOKLogger.info(Main.class.getName(), e.getClass().getName() + ": " + e.getMessage() + ", retrying, Press Ctrl+C to cancel"); retry = true; } } while (retry); FOKLogger.info(Main.class.getName(), "----------------------------------------------------------------------"); FOKLogger.info(Main.class.getName(), "The following is the out- and input of the ssh session."); FOKLogger.info(Main.class.getName(), "Please note that out- and input may appear out of sync."); FOKLogger.info(Main.class.getName(), "----------------------------------------------------------------------"); PipedInputStream sshIn = new PipedInputStream(); PipedOutputStream sshIn2 = new PipedOutputStream(sshIn); PrintStream sshInCommandStream = new PrintStream(sshIn2); Channel channel = session.openChannel("shell"); channel.setInputStream(sshIn); channel.setOutputStream(new MyPrintStream()); channel.connect(); sshInCommandStream.print("yes\n"); sshInCommandStream.print("yes\n"); sshInCommandStream.print("1\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("yes\n"); sshInCommandStream.print("yes\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("echo \"" + adminUsername + ":" + vpnPassword + "\" | sudo chpasswd\n"); sshInCommandStream.print("exit\n"); NullOutputStream nullOutputStream = new NullOutputStream(); Thread watchForSSHDisconnectThread = new Thread(() -> { while (channel.isConnected()) { nullOutputStream.write(0); } // disconnected cont(); }); watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread"); watchForSSHDisconnectThread.start(); } } catch (JSchException | IOException e) { e.printStackTrace(); if (session != null) { session.disconnect(); } System.exit(1); } }
From source file:com.kpbird.aws.Main.java
private void createEC2SecurityGroup() { try {//from www . ja va2s . com log.Info("Create Security Group Request"); CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest(); createSecurityGroupRequest.withGroupName(groupName).withDescription(groupDescription); createSecurityGroupRequest.setRequestCredentials(credentials); CreateSecurityGroupResult csgr = ec2client.createSecurityGroup(createSecurityGroupRequest); String groupid = csgr.getGroupId(); log.Info("Security Group Id : " + groupid); log.Info("Create Security Group Permission"); Collection<IpPermission> ips = new ArrayList<IpPermission>(); // Permission for SSH only to your ip IpPermission ipssh = new IpPermission(); ipssh.withIpRanges(sshIpRange).withIpProtocol(sshprotocol).withFromPort(sshFromPort) .withToPort(sshToPort); ips.add(ipssh); // Permission for HTTP, any one can access IpPermission iphttp = new IpPermission(); iphttp.withIpRanges(httpIpRange).withIpProtocol(httpProtocol).withFromPort(httpFromPort) .withToPort(httpToPort); ips.add(iphttp); //Permission for HTTPS, any one can accesss IpPermission iphttps = new IpPermission(); iphttps.withIpRanges(httpsIpRange).withIpProtocol(httpsProtocol).withFromPort(httpsFromPort) .withToPort(httpsToProtocol); ips.add(iphttps); log.Info("Attach Owner to security group"); // Register this security group with owner AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); authorizeSecurityGroupIngressRequest.withGroupName(groupName).withIpPermissions(ips); ec2client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); } catch (Exception e) { e.printStackTrace(); System.exit(0); } }
From source file:com.netflix.simianarmy.client.aws.AWSClient.java
License:Apache License
/** {@inheritDoc} */ public String createSecurityGroup(String instanceId, String name, String description) { String vpcId = getVpcId(instanceId); AmazonEC2 ec2Client = ec2Client();// w ww.ja v a 2 s. c om CreateSecurityGroupRequest request = new CreateSecurityGroupRequest(); request.setGroupName(name); request.setDescription(description); request.setVpcId(vpcId); LOGGER.info(String.format("Creating EC2 security group %s.", name)); CreateSecurityGroupResult result = ec2Client.createSecurityGroup(request); return result.getGroupId(); }
From source file:com.urbancode.terraform.tasks.aws.helpers.AWSHelper.java
License:Apache License
/** * * @param groupName//from w w w . j a v a 2s .c om * @param vpcId leave null if you do not want your security group to be associated with a VPC * @param descr * @param ec2Client * @return */ public String createSecurityGroup(String groupName, String vpcId, String descr, AmazonEC2 ec2Client) { String groupId = null; try { CreateSecurityGroupRequest request = new CreateSecurityGroupRequest().withGroupName(groupName) .withDescription(descr); if (vpcId != null) { request = request.withVpcId(vpcId); } CreateSecurityGroupResult result = ec2Client.createSecurityGroup(request); groupId = result.getGroupId(); } catch (AmazonServiceException e) { log.error("Failed to create Security Group", e); if (!"InvalidVpcID.NotFound".equalsIgnoreCase(e.getErrorCode())) { throw e; } } return groupId; }
From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.java
License:Open Source License
public static String createSecurityGroup(AmazonEC2AsyncClient client, String name, String description, String vpcId) {/* ww w . j a v a 2 s. co m*/ CreateSecurityGroupRequest req = new CreateSecurityGroupRequest().withDescription(description) .withGroupName(name); // set vpc for the security group if provided if (vpcId != null) { req = req.withVpcId(vpcId); } CreateSecurityGroupResult result = client.createSecurityGroup(req); return result.getGroupId(); }
From source file:com.zotoh.cloudapi.aws.SecurityGroup.java
License:Open Source License
/** * returns the Amazon group-id, which is different to group-name. *//*w w w . ja v a 2 s. co m*/ @Override public String create(String group, String desc) throws InternalException, CloudException { tstEStrArg("group-description", desc); tstEStrArg("group-name", group); CreateSecurityGroupResult res = _svc.getCloud().getEC2() .createSecurityGroup(new CreateSecurityGroupRequest(group, desc)); return res == null ? null : res.getGroupId(); }
From source file:DynamicProvisioning.SecGroupCreate.java
License:Open Source License
public static void main(String[] args) { AWSCredentials credentials = null;//ww w . j a v a 2 s . c o m 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()); } }