protected ExecResponse runCommand(String command) { ExecResponse returnVal; logger.debug(">> running [%s] as %s@%s", command.replace(node.getCredentials().getOptionalPassword().isPresent() ? node .getCredentials().getOptionalPassword().get() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress()); returnVal = ssh.exec(command); return returnVal; }
public RunScriptOptions overrideLoginCredentials(LoginCredentials overridingCredentials) { checkNotNull(overridingCredentials, "overridingCredentials"); this.loginUser = overridingCredentials.getUser(); this.loginPassword = overridingCredentials.getOptionalPassword(); this.loginPrivateKey = overridingCredentials.getOptionalPrivateKey(); this.authenticateSudo = overridingCredentials.shouldAuthenticateSudo() ? true : null; return this; }
@Override public void authenticate(Connection connection) throws IOException { String u = credentials.getUser(); if(!connection.authenticateWithPublicKey(u, credentials.getPrivateKey().toCharArray(), credentials.getPassword())){ throw new IOException(String.format("Public key authentication failed: trying to login as %s@%s with %s", u, connection.getHostname(), keyPair.privateKey)); } }
public LoginCredentials apply(Template template, LoginCredentials fromNode) { LoginCredentials creds = fromNode; LoginCredentials credsFromParameters = credentialsFromImageOrTemplateOptions.apply(template); if (credsFromParameters != null) { Builder builder = LoginCredentials.builder(creds); if (credsFromParameters.getUser() != null) builder.user(credsFromParameters.getUser()); if (credsFromParameters.getPassword() != null) builder.password(credsFromParameters.getPassword()); if (credsFromParameters.getPrivateKey() != null) builder.privateKey(credsFromParameters.getPrivateKey()); if (credsFromParameters.shouldAuthenticateSudo()) builder.authenticateSudo(true); creds = builder.build(); } return creds; }
public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() { Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user("ubuntu").password("password2").build()); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password")); replay(template, image); assertEquals(fn.apply(template), expected); verify(template, image); } }
public void testPrivateKeySetsPasswordToAbsentWhenUnset() { LoginCredentials toTest = LoginCredentials.builder().user("user").privateKey("key").build(); assertEquals(toTest.getOptionalPassword(), Optional.absent()); assertEquals(toTest.getOptionalPrivateKey(), Optional.of("key")); }
@Test public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound() throws UnknownHostException { LoginCredentials creds = LoginCredentials.builder().user("root").password("abdce").build(); RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of( "node#us-east-1/i-0799056f", creds)); RunningInstance server = firstInstanceFromResource("/describe_instances_running.xml"); assertEquals( parser.apply(server).toString(), new NodeMetadataBuilder().status(Status.RUNNING).backendStatus("running").hostname("ip-10-243-42-70") .publicAddresses(ImmutableSet.<String> of()).privateAddresses(ImmutableSet.of("10.243.42.70")) .publicAddresses(ImmutableSet.of("174.129.81.68")).credentials(creds) .imageId("us-east-1/ami-82e4b5c7").id("us-east-1/i-0799056f").providerId("i-0799056f").build().toString()); }
@Test public void testTemplateChoiceForInstanceByImageIdDoesNotGetAllImages() throws Exception { @SuppressWarnings("unchecked") Supplier<Set<? extends Image>> images = createMock(Supplier.class); replay(images); final Image image = new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true)) .description("description").version("1.0").defaultCredentials(LoginCredentials.builder().user("root").build()) .status(Image.Status.AVAILABLE) .build(); Map<RegionAndName, Image> imageMap = ImmutableMap.of( new RegionAndName(image.getLocation().getId(), image.getProviderId()), image); // weird compilation error means have to declare extra generics for call to build() - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=365818 Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache = Suppliers.<LoadingCache<RegionAndName, ? extends Image>> ofInstance( CacheBuilder.newBuilder().<RegionAndName,Image>build(CacheLoader.from(Functions.forMap(imageMap)))); Template template = newTemplateBuilder(images, imageCache).imageId("us-east-1/cc-image").build(); assert template != null : "The returned template was null, but it should have a value."; assertEquals(template.getImage().getId(), "us-east-1/cc-image"); }
@Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); LoginCredentials credentials = f.apply(new EncryptedPasswordAndPrivateKey(ENCRYPTED_PASSWORD, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getOptionalPassword().get(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); } }
@Test(expectedExceptions = IllegalStateException.class) public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( LoginCredentials.builder().user("tester").password("notalot").build()).build(); SshClient sshClient = createMock(SshClient.class); replay(sshClient); RunScriptOnNodeAsInitScriptUsingSsh testMe = new RunScriptOnNodeAsInitScriptUsingSsh(Functions .forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create() .appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions()); testMe.call(); }
public void testParseCCImage() { Set<org.jclouds.compute.domain.Image> result = convertImages("/describe_images_cc.xml"); assertEquals( Iterables.get(result, 0), new ImageBuilder() .name("EC2 CentOS 5.4 HVM AMI") .operatingSystem( new OperatingSystem.Builder().family(OsFamily.CENTOS).arch("hvm").version("5.4") .description("amazon/EC2 CentOS 5.4 HVM AMI").is64Bit(true).build()) .description("EC2 CentOS 5.4 HVM AMI") .defaultCredentials(LoginCredentials.builder().user("root").build()).id("us-east-1/ami-7ea24a17") .providerId("ami-7ea24a17").location(defaultLocation) .userMetadata(ImmutableMap.of( "owner", "206029621532", "rootDeviceType", "ebs", "virtualizationType", "hvm", "hypervisor", "xen")) .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build()); assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE); }
/** * @return true if there is a private key attached that is not encrypted */ public boolean hasUnencryptedPrivateKey() { return getOptionalPrivateKey().isPresent() && !getOptionalPrivateKey().get().isEmpty() && !getOptionalPrivateKey().get().contains(Pems.PROC_TYPE_ENCRYPTED); }
public void testCreateNodeWithGeneratedKeyPairAndOverriddenLoginUser() throws Exception { Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(describeRegionsRequest, describeRegionsResponse); requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse); requestResponseMap.put(describeImagesRequest, describeImagesResponse); requestResponseMap.put(createKeyPairRequest, createKeyPairResponse); requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse); requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse); requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse); requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse); requestResponseMap.put(runInstancesRequest, runInstancesResponse); requestResponseMap.put(describeInstanceRequest, describeInstanceResponse); requestResponseMap.put(describeInstanceMultiIdsRequest, describeInstanceMultiIdsResponse); requestResponseMap.put(describeImageRequest, describeImagesResponse); ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build()); NodeMetadata node = Iterables.getOnlyElement(apiThatCreatesNode.createNodesInGroup("test", 1, blockUntilRunning(false).overrideLoginUser("ec2-user"))); assertEquals(node.getCredentials().getUser(), "ec2-user"); System.out.println(node.getImageId()); assertNotNull(node.getCredentials().getPrivateKey()); }
@Override public Optional<LoginCredentials> load(final RunningInstance instance) throws ExecutionException { if ("windows".equals(instance.getPlatform())) { return Optional.of(passwordCredentialsFromWindowsInstance.apply(instance)); } else if (instance.getKeyName() != null) { return Optional.of(LoginCredentials.builder().user(getLoginAccountFor(instance)).privateKey(getPrivateKeyOrNull(instance)).build()); } return Optional.absent(); }
@Test public void testApply() throws Exception { WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); LoginCredentials credentials = f.apply(new EncryptedPasswordAndPrivateKey(ENCRYPTED_PASSWORD, PRIVATE_KEY)); assertEquals(credentials.getUser(), "Administrator"); assertEquals(credentials.getPassword(), "u4.y9mb;nR."); assertFalse(credentials.getOptionalPrivateKey().isPresent()); } }
@Test public void testDefaultCredentials() { Map<OsFamily, String> defaultUsernames = ImmutableMap.of(COREOS, "core", WINDOWS, "Administrator"); Set<? extends Image> images = view.getComputeService().listImages(); for (Image image : images) { assertEquals(image.getDefaultCredentials().getUser(), firstNonNull(defaultUsernames.get(image.getOperatingSystem().getFamily()), "jclouds")); } }
@VisibleForTesting public String execAsRoot(String command) { if (node.getCredentials().identity.equals("root")) { } else if (node.getCredentials().shouldAuthenticateSudo()) { command = String.format("sudo -S sh <<'%s'\n'%s'\n%s%s\n", MARKER, node.getCredentials().getOptionalPassword ().get(), command, MARKER); } else { command = String.format("sudo sh <<'%s'\n%s%s\n", MARKER, command, MARKER); } return command; }
@VisibleForTesting public void execute(URI org, String group, String identity, TerremarkVCloudTemplateOptions options) { String sshKeyFingerprint = options.getSshKeyFingerprint(); boolean shouldAutomaticallyCreateKeyPair = options.shouldAutomaticallyCreateKeyPair(); if (sshKeyFingerprint == null && shouldAutomaticallyCreateKeyPair) { // make sure that we don't request multiple keys simultaneously synchronized (credentialStore) { // if there is already a keypair for the group specified, use it if (credentialStore.containsKey("group#" + group)) { LoginCredentials creds = LoginCredentials.fromCredentials(credentialStore.get("group#" + group)); checkState(creds.getOptionalPrivateKey().isPresent(), "incorrect state: should have private key for: %s", creds); options.sshKeyFingerprint(SshKeys.fingerprintPrivateKey(creds.getPrivateKey())); } else { // otherwise create a new keypair and key it under the group KeyPair keyPair = createUniqueKeyPair.apply(new OrgAndName(org, group)); credentialStore.put("group#" + group, LoginCredentials.builder().user(identity).privateKey( keyPair.getPrivateKey()).build()); options.sshKeyFingerprint(keyPair.getFingerPrint()); } } } } }