Skip to content

serverless package now requires AWS credentials if a layer is present in serverless.yml #8187

Open

Description

@ryan-roemer

Hi folks!

I'm the author of serverless-jetpack and in upgrading my test fixture suite from [email protected] to [email protected] (which runs virtually all of the available serverless config variations) I noticed the following issue:

If you are just running serverless package to create artifacts and you have a layer included in serverless.yml configuration there is now a hard requirement to have working AWS credentials available (ServerlessError: AWS provider credentials not found).

I'm assuming that this is not intended as packaging seems like it should be able to be completed without credentials.

For ease of reproduction, I have a minimal repository that can be installed to reproduce the issue at: https://github.com/FormidableLabs/serverless-layers-aws-issue

Hope that helps and thanks for the help!

serverless.yml
service: layers-aws-issue

package:
  excludeDevDependencies: true
  include:
    - "!node_modules/**"
    - "!**/*.lock"

custom:
  region: ${opt:region, env:AWS_REGION, "us-east-1"}
  stage: ${opt:stage, env:STAGE, "sandbox"}

provider:
  name: aws
  runtime: nodejs8.10
  region: ${self:custom.region}
  stage: ${self:custom.stage}

# ISSUE NOTE: If you comment out this entire `layers` section,
# packaging works fine without needing AWS credentials.
layers:
  base:
    path: layer

functions:
  base:
    handler: index.handler
    events: # Use a generic proxy to allow Express app to route.
      - http: ANY /base
      - http: 'ANY /base/{proxy+}'
serverless package output
$ SLS_DEBUG=* serverless package
Serverless: To ensure safe major version upgrades ensure "frameworkVersion" setting in service configuration (recommended setup: "frameworkVersion: ^1.81.1")

Serverless: Load command interactiveCli
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command config:tabcompletion
Serverless: Load command config:tabcompletion:install
Serverless: Load command config:tabcompletion:uninstall
Serverless: Load command create
Serverless: Load command install
Serverless: Load command package
Serverless: Load command deploy
Serverless: Load command deploy:function
Serverless: Load command deploy:list
Serverless: Load command deploy:list:functions
Serverless: Load command invoke
Serverless: Load command invoke:local
Serverless: Load command info
Serverless: Load command logs
Serverless: Load command metrics
Serverless: Load command print
Serverless: Load command remove
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command slstats
Serverless: Load command plugin
Serverless: Load command plugin
Serverless: Load command plugin:install
Serverless: Load command plugin
Serverless: Load command plugin:uninstall
Serverless: Load command plugin
Serverless: Load command plugin:list
Serverless: Load command plugin
Serverless: Load command plugin:search
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command upgrade
Serverless: Load command uninstall
Serverless: Load command login
Serverless: Load command logout
Serverless: Load command generate-event
Serverless: Load command test
Serverless: Load command dashboard
Serverless: Load command output
Serverless: Load command output:get
Serverless: Load command output:list
Serverless: Load command param
Serverless: Load command param:get
Serverless: Load command param:list
Serverless: Load command studio
Serverless: Load command dev
Serverless: Invoke package
Serverless: Invoke aws:common:validate
Serverless: Invoke aws:common:cleanupTempDir
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Excluding development dependencies...
Serverless: [AWS cloudformation undefined 2.026s 0 retries] describeStacks({ StackName: 'layers-aws-issue-sandbox' })
 
  Serverless Error ---------------------------------------
 
  ServerlessError: AWS provider credentials not found. Learn how to set up AWS provider credentials in our docs here: <http://slss.io/aws-creds-setup>.
      at /Users/rye/scm/fmd/serverless-layers-aws-issue/node_modules/serverless/lib/plugins/aws/provider/awsProvider.js:527:29
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com
 
  Your Environment Information ---------------------------
     Operating System:          darwin
     Node Version:              12.18.3
     Framework Version:         1.81.1 (local)
     Plugin Version:            3.8.3
     SDK Version:               2.3.1
     Components Version:        2.34.9

Installed version

Framework Core: 1.81.1 (local)
Plugin: 3.8.3
SDK: 2.3.1
Components: 2.34.9

Activity

  1. ryan-roemer commented on Sep 3, 2020

    @ryan-roemer
    ContributorAuthor

    Reviewing the source code, I think that the issue was introduced by #7680 in the new compareWithLastLayer() function that reaches out to AWS directly to see whether or not the being-packaged layer is the same as the presently deployed one.

    If I'm understanding what's going, my two cents would be that as a deploy-time thing it would totally fine to check if the to-be-uploaded layer matches the alread-deployed layer and skip deployment. But as a package-time thing, especially for the many situations in which you want separate, pristine artifacts, the layers should always be packaged.

  2. medikoo commented on Sep 4, 2020

    @medikoo
    Contributor

    @ryan-roemer thanks for report. It is definitely a valid concern, @exoego what do you think about that?

    as a deploy-time thing it would totally fine to check if the to-be-uploaded layer matches the alread-deployed layer and skip deployment. But as a package-time thing, especially for the many situations in which you want separate, pristine artifacts, the layers should always be packaged.

    It sounds reasonable, still one issue I see with that, is that it'll break consistency. Currently (I believe), effect for operations as (1) sls deploy and (2) sls package_--package foo && sls deploy --package foo is equivalent. While with above we will break that, and that can be confusing.

    Maybe it'll be better to introduce an option which will allow to opt-out from comparision against deployed layers?

  3. exoego commented on Sep 4, 2020

    @exoego
    Contributor

    I am fine with moving compareWithLastLayer() and related codes to deploy-time only.

    I was not aware that #7680 introduced such accidental breaking change (AWS credentials required for package), since I am using only deploy and have never used package.

  4. ryan-roemer commented on Oct 1, 2020

    @ryan-roemer
    ContributorAuthor

    I'm taking a stab at a PR here, but did want to get some more input if possible. Seems like there are two options:

    Option One - sls package deterministically produces artifacts irrespective of deployed state.

    A good portion of our client work using the Serverless framework relies on having deterministic artifacts produced by sls package in CI/CD, stored remotely, then deployed (without another build/package) later. So that we can rollback arbitrarily to known, vetted artifacts at any point in time that are totally self-contained.

    Any checks for "should I upload this?" are performed during sls deploy lifecycle events only. If I'm reading things correctly, this requires extracting lib/plugins/aws/package/compile/layers/index.js:compareWithLastLayer() out and moving it to some place like lib/plugins/aws/deploy/lib/checkForChanges.js or maybe some other place to mutate the CloudFormation template before deploy to reflect the already deployed layer.

    Option Two - sls package produces different artifacts based on currently deployed state.

    This would be @medikoo mentioned here wherein the CloudFormation template information for a given layer is nondeterministic, mutable based on the time of running sls package and the state of the currently deployed.

    The implementation would be much easier, such as adding a config option to serverless.yml and consumed in lib/plugins/aws/package/compile/layers/index.js:compareWithLastLayer().

    Thoughts

    I'm leaning toward option one because it keeps sls package clean, deterministic, and doesn't require special extra configuration for usage. It is also inline with not having compile/functions do any remote determination as to if the function already exists. But it is a lot more work for me to grok where to place the check.

    I'd love to hear @medikoo and @exoego 's thoughts on this approach and any tips for where to place the compareWithLastLayer() function / mutation...

    Thanks!

  5. ryan-roemer commented on Oct 1, 2020

    @ryan-roemer
    ContributorAuthor

    Digging in more to lib/plugins/aws/deploy/lib/checkForChanges.js I think that checkIfDeploymentIsNecessary() is extended or refactored to do something like:

    1. If all object hashes (cf template, functions zips, layers zips) are identical, set this.serverless.service.provider.shouldNotDeploy = true and skip entire deployment. (Existing behavior).
    2. If the cf template hash has not changed, but some of function or layer zip hashes have, then rewrite the cf template like we currently have in lib/plugins/aws/package/compile/layers/index.js:compareWithLastLayer() for functions and layers to do a new CF template but referring to some existing functions and layers.
    3. If the CF template hash has changed or all of the functions + layers hashes have changed, just do a fresh normal deployment.

    This would be a larger change as:

    1. Now sls deploy can mutate the cf template which it previously didn't. (I think this is better than sls package mutating the cf template non-deterministically, but ...)
    2. We could potentially also do this for functions. Although to minimize change surface I could try it out for just layers at first in a PR to try and keep functionality as equivalent as possible to current.
  6. medikoo commented on Oct 2, 2020

    @medikoo
    Contributor

    @ryan-roemer with your reasoning, you've convinced me, that indeed option 1 is probably better.

    As as you pointed when we just package, it's for a deployment at uncertain future point. While we package & deploy it's fine to imply some optimizations in relation to current external state.

    Now sls deploy can mutate the cf template which it previously didn't.

    I think it's not an issue. Technically it's purely about moving this operation from package to pre deploy stage

    We could potentially also do this for functions. Although to minimize change surface I could try it out for just layers at first in a PR to try and keep functionality as equivalent as possible to current.

    To not overcomplicate this, I would just focus on moving layers related logic here, and eventually in second batch we can implement same for functions

  7. ryan-roemer commented on Oct 3, 2020

    @ryan-roemer
    ContributorAuthor

    Thanks! I'm working along on this in a very WIP/draft state at master...FormidableLabs:layers-aws-auth and I think I have a good idea of where everything will go to try and minimize change surface in an ultimate PR.

    One side note -- I discovered an existing bug along the way in this code:

    const zipFiles = globby.sync(['**.zip'], { cwd: serverlessDirPath, dot: true, silent: true });
    if (this.serverless.service.package.artifact) {
    zipFiles.push(
    path.resolve(this.serverless.config.servicePath, this.serverless.service.package.artifact)
    );
    }
    const zipFilePaths = zipFiles.map(zipFile => path.resolve(serverlessDirPath, zipFile));

    The issue is that if a plugin (like jetpack does) or outside build process places it's own artifact into .serverless/<FROM_PACKAGE_ARTIFACT>.zip and sets package.artifact we end up with a case wherein we glob .serverless/<FROM_PACKAGE_ARTIFACT>.zip first in the sync glob and then add the exact same file(s) again in the package.artifact code in the conditional. This has the effect of (1) doing extra unneeded I/O for the hash calculation and (2) adding extra identical hashes to the localHashes array which causes the _.isEqual() check to be false and ultimately serverless will deploy when it otherwise shouldn't.

    In my PR, I'm refactoring the _.isEqual() comparison slightly so the issue will go away as part of the work. I'm not planning on adding a separate bug / PR unless someone else wants it, and just intend to comment / flag the change as part of my PR for this issue.

  8. medikoo commented on Oct 5, 2020

    @medikoo
    Contributor

    Thanks @ryan-roemer for pointing. If fixing that derives from main goal of your work, then I would introduce it with other PR's. Note that we generate changelog of out commits, and one PR is one commit. Ideally bug fixes and features should be introduced in its own dedicated PR's.

    Here some solution could be, to in resolution phase add paths to some Set instance (it'll guarantee no duplicates), and after having all paths resolved simply populate zipFiles with values gathered in set

  9. ryan-roemer commented on Oct 5, 2020

    @ryan-roemer
    ContributorAuthor

    Makes total sense @medikoo ! I’m planning on switching to an object for the isEqual comparison for the existing case because I need to later know which hashes are different for the case of only mutating CF template for layers, so I would effectively be rewriting a straight “fix” for the issue.

    If I don’t ultimately end up going down that road and leave that existing code path in place, I’ll open up a separate small PR for just that fix!

  10. ryan-roemer commented on Oct 6, 2020

    @ryan-roemer
    ContributorAuthor

    @medikoo -- I'm toying with a different direction as to where to refactor the CF mutation to and so as not to block an otherwise quick bugfix, I have a fix per your guidance for the isEqual() comparison at #8351

  11. medikoo commented on Nov 2, 2021

    @medikoo
    Contributor

    I revisited this issue, just now, and I think it requires some update after we looked more thoroughly into design issues that Framework shares.

    This specific issue (AWS creds needed for packaging step, when layers are involved) is caused by fact that sls package step, also generates final CloudFormation template, and logic that detects whether layer was updated, links old layer artifact in the CF template if no changes are detected.

    So as long as sls package is responsible for generating the final CF template, it's probably the only way it can work.

    Of course, this design is quite limiting, and we have numerous reports about that. To mitigate that, there's an issue created, which proposes that packaging step cares only for packing artifacts but not for generating of final CF template, as the latter should rather be handled at sls deploy step -> #8499

    The other issue briefly discussed here, related to how we check for changes on deployed artifacts, also has an optimization proposal: #8499 (and that one can be addressed more easily, there's also a PR attempt on that already)

  12. takuya-okamoto-esm commented on Jun 23, 2022

    @takuya-okamoto-esm

    Thanks to describe here abount this problem in detail.
    Today, I hit this problem in our project, and this Issue was so helpful !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug/designcat/deploymentcat/packaging

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions