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

The following examples show how to use com.amazonaws.services.ec2.model.CreateSecurityGroupRequest. 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: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/***
 * Create an Amazon AWS security group
 *
 * @param groupName Security group name
 * @param description Security group description
 */
public void createSecurityGroup(String groupName,
    String description) {

  AmazonEC2 amazonEC2 = getEc2Client();
  try {
    final CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest()
        .withGroupName(groupName)
        .withDescription(description);
    amazonEC2.createSecurityGroup(securityGroupRequest);

    LOGGER.info("Created Security Group: " + groupName);
  } catch (AmazonServiceException ase) {
    // This might mean that security group is already created, hence ignore
    LOGGER.warn("Issue in creating security group", ase);
  }
}
 
Example #2
Source File: VpcImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup createSecurityGroup(CreateSecurityGroupRequest request,
        ResultCapture<CreateSecurityGroupResult> extractor) {

    ActionResult result = resource.performAction("CreateSecurityGroup",
            request, extractor);

    if (result == null) return null;
    return new SecurityGroupImpl(result.getResource());
}
 
Example #3
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup createSecurityGroup(CreateSecurityGroupRequest request,
        ResultCapture<CreateSecurityGroupResult> extractor) {

    ActionResult result = service.performAction("CreateSecurityGroup",
            request, extractor);

    if (result == null) return null;
    return new SecurityGroupImpl(result.getResource());
}
 
Example #4
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup createSecurityGroup(String description, String
        groupName, ResultCapture<CreateSecurityGroupResult> extractor) {

    CreateSecurityGroupRequest request = new CreateSecurityGroupRequest()
        .withDescription(description)
        .withGroupName(groupName);
    return createSecurityGroup(request, extractor);
}
 
Example #5
Source File: AmazonIpRuleManager.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public boolean createRuleSet( final String name ) {
    try {
        CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();

        request = request.withGroupName( name ).withDescription( "Judo Chop Security Group" );
        CreateSecurityGroupResult result = client.createSecurityGroup( request );
        return ( result != null && result.getGroupId() != null && ! result.getGroupId().isEmpty() );
    }
    catch ( AmazonServiceException e ) {
        LOG.warn( "Error while trying to create security group", e );
        return false;
    }
}
 
Example #6
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Create Security Group.
 *
 * @param groupName the group Name
 * @param groupDescription the group Description
 * @param vpcId vpcId for Sg
 * @return Security Group Id
 */
protected final String createSecurityGroup(final String groupName, final String groupDescription, final String vpcId) {
    String groupId = null;

    CreateSecurityGroupRequest req = new CreateSecurityGroupRequest();
    req.setGroupName(groupName);
    req.setDescription(groupDescription);
    req.setVpcId(vpcId);
    CreateSecurityGroupResult result = amazonEC2Client.createSecurityGroup(req);
    if (result != null) {
    	groupId = result.getGroupId();
    }

    return groupId;
}
 
Example #7
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the security group.
 *
 * @param sourceSecurityGroupId the source security group id
 * @param vpcId the vpc id
 * @param ec2Client the ec 2 client
 * @param ipPermissionsToBeAdded the ip permissions to be added
 * @param resourceId the resource id
 * @param defaultCidrIp the default cidr ip
 * @param existingIpPermissions the existing ip permissions
 * @return the string
 * @throws Exception the exception
 */
public static String createSecurityGroup(String sourceSecurityGroupId, String vpcId, AmazonEC2 ec2Client, Collection<IpPermission> ipPermissionsToBeAdded, String resourceId,String defaultCidrIp,List<IpPermission> existingIpPermissions) throws Exception {
	String createdSecurityGroupId = null;
	try {
		CreateSecurityGroupRequest createsgRequest = new CreateSecurityGroupRequest();
		createsgRequest.setGroupName(createSecurityGroupName(pacTag,resourceId));
		createsgRequest.setVpcId(vpcId);
		createsgRequest.setDescription(createSecurityGroupDescription(sourceSecurityGroupId));
		CreateSecurityGroupResult createResult = ec2Client.createSecurityGroup(createsgRequest);
		createdSecurityGroupId = createResult.getGroupId();

		if (!createdSecurityGroupId.isEmpty()) {
			logger.info("Security Group {} created successfully" ,createdSecurityGroupId);
			// Authorize newly created securityGroup with Inbound Rules
			AuthorizeSecurityGroupIngressRequest authRequest = new AuthorizeSecurityGroupIngressRequest();
			authRequest.setGroupId(createdSecurityGroupId);
			if(ipPermissionsToBeAdded.isEmpty()){
                   IpRange ipv4Ranges = new IpRange();
                   ipv4Ranges.setCidrIp(defaultCidrIp);
				for (IpPermission ipPermission : existingIpPermissions) {

					if (!ipPermission.getIpv4Ranges().isEmpty()) {
						ipPermission.setIpv4Ranges(Arrays.asList(ipv4Ranges));
					}

					if (!ipPermission.getIpv6Ranges().isEmpty()) {
						Ipv6Range ipv6Range = new Ipv6Range();
						ipPermission.setIpv6Ranges(Arrays.asList(ipv6Range));
					}
					if (!ipPermission.getIpv4Ranges().isEmpty() || !ipPermission.getIpv6Ranges().isEmpty()) {
						ipPermissionsToBeAdded.add(ipPermission);
					}
				}
               }
			authRequest.setIpPermissions(ipPermissionsToBeAdded);
			ec2Client.authorizeSecurityGroupIngress(authRequest);
			//adding tag
			String deleteSgTag = CommonUtils.getPropValue("deleteSgTag");
			Map<String, String> tagMap = new HashMap();
			tagMap.put(deleteSgTag, "true");
			CreateTagsRequest createTagsRequest = new CreateTagsRequest(Arrays.asList(createdSecurityGroupId), new ArrayList<>());
			createTagsRequest.setTags(tagMap.entrySet().stream().map(t -> new Tag(t.getKey(), t.getValue())).collect(Collectors.toList()));
			try {
				ec2Client.createTags(createTagsRequest);
			} catch (AmazonServiceException ase) {
				logger.error("error tagging sg - > " + resourceId, ase);
				throw ase;
			}
		}

	} catch (Exception e) {
		logger.error(e.getMessage());
		logger.debug(e.getMessage());
		throw new RuntimeException(sourceSecurityGroupId+ " SG copy failed");
	}
	return createdSecurityGroupId;
}
 
Example #8
Source File: CreateSecurityGroup.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
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);
    }

    String group_name = args[0];
    String group_desc = args[1];
    String vpc_id = args[2];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    CreateSecurityGroupRequest create_request = new
        CreateSecurityGroupRequest()
            .withGroupName(group_name)
            .withDescription(group_desc)
            .withVpcId(vpc_id);

    CreateSecurityGroupResult create_response =
        ec2.createSecurityGroup(create_request);

    System.out.printf(
        "Successfully created security group named %s",
        group_name);

    IpRange ip_range = new IpRange()
        .withCidrIp("0.0.0.0/0");

    IpPermission ip_perm = new IpPermission()
        .withIpProtocol("tcp")
        .withToPort(80)
        .withFromPort(80)
        .withIpv4Ranges(ip_range);

    IpPermission ip_perm2 = new IpPermission()
        .withIpProtocol("tcp")
        .withToPort(22)
        .withFromPort(22)
        .withIpv4Ranges(ip_range);

    AuthorizeSecurityGroupIngressRequest auth_request = new
        AuthorizeSecurityGroupIngressRequest()
            .withGroupName(group_name)
            .withIpPermissions(ip_perm, ip_perm2);

    AuthorizeSecurityGroupIngressResult auth_response =
        ec2.authorizeSecurityGroupIngress(auth_request);

    System.out.printf(
        "Successfully added ingress policy to security group %s",
        group_name);
}
 
Example #9
Source File: VpcImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public SecurityGroup createSecurityGroup(CreateSecurityGroupRequest request)
        {

    return createSecurityGroup(request, null);
}
 
Example #10
Source File: EC2Impl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public SecurityGroup createSecurityGroup(CreateSecurityGroupRequest request)
        {

    return createSecurityGroup(request, null);
}
 
Example #11
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 #12
Source File: Vpc.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateSecurityGroup</code> action.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Vpc</code> resource, and any conflicting parameter value set in the
 * request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>VpcId</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The <code>SecurityGroup</code> resource object associated with
 *         the result of this action.
 * @see CreateSecurityGroupRequest
 */
SecurityGroup createSecurityGroup(CreateSecurityGroupRequest request);
 
Example #13
Source File: Vpc.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateSecurityGroup</code> action and use a
 * ResultCapture to retrieve the low-level client response.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Vpc</code> resource, and any conflicting parameter value set in the
 * request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>VpcId</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The <code>SecurityGroup</code> resource object associated with
 *         the result of this action.
 * @see CreateSecurityGroupRequest
 */
SecurityGroup createSecurityGroup(CreateSecurityGroupRequest request,
        ResultCapture<CreateSecurityGroupResult> extractor);
 
Example #14
Source File: EC2.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateSecurityGroup</code> action.
 *
 * <p>
 *
 * @return The <code>SecurityGroup</code> resource object associated with
 *         the result of this action.
 * @see CreateSecurityGroupRequest
 */
com.amazonaws.resources.ec2.SecurityGroup createSecurityGroup(
        CreateSecurityGroupRequest request);
 
Example #15
Source File: EC2.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateSecurityGroup</code> action and use a
 * ResultCapture to retrieve the low-level client response.
 *
 * <p>
 *
 * @return The <code>SecurityGroup</code> resource object associated with
 *         the result of this action.
 * @see CreateSecurityGroupRequest
 */
com.amazonaws.resources.ec2.SecurityGroup createSecurityGroup(
        CreateSecurityGroupRequest request,
        ResultCapture<CreateSecurityGroupResult> extractor);