使用AWS Java的SDK,如何终止当前实例的CloudFormation堆栈?

时间:2022-03-23 17:14:47

Uses on-line decomentation I come up with the following code to terminate the current EC2 Instance:

使用在线装饰我提出以下代码来终止当前的EC2实例:

public class Ec2Utility {

    static private final String LOCAL_META_DATA_ENDPOINT = "http://169.254.169.254/latest/meta-data/";
    static private final String LOCAL_INSTANCE_ID_SERVICE = "instance-id";

    static public void terminateMe() throws Exception {
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest().withInstanceIds(getInstanceId());
        AmazonEC2 ec2 = new AmazonEC2Client();
        ec2.terminateInstances(terminateRequest);
    }

    static public String getInstanceId() throws Exception {
        //SimpleRestClient, is an internal wrapper on http client.
        SimpleRestClient client = new SimpleRestClient(LOCAL_META_DATA_ENDPOINT);
        HttpResponse response = client.makeRequest(METHOD.GET, LOCAL_INSTANCE_ID_SERVICE);
        return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    }
}

My issue is that my EC2 instance is under an AutoScalingGroup which is under a CloudFormationStack, that is because of my organisation deployment standards though this single EC2 is all there is there for this feature.

我的问题是我的EC2实例属于CloudFormationStack下的AutoScalingGroup,这是因为我的组织部署标准,尽管这个单一的EC2就是这个功能的全部。

So, I want to terminate the entire CloudFormationStack from the JavaSDK, keep in mind, I don't have the CloudFormation Stack Name in advance as I didn't have the EC2 Instance Id so I will have to get it from the code using the API calls.
How can I do that, if I can do it?

所以,我想从JavaSDK终止整个CloudFormationStack,请记住,我没有预先提供CloudFormation Stack Name,因为我没有EC2 Instance Id所以我将不得不从代码中获取它API调用。如果可以的话,我怎么能这样做?

2 个解决方案

#1


1  

you should be able to use the deleteStack method from cloud formation sdk

你应该能够使用cloud formation sdk中的deleteStack方法

DeleteStackRequest request = new DeleteStackRequest();
request.setStackName(<stack_name_to_be_deleted>);

AmazonCloudFormationClient client = new AmazonCloudFormationClient (<credentials>);
client.deleteStack(request);

If you don't have the stack name, you should be able to retrieve from the Tag of your instance

如果您没有堆栈名称,则应该能够从实例的Tag中进行检索

DescribeInstancesRequest request =new DescribeInstancesRequest();   
request.setInstanceIds(instancesList);
DescribeInstancesResult disresult = ec2.describeInstances(request);
List <Reservation> list  = disresult.getReservations();

for (Reservation res:list){
    List <Instance> instancelist = res.getInstances();

    for (Instance instance:instancelist){

        List <Tag> tags = instance.getTags();
        for (Tag tag:tags){
            if (tag.getKey().equals("aws:cloudformation:stack-name")) {
                tag.getValue(); // name of the stack
            }
        }

#2


0  

At the end I've achieved the desired behaviour using the set of the following util functions I wrote:

最后,我使用我编写的以下util函数集实现了所需的行为:

/**
 * Delete the CloudFormationStack with the given name.
 * 
 * @param stackName
 * @throws Exception
 */
static public void deleteCloudFormationStack(String stackName) throws Exception {
    AmazonCloudFormationClient client = new AmazonCloudFormationClient();
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName("");
    client.deleteStack(deleteStackRequest);
}

static public String getCloudFormationStackName() throws Exception {
    AmazonEC2 ec2 = new AmazonEC2Client();
    String instanceId = getInstanceId();
    List<Tag> tags = getEc2Tags(ec2, instanceId);
    for (Tag t : tags) {
        if (t.getKey().equalsIgnoreCase(TAG_KEY_STACK_NAME)) {
            return t.getValue();
        }
    }
    throw new Exception("Couldn't find stack name for instanceId:" + instanceId);
}

static private List<Tag> getEc2Tags(AmazonEC2 ec2, String instanceId) throws Exception {
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
    DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);
    List<Reservation> reservations = describeInstances.getReservations();
    if (reservations.isEmpty()) {
        throw new Exception("DescribeInstances didn't returned reservation for instanceId:" + instanceId);
    }
    List<Instance> instances = reservations.get(0).getInstances();
    if (instances.isEmpty()) {
        throw new Exception("DescribeInstances didn't returned instance for instanceId:" + instanceId);
    }
    return instances.get(0).getTags();
}

// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Example of usage from the code:
deleteCloudFormationStack(getCloudFormationStackName());
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#1


1  

you should be able to use the deleteStack method from cloud formation sdk

你应该能够使用cloud formation sdk中的deleteStack方法

DeleteStackRequest request = new DeleteStackRequest();
request.setStackName(<stack_name_to_be_deleted>);

AmazonCloudFormationClient client = new AmazonCloudFormationClient (<credentials>);
client.deleteStack(request);

If you don't have the stack name, you should be able to retrieve from the Tag of your instance

如果您没有堆栈名称,则应该能够从实例的Tag中进行检索

DescribeInstancesRequest request =new DescribeInstancesRequest();   
request.setInstanceIds(instancesList);
DescribeInstancesResult disresult = ec2.describeInstances(request);
List <Reservation> list  = disresult.getReservations();

for (Reservation res:list){
    List <Instance> instancelist = res.getInstances();

    for (Instance instance:instancelist){

        List <Tag> tags = instance.getTags();
        for (Tag tag:tags){
            if (tag.getKey().equals("aws:cloudformation:stack-name")) {
                tag.getValue(); // name of the stack
            }
        }

#2


0  

At the end I've achieved the desired behaviour using the set of the following util functions I wrote:

最后,我使用我编写的以下util函数集实现了所需的行为:

/**
 * Delete the CloudFormationStack with the given name.
 * 
 * @param stackName
 * @throws Exception
 */
static public void deleteCloudFormationStack(String stackName) throws Exception {
    AmazonCloudFormationClient client = new AmazonCloudFormationClient();
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName("");
    client.deleteStack(deleteStackRequest);
}

static public String getCloudFormationStackName() throws Exception {
    AmazonEC2 ec2 = new AmazonEC2Client();
    String instanceId = getInstanceId();
    List<Tag> tags = getEc2Tags(ec2, instanceId);
    for (Tag t : tags) {
        if (t.getKey().equalsIgnoreCase(TAG_KEY_STACK_NAME)) {
            return t.getValue();
        }
    }
    throw new Exception("Couldn't find stack name for instanceId:" + instanceId);
}

static private List<Tag> getEc2Tags(AmazonEC2 ec2, String instanceId) throws Exception {
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
    DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);
    List<Reservation> reservations = describeInstances.getReservations();
    if (reservations.isEmpty()) {
        throw new Exception("DescribeInstances didn't returned reservation for instanceId:" + instanceId);
    }
    List<Instance> instances = reservations.get(0).getInstances();
    if (instances.isEmpty()) {
        throw new Exception("DescribeInstances didn't returned instance for instanceId:" + instanceId);
    }
    return instances.get(0).getTags();
}

// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Example of usage from the code:
deleteCloudFormationStack(getCloudFormationStackName());
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX