ImmutableMap.Builder<String, String> metadataBuilder = metatadaFromTemplateOptions.apply(options);
instanceTemplate.metadata(metadataBuilder.build());
instanceTemplate.serviceAccounts(options.getServiceAccounts());
instanceTemplate.image(checkNotNull(template.getImage().getUri(), "image URI is null"));
final InstanceApi instanceApi = api.getInstanceApiForProject(userProject.get());
final String zone = template.getLocation().getId();
Operation operation = instanceApi.createInZone(name, zone, instanceTemplate);
if (options.shouldBlockUntilRunning()) {
waitOperationDone(operation);
}
// some times the newly created instances are not immediately returned
AtomicReference<Instance> instance = new AtomicReference<Instance>();
retry(new Predicate<AtomicReference<Instance>>() {
@Override
public boolean apply(AtomicReference<Instance> input) {
input.set(instanceApi.getInZone(zone, name));
return input.get() != null;
}
}, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS).apply(instance);
if (!options.getTags().isEmpty()) {
Operation tagsOperation = instanceApi.setTagsInZone(zone,
name, options.getTags(), instance.get().getTags().getFingerprint());
waitOperationDone(tagsOperation);
retry(new Predicate<AtomicReference<Instance>>() {
@Override
public boolean apply(AtomicReference<Instance> input) {
input.set(instanceApi.getInZone(zone, name));
return input.get() != null;
}
}, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS).apply(instance);
}
// Add tags for security groups
final FirewallTagNamingConvention naming = firewallTagNamingConvention.get(group);
Set<String> tags = FluentIterable.from(Ints.asList(options.getInboundPorts()))
.transform(new Function<Integer, String>(){
@Override
public String apply(Integer input) {
return input != null
? naming.name(input)
: null;
}
})
.toSet();
instanceApi.setTagsInZone(zone, instance.get().getName(), tags, instance.get().getTags().getFingerprint());
InstanceInZone instanceInZone = new InstanceInZone(instance.get(), zone);
return new NodeAndInitialCredentials<InstanceInZone>(instanceInZone, instanceInZone.slashEncode(), credentials);
}