Example usage for com.amazonaws.services.ec2 AmazonEC2 createSecurityGroup

List of usage examples for com.amazonaws.services.ec2 AmazonEC2 createSecurityGroup

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2 createSecurityGroup.

Prototype

CreateSecurityGroupResult createSecurityGroup(CreateSecurityGroupRequest createSecurityGroupRequest);

Source Link

Document

Creates a security group.

Usage

From source file:Security.java

License:Open Source License

String createSG(AmazonEC2 ec2) throws IOException {
    try {// www  . ja  v a2 s .  c  o  m
        securitygroup = "VirualIT_Security_Group" + Virtualize.no_of_days;
        CreateSecurityGroupRequest reqsec = new CreateSecurityGroupRequest().withGroupName(securitygroup)
                .withDescription("ssh-tcp-https-http");
        CreateSecurityGroupResult ressec = ec2.createSecurityGroup(reqsec);
        String ipAddr = "0.0.0.0/0";
        ArrayList<String> ipRanges = new ArrayList<String>();
        ipRanges.add(ipAddr);
        ArrayList<IpPermission> ipPermissions = new ArrayList<IpPermission>();
        IpPermission ipPermission_ssh = new IpPermission();
        ipPermission_ssh.setIpProtocol("tcp");
        ipPermission_ssh.setFromPort(new Integer(22));
        ipPermission_ssh.setToPort(new Integer(22));
        IpPermission ipPermission_http = new IpPermission();
        ipPermission_http.setIpProtocol("tcp");
        ipPermission_http.setFromPort(new Integer(80));
        ipPermission_http.setToPort(new Integer(80));
        IpPermission ipPermission_https = new IpPermission();
        ipPermission_https.setIpProtocol("tcp");
        ipPermission_https.setFromPort(new Integer(443));
        ipPermission_https.setToPort(new Integer(443));
        ipPermission_ssh.setIpRanges(ipRanges);
        ipPermission_http.setIpRanges(ipRanges);
        ipPermission_https.setIpRanges(ipRanges);
        ipPermissions.add(ipPermission_http);
        ipPermissions.add(ipPermission_https);
        ipPermissions.add(ipPermission_ssh);
        try {
            // Authorize the ports to the used.
            AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
                    securitygroup, ipPermissions);
            ec2.authorizeSecurityGroupIngress(ingressRequest);
            System.out.println("Assigned " + ingressRequest);
        } catch (AmazonServiceException ase) {
            // Ignore because this likely means the zone has already been authorized.
            System.err.println(ase.getMessage());
        }
        DescribeSecurityGroupsRequest x = new DescribeSecurityGroupsRequest().withGroupNames(securitygroup);
        DescribeSecurityGroupsResult secgrp = ec2.describeSecurityGroups(x);
        for (SecurityGroup s : secgrp.getSecurityGroups()) {
            if (s.getGroupName().equals(securitygroup)) {
                System.out.println(s.getIpPermissions());
            }
        }
    } 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 securitygroup;
}

From source file:SecurityGroup.java

License:Open Source License

public void create(String groupName) {

    AWSCredentials credentials = null;/*from w  w w .  j av a2s .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) {

    /*//  www. j  a  va 2s . co m
     * 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:advanced.CreateSecurityGroupApp.java

License:Open Source License

/**
 * @param args//from w  ww  . ja  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(
                InlineTaggingCodeSampleApp.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:aws.example.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);//w w w  .j  a  va  2  s  .  co m
    }

    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);
}

From source file:aws.sample.CreateSecurityGroupApp.java

License:Open Source License

/**
 * @param args//www . j a  v  a2 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: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 ww.ja  v a2 s . c o 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.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();
    CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();
    request.setGroupName(name);/* w  w  w. j a  v  a 2  s  . c o  m*/
    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  2 s . c  o  m
 * @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: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 {//from ww w. ja  v a2s.c  o 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);
    }
}