在jclouds中使用现有的securityGroup和pem文件 - Java

时间:2016-09-17 21:03:09

标签: java amazon-web-services amazon-ec2 jclouds

我开始使用jclouds来操纵EC2实例。因此,我有以下方法:

private ComputeService compute;

public void add(Integer instances) {
        try {
            logger.info("------------------------------------------------------");
            logger.info(String.format(">> adding node to group %s%n", this.groupname));
            // Default template chooses the smallest size on an operating system
            // that tested to work with java, which tends to be Ubuntu or CentOS
            TemplateBuilder templateBuilder = this.compute.templateBuilder();
            // note this will create a user with the same name as you on the
            // node. ex. you can connect via ssh publicip
            Statement bootInstructions = AdminAccess.standard();

            // to run commands as root, we use the runScript option in the template.
            templateBuilder.options(runScript(bootInstructions));

            Template template = templateBuilder.build();
            // add a custom security group

            NodeMetadata node = getOnlyElement(this.compute.createNodesInGroup(this.groupname, instances, template));
            logger.info(String.format("<< node %s: %s%n", node.getId(),
                        concat(node.getPrivateAddresses(), node.getPublicAddresses())));
            logger.info("------------------------------------------------------");
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.info("------------------------------------------------------");
        }
    }

请假设身份验证正确无误 groupname = default。当我执行

this.compute.add(1); 

即使创建了一个实例,jclouds每次都会创建一个新的security groupkey pair。我有现有的foo.pem文件和default安全组。例如: security group = jclouds#default。如何使用现有的安全组和密钥值?

1 个答案:

答案 0 :(得分:0)

如果要使用现有的安全组或密钥对,可以通过将它们提供给模板构建器来完成:

templateBuilder.securityGroups(<existing security groups>);
templateBuilder.as(AWSEC2TemplateOptions.class).keyPair(<existing key pair>);
templateBuilder.options(runScript(bootInstructions));

请注意,为了使用keypair方法,您需要将选项强制转换为AWS类,因为便携式界面中没有该选项。

另请注意,当使用基于密钥的访问权限通过SSH访问节点(运行脚本)时,jclouds必须提供&#34;私钥&#34;到节点。您有两种选择:事先将密钥加载到ssh-agent中,或使用templateOptions.overrideLoginPrivateKey提供私钥,以便jclouds可以正确登录节点。