Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aws-lambda: Migrating from currentVersion.addAlias() to function.addAlias() #27884

Open
jonnekaunisto opened this issue Nov 7, 2023 · 9 comments
Labels
@aws-cdk/aws-lambda Related to AWS Lambda documentation This is a problem with documentation. effort/small Small work item – less than a day of effort feature-request A feature should be added or improved. p2

Comments

@jonnekaunisto
Copy link
Contributor

Describe the issue

In the following commit currentVersion.addAlias() was deprecated: a79bc47

The advice is to move to using function.addAlias(), however by moving to using that function the logical id of the alias will change, which means our alias would try to get recreated which will fail due to the alias already existing.

What is the best path to migrating off of the deprecated function?

Links

https://github.com/aws/aws-cdk/blame/main/packages/aws-cdk-lib/aws-lambda/lib/lambda-version.ts

@jonnekaunisto jonnekaunisto added documentation This is a problem with documentation. needs-triage This issue or PR still needs to be triaged. labels Nov 7, 2023
@github-actions github-actions bot added the @aws-cdk/aws-lambda Related to AWS Lambda label Nov 7, 2023
@khushail khushail added investigating This issue is being investigated and/or work is in progress to resolve the issue. and removed needs-triage This issue or PR still needs to be triaged. labels Nov 8, 2023
@pahud
Copy link
Contributor

pahud commented Nov 8, 2023

Yes looks like new Alias with the same name can't be replaced.

A workaround is to use CfnResource.overrideLogicalId() to override with the original logicalId. For example:

export class Demo extends DemoStack {
	constructor(scope: Construct, id: string, props: StackProps) {
		super(scope, id, props);

		const fn = new lambda.Function(this, 'Func', {
			runtime: lambda.Runtime.PYTHON_3_10,
			code: lambda.Code.fromInline('def handler(event, context): return'),
			handler: 'index.handler',
		})

		// fn.currentVersion.addAlias('myalias')
		const cfnalias = fn.addAlias('myalias').node.tryFindChild('Resource') as lambda.CfnAlias
		cfnalias.overrideLogicalId('FuncCurrentVersionAliasmyalias70055E20')
	}
}

And run cdk diff to verify it:

image

@pahud pahud added response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. p2 effort/small Small work item – less than a day of effort and removed investigating This issue is being investigated and/or work is in progress to resolve the issue. labels Nov 8, 2023
@jonnekaunisto
Copy link
Contributor Author

We deploy our stacks to around 22 regions and each of the regions appear to have different logical id for the alias. Is there any better way to migrate than to hardcode all of the logical ids?

@github-actions github-actions bot removed the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. label Nov 9, 2023
@jakob-lj
Copy link

jakob-lj commented Nov 10, 2023

You could also calculate the Logical Id hash, and "generate" the logical ids for the already deployed functions like this:

class Demo extends cdk.Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const fn = new lambda.Function(this, "Func", {
      runtime: lambda.Runtime.PYTHON_3_10,
      code: lambda.Code.fromInline("def handler(event, context): return"),
      handler: "index.handler",
    });

    const aliasName = "myalias";

    // fn.currentVersion.addAlias(aliasName);
    const cfnalias = fn
      .addAlias(aliasName)
      .node.tryFindChild("Resource") as lambda.CfnAlias;

    const oldLogicalIdComponents = [
      "Func",
      "CurrentVersion",
      `Alias${aliasName}`,
    ];

    const oldLogicalIdHash = pathHash([...oldLogicalIdComponents, "Resource"]);

    const oldLogicalId = oldLogicalIdComponents.join("") + oldLogicalIdHash;

    cfnalias.overrideLogicalId(oldLogicalId);
  }
}

Here, I used the pathHash method provided (but not exported to my knowledge) here:

function pathHash(path: string[]): string {
const md5 = md5hash(path.join(PATH_SEP));
return md5.slice(0, HASH_LEN).toUpperCase();
}

Same solution as @pahud , but you don't have to hard code each of the logical Ids for your 22 (👀) regions.

Screenshot 2023-11-11 at 00 01 04

(Just a note: I don't think I would have done this myself, but I also don't think the method can be removed if this is the migration step needed ...)

@Jam-Davis
Copy link

Hello, this is still happening in aws-cdk-lib v2.160.0. Are there any plans to implement a solution for this in aws-cdk-lib rather than requiring a code workaround like in a previous comment?

We deploy our stacks to around 22 regions and each of the regions appear to have different logical id for the alias. Is there any better way to migrate than to hardcode all of the logical ids?

Like Jonne Kaunisto, we are running into this problem across many regions. We also have multiple stack deploys written in several different languages. We just ran into this problem in Python so I'm already having to recreate the solution which is proving difficult. It would be greatly appreciated if there was a way to indicate that this is an update to an existing Alias, not a new Alias with the same name as an existing Alias.

@pahud
Copy link
Contributor

pahud commented Oct 4, 2024

We will bring this up to the team's attention and hopefully add some insights here.

@Jam-Davis
Copy link

Jam-Davis commented Oct 4, 2024

Thank you @pahud. It's still causing us to be fully unable to deploy our nested stacks containing LambdaDeploymentGroups for our step functions as I haven't quite been able to get the workaround to well work in python.

We're in an air gapped system so I can't just copy/paste here, but I'm able to generate the same logical_id for the existing aliases and confirm it through cdk diff, but cdk deploy fails with the same error messages as before the workaround; a bunch of errors like: ... | UPDATE_FAILED | AWS::Lambda::Alias | .../Function/Aliasgreen (...FunctionAliasgreenA3D7FF90) Deployment failed with deployment id - Settable [value=d-QN5NW12K9, ready=true]

We're currently using CDK v2.114.1, but I'm trying to update that to latest (v2.160.0) to see if that helps but I'm running into other problems with existing code.

@Jam-Davis
Copy link

Jam-Davis commented Oct 4, 2024

I also noticed it's possible to get an existing lambda function's aws:cloudformation:logical-id using boto3, but not the lambda alias's logical-id which is why we have to use such a workaround that recreates the logical-id from the alias's function id and alias name. This is pretty much what I have it boiled down to:

def path_hash(path: List[str]) -> str:
    return hashlib.md5("/".join(path).encode()).hexdigest()[:8].upper()

def generate_default_logical_id(path: List[str]) -> str:
    return "".join(path) + path_hash(path + ["Resource")

alias = self.lambda_function.add_alias(alias_name)
cfn_alias: CfnAlias = alias.node.try_find_child("Resource")
logical_id_components = [lambda_function_jsii_id, "Function", f"Alias{alias_name}"]
logical_id = generate_default_logical_id(logical_id_components)
cfn_alias.override_logical_id(logical_id)
LambdaDeploymentGroup(self, id, application=..., alias=alias, ...)

@Jam-Davis
Copy link

Jam-Davis commented Oct 7, 2024

Updating to CDK v2.160.0 didn't fix our deploys, it actually made it worse because our rollback failed after the deploy failed so then I had to delete and recreate our stack which is exactly what we're trying to avoid when we make updates to these lambdas.

This appears to have happened because it changed the names of roles and policies used by our lambdas and deleted the old ones during the update so then the old roles and policies didn't exist for the rollback.

@Jam-Davis
Copy link

As the workaround wasn't working for us, we eventually had to remove any LambdaDeploymentGroup and codedeploy LambdaApplication we were using to avoid this bug alltogether.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
@aws-cdk/aws-lambda Related to AWS Lambda documentation This is a problem with documentation. effort/small Small work item – less than a day of effort feature-request A feature should be added or improved. p2
Projects
None yet
Development

No branches or pull requests

6 participants