class AwsLaunchTemplateImageUpdateService {

    public void updateImage(AuthenticatedContext authenticatedContext, CloudStack stack, CloudResource cfResource) {
        AwsCredentialView credentialView = new AwsCredentialView(authenticatedContext.getCloudCredential());
        String regionName = authenticatedContext.getCloudContext().getLocation().getRegion().getRegionName();
        AmazonCloudFormationClient cloudFormationClient = awsClient.createCloudFormationClient(credentialView, regionName);

        String imageName = stack.getImage().getImageName();
        String cfStackName = cfResource.getName();
        String cfTemplate = getCfTemplate(cfResource, cloudFormationClient);
        Json templateJson = new Json(cfTemplate);

        Map<String, String> encryptedImages = getEncryptedImagesMappedByAutoscalingGroupName(authenticatedContext, stack);
        stack.getGroups().forEach(group -> {
            String imageIdPath = String.format("Resources.%s.Properties.LaunchTemplateData.ImageId", AwsGroupView.getLaunchTemplateName(group.getName()));
            Object oldImageId = templateJson.getValue(imageIdPath);
            boolean encryptedImage = !"{\"Ref\":\"AMI\"}".equals(oldImageId.toString());
            if (encryptedImage) {
                replaceEncryptedImageInGroup(encryptedImages, imageName, templateJson, group, imageIdPath);
            }
        });

        String newCfTemplate = templateJson.getValue();
        UpdateStackRequest updateStackRequest = awsStackRequestHelper.createUpdateStackRequest(authenticatedContext, stack, cfStackName, newCfTemplate);
        cloudFormationClient.updateStack(updateStackRequest);
    }

}