Example usage for com.amazonaws.services.elasticbeanstalk.model EnvironmentDescription getEnvironmentId

List of usage examples for com.amazonaws.services.elasticbeanstalk.model EnvironmentDescription getEnvironmentId

Introduction

In this page you can find the example usage for com.amazonaws.services.elasticbeanstalk.model EnvironmentDescription getEnvironmentId.

Prototype


public String getEnvironmentId() 

Source Link

Document

The ID of this environment.

Usage

From source file:br.com.ingenieux.jenkins.plugins.awsebdeployment.cmd.ZeroDowntime.java

License:Apache License

@Override
public boolean perform() throws Exception {
    environmentNames = generateEnvironmentNames();

    EnvironmentDescription environmentDescription = null;

    try {//from  w w w .  j  a  v a 2  s .c om
        environmentDescription = lookupEnvironmentIds(environmentNames);

        environmentId = environmentDescription.getEnvironmentId();

    } catch (InvalidDeploymentTypeException exc) {
        log("Zero Downtime isn't valid for Worker Environments.");

        return true;
    } catch (InvalidEnvironmentsSizeException exc) {
        log("Unable to find any suitable environment. Aborting.");

        return true;
    }

    if (environmentDescription.getVersionLabel().equals(getVersionLabel())) {
        log("The version to deploy and currently used are the same. Even if you overwrite, AWSEB won't allow you to update."
                + "Skipping.");

        return true;
    }

    templateName = createConfigurationTemplate(environmentId);

    String clonedEnvironmentId = createEnvironment(getVersionLabel(), templateName, environmentNames);

    setEnvironmentId(clonedEnvironmentId);

    log("From now on, we'll use '%s' as the environmentId, but once finished, we'll swap and replace with '%s'",
            getEnvironmentId(), environmentId);

    return false;
}

From source file:br.com.ingenieux.mojo.beanstalk.BeanstalkTestBase.java

License:Apache License

public void clearEnvironments() {
    DescribeEnvironmentsResult environments = service.describeEnvironments();

    for (EnvironmentDescription d : environments.getEnvironments()) {
        service.terminateEnvironment(new TerminateEnvironmentRequest().withEnvironmentId(d.getEnvironmentId())
                .withTerminateResources(true));
    }//from   www . ja v  a  2s. c o  m
}

From source file:br.com.ingenieux.mojo.beanstalk.bg.BluegreenDeploymentMojo.java

License:Apache License

@Override
protected Object executeInternal() throws Exception {
    versionLabel = lookupVersionLabel(applicationName, versionLabel);

    getLog().info(format("Using version %s", versionLabel));

    Collection<EnvironmentDescription> envs = new WaitForEnvironmentCommand(this)
            .lookupInternal(new WaitForEnvironmentContextBuilder().withApplicationName(applicationName)
                    .withEnvironmentRef(environmentNamePrefix + "*").build());

    if (envs.size() > 2) {
        final Collection<String> environmentList = Collections2.transform(envs,
                new Function<EnvironmentDescription, String>() {
                    @Override//from  w  ww  .j a  v a 2 s  .  c  o m
                    public String apply(EnvironmentDescription input) {
                        return format("%s[%s]", input.getEnvironmentId(), input.getEnvironmentName());
                    }
                });

        String message = "Ooops. There are multiple environments matching the lookup spec: " + environmentList;

        getLog().warn(message);
        getLog().warn("Will pick one at random anyway as long as it uses WebServer tier name");
    }

    String otherEnvId = null;
    for (EnvironmentDescription e : envs) {
        if (!e.getEnvironmentId().equals(curEnv.getEnvironmentId())
                && "WebServer".equals(e.getTier().getName())) {
            otherEnvId = e.getEnvironmentId();
            break;
        }
    }

    getLog().info(
            format("(Green) Environment with environmentId['%s'] will be prepared once its ready to update",
                    curEnv.getEnvironmentId()));

    new WaitForEnvironmentCommand(this).execute(new WaitForEnvironmentContextBuilder()
            .withStatusToWaitFor("Ready").withApplicationName(applicationName)
            .withEnvironmentRef(curEnv.getEnvironmentId()).build());

    getLog().info(
            format("(Blue) Environment with environmentId['%s'] will be prepared once its ready to update",
                    otherEnvId));

    new WaitForEnvironmentCommand(this)
            .execute(new WaitForEnvironmentContextBuilder().withStatusToWaitFor("Ready")
                    .withApplicationName(applicationName).withEnvironmentRef(otherEnvId).build());

    getLog().info(format("(Blue) Updating environmentId to version %s", versionLabel));

    new UpdateEnvironmentCommand(this).execute(new UpdateEnvironmentContextBuilder()
            .withEnvironmentId(otherEnvId).withVersionLabel(versionLabel).build());

    getLog().info(format("(Blue) Waiting for environmentId['%s'] to get ready and green prior to switching",
            otherEnvId));

    new WaitForEnvironmentCommand(this).execute(new WaitForEnvironmentContextBuilder()
            .withStatusToWaitFor("Ready").withApplicationName(applicationName).withHealth("Green")
            .withEnvironmentRef(otherEnvId).build());

    getLog().info(format("Ok. Switching"));

    getService().swapEnvironmentCNAMEs(new SwapEnvironmentCNAMEsRequest()
            .withDestinationEnvironmentId(curEnv.getEnvironmentId()).withSourceEnvironmentId(otherEnvId));

    getLog().info(format("Done."));

    return null; //To change body of implemented methods use File | Settings | File Templates.
}

From source file:br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand.java

License:Apache License

protected List<Predicate<EnvironmentDescription>> getEnvironmentDescriptionPredicate(
        WaitForEnvironmentContext context) {
    // as well as those (which are used as predicate variables, thus being
    // final)/*  ww w . j a  v  a 2 s  . c o m*/
    final String environmentRef = context.getEnvironmentRef();
    final String statusToWaitFor = defaultString(context.getStatusToWaitFor(), "!Terminated");
    final String healthToWaitFor = context.getHealth();

    // Sanity Check
    Validate.isTrue(isNotBlank(environmentRef), "EnvironmentRef is blank or null", environmentRef);

    // some argument juggling

    final boolean negated = statusToWaitFor.startsWith("!");

    // argument juggling

    List<Predicate<EnvironmentDescription>> result = new ArrayList<Predicate<EnvironmentDescription>>();

    if (environmentRef.matches("e-\\p{Alnum}{10}")) {
        result.add(new Predicate<EnvironmentDescription>() {
            @Override
            public boolean apply(EnvironmentDescription t) {
                return t.getEnvironmentId().equals(environmentRef);
            }
        });

        info("... with environmentId equal to '%s'", environmentRef);
    } else if (environmentRef.matches(".*\\Q.elasticbeanstalk.com\\E")) {
        result.add(new Predicate<EnvironmentDescription>() {
            @Override
            public boolean apply(EnvironmentDescription t) {
                return defaultString(t.getCNAME()).equals(environmentRef);
            }
        });
        info("... with cname set to '%s'", environmentRef);
    } else {
        String tmpRE = Pattern.quote(environmentRef);

        if (environmentRef.endsWith("*")) {
            tmpRE = format("^\\Q%s\\E.*", environmentRef.substring(0, -1 + environmentRef.length()));
        }

        final String environmentRefNameRE = tmpRE;

        result.add(new Predicate<EnvironmentDescription>() {
            @Override
            public boolean apply(EnvironmentDescription t) {
                return t.getEnvironmentName().matches(environmentRefNameRE);
            }
        });

        info("... with environmentName matching re '%s'", environmentRefNameRE);
    }

    {
        // start building predicates with the status one - "![status]" must
        // be equal to status or not status
        final int offset = negated ? 1 : 0;
        final String vStatusToWaitFor = statusToWaitFor.substring(offset);

        result.add(new Predicate<EnvironmentDescription>() {
            public boolean apply(EnvironmentDescription t) {

                boolean result = vStatusToWaitFor.equals(t.getStatus());

                if (negated) {
                    result = !result;
                }

                debug("testing status '%s' as equal as '%s' (negated? %s, offset: %d): %s", vStatusToWaitFor,
                        t.getStatus(), negated, offset, result);

                return result;
            }
        });

        info("... with status %s set to '%s'", (negated ? "*NOT*" : " "), vStatusToWaitFor);
    }

    {
        if (isNotBlank(healthToWaitFor)) {
            result.add(new Predicate<EnvironmentDescription>() {
                @Override
                public boolean apply(EnvironmentDescription t) {
                    return t.getHealth().equals(healthToWaitFor);
                }
            });

            info("... with health equal to '%s'", healthToWaitFor);
        }
    }
    return result;
}

From source file:br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand.java

License:Apache License

public EnvironmentDescription executeInternal(WaitForEnvironmentContext context) throws Exception {
    // Those are invariants
    long timeoutMins = context.getTimeoutMins();

    Date expiresAt = new Date(System.currentTimeMillis() + MINS_TO_MSEC * timeoutMins);
    Date lastMessageRecord = new Date();

    info("Environment Lookup");

    List<Predicate<EnvironmentDescription>> envPredicates = getEnvironmentDescriptionPredicate(context);
    Predicate<EnvironmentDescription> corePredicate = envPredicates.get(0);
    Predicate<EnvironmentDescription> fullPredicate = Predicates.and(envPredicates);

    do {//  w ww  .  j  a  v  a  2s  .  c om
        DescribeEnvironmentsRequest req = new DescribeEnvironmentsRequest()
                .withApplicationName(context.getApplicationName()).withIncludeDeleted(true);

        final List<EnvironmentDescription> envs = parentMojo.getService().describeEnvironments(req)
                .getEnvironments();

        Collection<EnvironmentDescription> validEnvironments = Collections2.filter(envs, fullPredicate);

        debug("There are %d environments", validEnvironments.size());

        if (1 == validEnvironments.size()) {
            EnvironmentDescription foundEnvironment = validEnvironments.iterator().next();

            debug("Found environment %s", foundEnvironment);

            return foundEnvironment;
        } else {
            debug("Found %d environments. No good. Ignoring.", validEnvironments.size());

            for (EnvironmentDescription d : validEnvironments) {
                debug(" ... %s", d);
            }

            // ... but have we've got any closer match? If so, dump recent events

            Collection<EnvironmentDescription> foundEnvironments = Collections2.filter(envs, corePredicate);

            if (1 == foundEnvironments.size()) {
                EnvironmentDescription foundEnvironment = foundEnvironments.iterator().next();

                DescribeEventsResult events = service.describeEvents(
                        new DescribeEventsRequest().withApplicationName(foundEnvironment.getApplicationName())
                                .withStartTime(new Date(1000 + lastMessageRecord.getTime()))
                                .withEnvironmentId(foundEnvironment.getEnvironmentId()).withSeverity("TRACE"));

                Set<EventDescription> eventList = new TreeSet<EventDescription>(
                        new EventDescriptionComparator());

                eventList.addAll(events.getEvents());

                for (EventDescription d : eventList) {
                    info(String.format("%s %s %s", d.getSeverity(), d.getEventDate(), d.getMessage()));

                    if (d.getSeverity().equals(("ERROR"))) {
                        throw new MojoExecutionException(
                                "Something went wrong in while waiting for the environment setup to complete : "
                                        + d.getMessage());
                    }
                    lastMessageRecord = d.getEventDate();
                }
            }
        }

        sleepInterval(POLL_INTERVAL);
    } while (!timedOutP(expiresAt));

    throw new MojoExecutionException("Timed out");
}

From source file:br.com.ingenieux.mojo.beanstalk.env.ReplaceEnvironmentMojo.java

License:Apache License

@Override
protected Object executeInternal() throws Exception {
    solutionStack = lookupSolutionStack(solutionStack);

    /*/*from w  ww. jav  a 2 s  .c  om*/
     * Is the desired cname not being used by other environments? If so,
     * just launch the environment
     */
    if (!hasEnvironmentFor(applicationName, cnamePrefix)) {
        if (getLog().isInfoEnabled()) {
            getLog().info("Just launching a new environment.");
        }

        return super.executeInternal();
    }

    /*
       * Gets the current environment using this cname
     */
    EnvironmentDescription curEnv = getEnvironmentFor(applicationName, cnamePrefix);

    if (curEnv.getVersionLabel().equals(versionLabel) && skipIfSameVersion) {
        getLog().warn(format("Environment is running version %s and skipIfSameVersion is true. Returning",
                versionLabel));

        return null;
    }

    /*
         * Decides on a environmentRef, and launches a new environment
     */
    String cnamePrefixToCreate = getCNamePrefixToCreate();

    if (getLog().isInfoEnabled()) {
        getLog().info("Creating a new environment on " + cnamePrefixToCreate + ".elasticbeanstalk.com");
    }

    if (copyOptionSettings) {
        copyOptionSettings(curEnv);
    }

    if (!solutionStack.equals(curEnv.getSolutionStackName()) && copySolutionStack) {
        if (getLog().isWarnEnabled()) {
            getLog().warn(format(
                    "(btw, we're launching with solutionStack/ set to '%s' based on the existing env instead of the "
                            + "default ('%s'). If this is not the desired behavior please set the copySolutionStack property to"
                            + " false.",
                    curEnv.getSolutionStackName(), solutionStack));
        }

        solutionStack = curEnv.getSolutionStackName();
    }

    /**
     * TODO: Spend a comfy Saturday Afternoon in a Coffee Shop trying to figure out this nice boolean logic with Karnaugh Maps sponsored by Allogy
     */

    boolean userWantsHealthyExitStatus = mustBeHealthy;
    final boolean currentEnvironmentIsRed = "Red".equals(curEnv.getHealth());

    if (redToRedOkay) {
        //Side-effect: must be before createEnvironment() and waitForEnvironment() to effect superclass behavior.
        mustBeHealthy = !currentEnvironmentIsRed;
    }

    /**
     * // I really meant it.
     */

    String newEnvironmentName = getNewEnvironmentName(
            StringUtils.defaultString(this.environmentName, curEnv.getEnvironmentName()));

    if (getLog().isInfoEnabled()) {
        getLog().info("And it'll be named " + newEnvironmentName);
        getLog().info("And it will replace a '" + curEnv.getHealth() + "' enviroment");
    }

    CreateEnvironmentResult createEnvResult = createEnvironment(cnamePrefixToCreate, newEnvironmentName);

    /*
       * Waits for completion
     */
    EnvironmentDescription newEnvDesc = null;

    try {
        newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId());
    } catch (Exception exc) {
        /*
         * Terminates the failed launched environment
        */
        terminateEnvironment(createEnvResult.getEnvironmentId());

        handleException(exc);

        return null;
    }

    /*
       * Swaps. Due to beanstalker-25, we're doing some extra logic we
     * actually woudln't want to.
     */
    {
        boolean swapped = false;
        for (int i = 1; i <= maxAttempts; i++) {
            try {
                swapEnvironmentCNames(newEnvDesc.getEnvironmentId(), curEnv.getEnvironmentId(), cnamePrefix,
                        newEnvDesc);
                swapped = true;
                break;
            } catch (Throwable exc) {
                if (exc instanceof MojoFailureException) {
                    exc = Throwable.class.cast(MojoFailureException.class.cast(exc).getCause());
                }

                getLog().warn(format("Attempt #%d/%d failed. Sleeping and retrying. Reason: %s (type: %s)", i,
                        maxAttempts, exc.getMessage(), exc.getClass()));

                sleepInterval(attemptRetryInterval);
            }
        }

        if (!swapped) {
            getLog().info(
                    "Failed to properly Replace Environment. Finishing the new one. And throwing you a failure");

            terminateEnvironment(newEnvDesc.getEnvironmentId());

            String message = "Unable to swap cnames. btw, see https://github.com/ingenieux/beanstalker/issues/25 and help us improve beanstalker";

            getLog().warn(message);

            throw new MojoFailureException(message);
        }
    }

    /*
       * Terminates the previous environment
     */
    terminateEnvironment(curEnv.getEnvironmentId());

    /**
     * TODO: I really need a Saturday Afternoon in order to understand this ffs.
     */
    if (currentEnvironmentIsRed && userWantsHealthyExitStatus) {
        final String newHealth = newEnvDesc.getHealth();

        if (newHealth.equals("Green")) {
            getLog().info("Previous environment was 'Red', new environment is 'Green' (for the moment)");
        } else {
            getLog().warn(format("Previous environment was 'Red', replacement environment is currently '%s'",
                    newHealth));

            //NB: we have already switched from one broken service to another, so this is more for the build status indicator...
            newEnvDesc = waitForGreenEnvironment(createEnvResult.getEnvironmentId());
        }
    }

    return createEnvResult;
}

From source file:br.com.ingenieux.mojo.beanstalk.env.ReplaceEnvironmentMojo.java

License:Apache License

/**
 * Prior to Launching a New Environment, lets look and copy the most we can
 *
 * @param curEnv current environment//  www  .j a va2s . co m
 */
private void copyOptionSettings(EnvironmentDescription curEnv) throws Exception {
    /**
     * Skip if we don't have anything
     */
    if (null != this.optionSettings && this.optionSettings.length > 0) {
        return;
    }

    DescribeConfigurationSettingsResult configSettings = getService()
            .describeConfigurationSettings(new DescribeConfigurationSettingsRequest()
                    .withApplicationName(applicationName).withEnvironmentName(curEnv.getEnvironmentName()));

    List<ConfigurationOptionSetting> newOptionSettings = new ArrayList<ConfigurationOptionSetting>(
            configSettings.getConfigurationSettings().get(0).getOptionSettings());

    ListIterator<ConfigurationOptionSetting> listIterator = newOptionSettings.listIterator();

    while (listIterator.hasNext()) {
        ConfigurationOptionSetting curOptionSetting = listIterator.next();

        boolean bInvalid = harmfulOptionSettingP(curEnv.getEnvironmentId(), curOptionSetting);

        if (bInvalid) {
            getLog().info(format("Excluding Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(),
                    curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting.getValue())));
            listIterator.remove();
        } else {
            getLog().info(format("Including Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(),
                    curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting.getValue())));
        }
    }

    Object __secGroups = project.getProperties().get("beanstalk.securityGroups");

    if (null != __secGroups) {
        String securityGroups = StringUtils.defaultString(__secGroups.toString());

        if (!StringUtils.isBlank(securityGroups)) {
            ConfigurationOptionSetting newOptionSetting = new ConfigurationOptionSetting(
                    "aws:autoscaling:launchconfiguration", "SecurityGroups", securityGroups);
            newOptionSettings.add(newOptionSetting);
            getLog().info(format("Including Option Setting: %s:%s['%s']", newOptionSetting.getNamespace(),
                    newOptionSetting.getOptionName(), newOptionSetting.getValue()));
        }
    }

    /*
       * Then copy it back
     */
    this.optionSettings = newOptionSettings.toArray(new ConfigurationOptionSetting[newOptionSettings.size()]);
}

From source file:br.com.ingenieux.mojo.beanstalk.env.SwapEnvironmentCnamesMojo.java

License:Apache License

@Override
protected Object executeInternal() throws AbstractMojoExecutionException {
    EnvironmentDescription sourceEnvironment = lookupEnvironment(applicationName,
            ensureSuffix(sourceEnvironmentCNamePrefix));
    EnvironmentDescription targetEnvironment = lookupEnvironment(applicationName,
            ensureSuffix(targetEnvironmentCNamePrefix));

    SwapCNamesContext context = SwapCNamesContextBuilder.swapCNamesContext()//
            .withSourceEnvironmentId(sourceEnvironment.getEnvironmentId())//
            .withSourceEnvironmentName(sourceEnvironment.getEnvironmentName())//
            .withDestinationEnvironmentId(targetEnvironment.getEnvironmentId())//
            .withDestinationEnvironmentName(targetEnvironment.getEnvironmentName())//
            .build();// ww  w .j a v a  2 s . c  om

    SwapCNamesCommand command = new SwapCNamesCommand(this);

    return command.execute(context);

}

From source file:br.com.ingenieux.mojo.beanstalk.version.RollbackVersionMojo.java

License:Apache License

Object changeToVersion(EnvironmentDescription d, ApplicationVersionDescription latestVersionDescription) {
    String curVersionLabel = d.getVersionLabel();
    String versionLabel = latestVersionDescription.getVersionLabel();

    UpdateEnvironmentRequest request = new UpdateEnvironmentRequest().withEnvironmentId(d.getEnvironmentId())
            .withVersionLabel(versionLabel);

    getLog().info("Changing versionLabel for Environment[name=" + curEnv.getEnvironmentName()
            + "; environmentId=" + curEnv.getEnvironmentId() + "] from version " + curVersionLabel
            + " to version " + latestVersionDescription.getVersionLabel());

    if (dryRun) {
        return null;
    }//from  w  w  w .j  av a 2s  .com

    return getService().updateEnvironment(request);
}

From source file:fr.xebia.cloud.amazon.aws.tools.AmazonAwsUtils.java

License:Apache License

public static void synchronousTerminateEnvironments(@Nonnull String applicationName,
        @Nonnull AWSElasticBeanstalk beanstalk) {
    Set<String> statusToTerminate = Sets.newHashSet("Launching", "Updating", "Ready");
    Set<String> statusTerminating = Sets.newHashSet("Terminating");

    List<EnvironmentDescription> environments = beanstalk
            .describeEnvironments(new DescribeEnvironmentsRequest().withApplicationName(applicationName))
            .getEnvironments();/*from w w w.  j  a v a  2  s .  c o  m*/
    List<EnvironmentDescription> environmentsToWaitFor = Collections.emptyList();

    int counter = 0;
    while (counter < 1 * 60) {
        environmentsToWaitFor = Lists.newArrayList();
        for (EnvironmentDescription environment : environments) {
            if (statusToTerminate.contains(environment.getStatus())) {
                TerminateEnvironmentResult terminateEnvironmentResult = beanstalk.terminateEnvironment(
                        new TerminateEnvironmentRequest().withEnvironmentId(environment.getEnvironmentId()));
                logger.debug("Terminate environment {}, status:{} - ",
                        new Object[] { environment.getEnvironmentName(), environment.getStatus(),
                                terminateEnvironmentResult });
                environmentsToWaitFor.add(environment);
            } else if (statusTerminating.contains(environment.getStatus())) {
                environmentsToWaitFor.add(environment);
                logger.debug("Skip termination of not running environment {}", environment);
            } else {
                logger.trace("skip terminated environment {}", environment);
            }
        }
        if (environmentsToWaitFor.isEmpty()) {
            break;
        } else {
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
            environments = beanstalk
                    .describeEnvironments(
                            new DescribeEnvironmentsRequest().withApplicationName(applicationName))
                    .getEnvironments();
        }
    }

    if (!environmentsToWaitFor.isEmpty()) {
        logger.warn("Failure to terminate {}", environmentsToWaitFor);
    }
}