Serverless: Serverless using AWS profiles only half working

Created on 22 Jun 2017  Β·  72Comments  Β·  Source: serverless/serverless

This is a Bug Report

Description

When using the serverless deploy --aws-profile or using the EXPORT AWS_PROFILE=<profile>; serverless deploy or the AWS_PROFILE=<profile> serverless deploy it only reads from the credentials file, but that should also be reading from the config file like the default aws cli tools does.

For example I have the following two files

~/.aws/config
[default]
aws_access_key_id = <>
aws_secret_access_key = <>

~/.aws/credentials
[profile default]
output = json
region = us-east-1

[profile dev]
role_arn = <cross_account_role>
source_profile = <another_profile>
mfa_serial = <mfa_serial>
region = us-east-1
output = json

If I run serverless deploy --profile dev it will fail with

ServerlessError: AWS provider credentials not found. You can find more info on how to set up provider credentials in our docs here: https://git.io/vXsdd

Then I tried AWS_PROFILE=dev serverless deploy and it failed with the above error

And finally I ran export AWS_PROFILE="dev" && export AWS_REGION=us-east-1 and then ran the serverless deploy and the same error occur.

So reading more in depth the above small link and talking to people on Gitter I moved that dev profile to ~/.aws/config, creating new keys since the previous used a cross account mfa role.

Its my experience using Troposphere and tools that rely on AWS Profiles, they should be looking into all of them and if they have an mfa, request the code about it.

Additional Data

  • Serverless Framework Version you're using: 1.15.3
  • Operating System: Mac OS 10.12.5
  • Stack Trace: Shown above

Workaround

Create an additional profile and store it inside the ~/.aws/config to use and then you can refer to it using --profile

feature help wanted

Most helpful comment

You can use AWS Profiles with Severless, including IAM cross-account role assumption, if you set this environment variable:

export AWS_SDK_LOAD_CONFIG=1

This enables any tool which uses the AWS SDK for Go (e.g. Serverless framework) to use AWS Profiles.

All 72 comments

I am having what I believe is the same issue, though not using MFA. It centers around a profile assuming a role in a different account.

At my company we have a "master" account where our usernames exist and access/secret keys are tied. We have the ability through STS to assume roles in "dev", "qa" and "prod" accounts. This is done easily via the aws cli, by setting up a profile in ~/.aws/config like such:

[profile dev]
role_arn = arn:aws:iam::<account number>:role/<role name>
source_profile = default 
output = json 
region = us-east-1

Then I'm able to do things like aws s3 ls --profile dev and I get a listing of my s3 buckets in the dev account.

However I cannot figure out how to get serverless to respect this. I've tried AWS_PROFILE=dev serverless info and I get AWS provider credentials not found. I've also tried serverless info --aws-profile=dev but then I get Stack with id <my app> does not exist, I assume because this thing hasn't been deployed yet. But that makes me think --aws-profile isn't being respected. I'm on Serverless version 1.17.0

@rob-cng I tried multiple times with those types of accounts and it didn't work. So I presume that serverless doesn't work with assume roles.

@rob-cng thanks for your comment and thanks @enriquemanuel for chiming in πŸ‘!

So I presume that serverless doesn't work with assume roles.

Yes, that's true. It's not supported right now. We use https://github.com/remind101/assume-role to work with assumed roles.

@pmuens assume-role works great!

@pmuens assume-role works great!

Thanks for the feedback @rob-cng πŸ‘. Glad to hear that it resolves the problem!

Maybe there's a chance that we include such a functionality into core because I believe MFA is quite popular in an enterprise context.

That would be awesome, but not only MFA, assuming roles between accounts as well (please? :)).
As @rob-cng we have many accounts with a principal one, and it gets really hard to deploy without dirty hacks using third party tools :(

I tried using the assume-role tool mentioned above and was able to prove that it doesn't work

 $GOPATH/bin/assume-role <ROLE>
export AWS_ACCESS_KEY_ID="REDACTED"
export AWS_SECRET_ACCESS_KEY="REDACTED"
export AWS_SESSION_TOKEN="REDACTED"
export AWS_SECURITY_TOKEN="REDACTED"
export ASSUMED_ROLE="<ROLE>"
# Run this to configure your shell:

serverless deploy -r us-east-2
Serverless: Packaging service...
Serverless: Creating Stack...

  Serverless Error ---------------------------------------

  User: arn:aws:iam::<myusername> is not authorized to perform: cloudformation:CreateStack on resource: arn:aws:cloudformation:us-east-2:<account>:stack/usersCrud-dev/*

As evident the output above has the user trying to execute the action which will obviously not work, tried also using --aws-profile

also tried

$GOPATH/bin/assume-role <ROLE> && serverless deploy -r us-east-2

running serverless 1.22.0

@jrasillo-boa Try this
~~~

$GOPATH/bin/assume-role bash
sls deploy -r us-east-2
~~~

Hi,
You can make it work by using the right declaration style in your ~/.aws/credentials file :

[dev]
role_arn = <cross_account_role>
source_profile = <another_profile>
....

instead of :

[profile dev]
role_arn = <cross_account_role>
source_profile = <another_profile>
....

You can set the deploy setting on your yml file:

provider:
  name: aws
  runtime: nodejs6.10
  profile: profileName

Would seriously like to see assuming a role natively supported. I'd hope that any larger serious AWS user has a multi-account strategy?

@LuisPaGarcia I tried that and it still ignored. I have always used the format @SkxNMDI5 mentions above, but still it assumes I am using the default role. As configured, I have no other issues with this and AWS CLI, so it definitely seems to be a serverless limitation. Pretty much leaves it broken for me.

Ran into this trying to deploy using a cross-account assumed role. Moving the cross-account profile from config to credentials worked for me (with the syntax change noted by @SkxNMDI5 above), and also seems to work for boto/cli.

So while the lack of support for ~/.aws/config is non-standard, at least there seems to be a simple workaround.

@JonFranchi have you tried https://github.com/remind101/assume-role ?

We use it to handle MFA + serverless.

I agree though, we should support this natively.

@DavidWells I did get that working the other day and was able to deploy three lambda functions, so life is good with the workaround.

Sent with GitHawk

+1 this is still a major issue. Going forward, most larger organizations are heavily leveraging assume role, and having proper .aws/config support, and not having to use wrappers (like assume-role, or aws-profile) would be great. Can we get this prioritized?

i thought i had this working in test using the credentials file, however trying to build it out in production i couldn't get it to work again. currently building out with this workaround, but having this working properly would be much nicer.

+1 Subscribing to this.

I couldn't get --aws-profile to function as expected either.

My workaround is to assume an IAM role in a wrapper script: https://github.com/mlafeldt/docker-serverless/commit/fa247d614d43dd9d26bd810c8eebd77033f86932

This is a blocker issue for me as well. Native support for assumed roles is needed.

assume-role works, but this should be baked in to serverless.

You can use AWS Profiles with Severless, including IAM cross-account role assumption, if you set this environment variable:

export AWS_SDK_LOAD_CONFIG=1

This enables any tool which uses the AWS SDK for Go (e.g. Serverless framework) to use AWS Profiles.

@dougireton Could you provide an example for running serverless commands with an assumed AWS role/profile? After exporting the env var you stated, I tried running sls commands with both --profile and --aws-profile flags to no avail.

@funkswing sls deploy --aws-profile dev --stage dev should work, I think.

What error message are you getting?

Can someone confirm that sls is working with an account where mfa is activated ?
I can't even make the most simple project work.

My ~/.aws/credentials contains valid MFA credentials :

[default]
aws_access_key_id = <valid-token>
aws_secret_access_key = <valid-token>
aws_security_token = <valid-token>

\aws sts get-session-token. I don't have any AWS_* env variables set. I know that my tokens are valid because every aws-cli calls are working.

sls deploy --aws-profile default on a vanilla sls create --template aws-nodejs is always failing with this error :

  Serverless Error ---------------------------------------

  ServerlessError: The security token included in the request is invalid.

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information -----------------------------
     OS:                     darwin
     Node Version:           10.1.0
     Serverless Version:     1.27.2

Help ? πŸ’

@Octirke MFA is activated on my account and I'm able to use sls deploy... without any problems without the aws_security_token setting in my ~/.aws/credentials.

@igorkosta Even without aws_security_token I'm still getting the exact same error. Do I have to set some options ? Some env variables are needed ? I'm not using a working serverless version ?

EDIT : Yep ... the correct syntax is aws_session_token, AWS switched from aws_security_token to aws_session_token in 2015 and most tools support the two syntax but sls don't and the error message could be way better like :

You are using aws_security_token in your credentials, we don't support this. Please use aws_session_token instead.

Should I PR something on that to save time for the next poor soul ? Either we give the user a more helpful error message or we just accept aws_security_token as an equivalent to aws_session_token.

@dougireton thank you so much. None of the other solutions worked but yours actually does.

For newcomers to the thread, this means that with you AWS config looking like:

[profile sls]
role_arn = arn:aws:iam::TargetAccount:role/CrossAccountRole
source_profile = iam

[profile iam]
output = json
region = eu-west-1
# this profile is backed by MFA
expiration = 2018-06-20T16:47:39Z

and a working ~/.aws/credentials setup you can do:

export AWS_SDK_LOAD_CONFIG=1
serverless --aws-profile sls deploy

and expect this command to run using the permissions of the role_arn and the right account. Without it, serverless will just mention that it can't find the profile.

The assume_role option did not work out for me (reporting expired token)

does anyone have a solution for this?

I have the following:
`~/.aws/credentials

[name]
aws_access_key_id = <valid key>
aws_secret_access_key = <valid key>

~/.aws/config

[profile name]
region = us-east-1
output = json
source_profile = name
role_arn = arn:aws:iam::xxxxxxx:role/admin
mfa_serial = arn:aws:iam::xxxxxxx:mfa/name

also:
export AWS_SDK_LOAD_CONFIG=1

I'm running:

$ assume-role name
MFA code: XXXXXX
export AWS_ACCESS_KEY_ID="xxx"
export AWS_SECRET_ACCESS_KEY="xxx"
export AWS_SESSION_TOKEN="xxx"
export AWS_SECURITY_TOKEN="xxxxxx"
export ASSUMED_ROLE="name"
# Run this to configure your shell:
# eval $(assume-role name)
$ eval $(assume-role name)
$ sls --aws-profile name deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...

  Serverless Error ---------------------------------------

  ServerlessError: User: arn:aws:iam::xxxxxxx:user/name is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:xxxxxxx:stack/bucket-name/* with an explicit deny

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information -----------------------------
     OS:                     darwin
     Node Version:           8.11.1
     Serverless Version:     1.27.2

Any ideas? this is killing me >.<

When you use assume-role, it fills in AWS_xxx ENV variables, so you do not
need to run sls with --aws-profile

The last command should be sls deploy

Let me know if that works. Been through hell to get it to work but now we
don't have issues anymore, happy to give a hand.

++
Sam

On Tue, Aug 7, 2018 at 1:25 PM AndrΓ©s Mijares notifications@github.com
wrote:

does anyone have a solution for this?

I have the following:
`~/.aws/credentials

[name]
aws_access_key_id =
aws_secret_access_key =

~/.aws/config

[profile name]
region = us-east-1
output = json
source_profile = andy
role_arn = arn:aws:iam::xxxxxxx:role/admin
mfa_serial = arn:aws:iam::xxxxxxx:mfa/name

also:
export AWS_SDK_LOAD_CONFIG=1

I'm running:

$ assume-role name
MFA code: XXXXXXexport AWS_ACCESS_KEY_ID="xxx"export AWS_SECRET_ACCESS_KEY="xxx"export AWS_SESSION_TOKEN="xxx"export AWS_SECURITY_TOKEN="xxxxxx"export ASSUMED_ROLE="name"# Run this to configure your shell:# eval $(assume-role name)
$ eval $(assume-role name)
$ sls --aws-profile name deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...

Serverless Error ---------------------------------------

ServerlessError: User: arn:aws:iam::xxxxxxx:user/name is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:749906055620:stack/bucket-name/* with an explicit deny

Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Issues: forum.serverless.com

Your Environment Information -----------------------------
OS: darwin
Node Version: 8.11.1
Serverless Version: 1.27.2

Any ideas? this is killing me >.<

β€”
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/serverless/serverless/issues/3833#issuecomment-411023823,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ACN4d0O3VpGVj5ptoQHGP-sbKCk1KfWZks5uOXkzgaJpZM4OC159
.

--
SaM'n'Co
R'U Ready? I was BORN ready!

Alternatively of course, is the role admin in account xxxxxxx really an
admin role?

On Tue, Aug 7, 2018 at 2:03 PM Samuel Cozannet samnco@gmail.com wrote:

When you use assume-role, it fills in AWS_xxx ENV variables, so you do not
need to run sls with --aws-profile

The last command should be sls deploy

Let me know if that works. Been through hell to get it to work but now we
don't have issues anymore, happy to give a hand.

++
Sam

On Tue, Aug 7, 2018 at 1:25 PM AndrΓ©s Mijares notifications@github.com
wrote:

does anyone have a solution for this?

I have the following:
`~/.aws/credentials

[name]
aws_access_key_id =
aws_secret_access_key =

~/.aws/config

[profile name]
region = us-east-1
output = json
source_profile = andy
role_arn = arn:aws:iam::xxxxxxx:role/admin
mfa_serial = arn:aws:iam::xxxxxxx:mfa/name

also:
export AWS_SDK_LOAD_CONFIG=1

I'm running:

$ assume-role name
MFA code: XXXXXXexport AWS_ACCESS_KEY_ID="xxx"export AWS_SECRET_ACCESS_KEY="xxx"export AWS_SESSION_TOKEN="xxx"export AWS_SECURITY_TOKEN="xxxxxx"export ASSUMED_ROLE="name"# Run this to configure your shell:# eval $(assume-role name)
$ eval $(assume-role name)
$ sls --aws-profile name deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...

Serverless Error ---------------------------------------

ServerlessError: User: arn:aws:iam::xxxxxxx:user/name is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:749906055620:stack/bucket-name/* with an explicit deny

Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Issues: forum.serverless.com

Your Environment Information -----------------------------
OS: darwin
Node Version: 8.11.1
Serverless Version: 1.27.2

Any ideas? this is killing me >.<

β€”
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/serverless/serverless/issues/3833#issuecomment-411023823,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ACN4d0O3VpGVj5ptoQHGP-sbKCk1KfWZks5uOXkzgaJpZM4OC159
.

--
SaM'n'Co
R'U Ready? I was BORN ready!

--
SaM'n'Co
"If you wait until you're ready, you'll be waiting the rest of your life"

@SaMnCo yeah, in fact theaws cli works perfect outside serverless.

I also tried again run assume-role profileName and then deploy sls still the same error :(

OK. I was asking as in my case the (equivalent of your) admin role is owned
by another team, and I have to request permissions.

so

aws --profile name cloudformation describe-stacks --stack-name bucket-name

might have failed.

Anyway, in my case I wanted to understand exactly what the various roles
and users were doing, so I split my users as:

  • iam is the main user in the IAM account
  • gc-iam (for Get Credentials IAM) is the MFA user in the IAM account. It
    only exists to relay the MFA information. and can be combined with the IAM
    user. Consider it just for the sake of clarity.
  • np is my non production user
  • p is my production user

My ~/.aws/config looks like:

[default]
output = json
region = eu-west-1

[profile gc-iam]
mfa_serial=arn:aws:iam::IamAccount:mfa/MyUser
get_session_token_duration_seconds=86400

[profile iam]
output = json
region = eu-west-1

[profile np]
role_arn =
arn:aws:iam::NonProductionAccount:role/CrossAccountAdministratorAccess
source_profile = iam
output = json
region = eu-west-1

[profile p]
role_arn = arn:aws:iam::ProdAccount:role/CrossAccountAdministratorAccess
source_profile = iam
output = json
region = eu-west-1

Now my ~/.aws/credentials is like:

[default]
aws_access_key_id = Foo
aws_secret_access_key = Bar

[gc-iam]
aws_access_key_id = Baz
aws_secret_access_key = Boo

Note that I intentionally let a default profile in both config and
credentials, as the framework sometimes fails when it is not there. So I
keep a dummy default profile for the sake of having one.

So now, would unset all my AWS ENV variables and reset them for a given
profile

unset AWS_SESSION_TOKEN AWS_SECRET_ACCESS_KEY AWS_ACCESS_KEY_ID
AWS_SECURITY_TOKEN
eval $(assume-role np)

From now on,

sls deploy

would work.

In order to populate the right settings, I have this script:

#!/bin/bash

# Parameter 1 is the name of the profile that is actually used by the
# holder, and carries the role of the user in a specific account.
MAIN_PROFILE="$1"

# Parameter 2 is the name of the profile that calls the
# session token service.
# It must contain IAM keys and mfa_serial configuration
GET_CREDENTIALS_PROFILE="$2"

# The STS response contains an expiration date/ time.
# This is checked to only set the keys if they are expired.
EXPIRATION=$(aws configure get expiration --profile "${MAIN_PROFILE}")

RELOAD="true"
if [ -n "${EXPIRATION}" ];
then
  # get current time and expiry time in seconds since 1-1-1970
  NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

  # if tokens are set and have not expired yet
  if [[ "${EXPIRATION}" > "$NOW" ]];
  then
    echo "Will not fetch new credentials. They expire at (UTC)
${EXPIRATION}"
    RELOAD="false"
  fi
fi

if [ "${RELOAD}" = "true" ];
then
  echo "Need to fetch new STS credentials"
  MFA_SERIAL=$(aws configure get mfa_serial --profile
"${GET_CREDENTIALS_PROFILE}")
  DURATION=$(aws configure get get_session_token_duration_seconds --profile
"${GET_CREDENTIALS_PROFILE}")
  read -p "Input current token for MFA Device (${MFA_SERIAL}): " TOKEN_CODE

  aws sts get-session-token \
    --profile "${GET_CREDENTIALS_PROFILE}" \
    --output json \
    --serial-number ${MFA_SERIAL} \
    --duration-seconds ${DURATION} \
    --token-code ${TOKEN_CODE} > /tmp/tmpCreds.json

  SECRET_ACCESS_KEY="$(jq --raw-output '.Credentials.SecretAccessKey'
/tmp/tmpCreds.json)"
  SESSION_TOKEN="$(jq --raw-output '.Credentials.SessionToken'
/tmp/tmpCreds.json)"
  EXPIRATION="$(jq --raw-output '.Credentials.Expiration'
/tmp/tmpCreds.json)"
  ACCESS_KEY_ID="$(jq --raw-output '.Credentials.AccessKeyId'
/tmp/tmpCreds.json)"

  aws configure set aws_secret_access_key "${SECRET_ACCESS_KEY}" --profile
"${MAIN_PROFILE}"
  aws configure set aws_session_token "${SESSION_TOKEN}" --profile "${
MAIN_PROFILE}"
  aws configure set aws_access_key_id "${ACCESS_KEY_ID}" --profile "${
MAIN_PROFILE}"
  aws configure set expiration "${EXPIRATION}" --profile "${MAIN_PROFILE}"

Sorry hit ctrl enter too fast.

So using the script fills in the iam * profile with temporary credentials
inherited from my MFA from *gc-iam
.

Let me know if that works for you.

++

On Tue, Aug 7, 2018 at 3:00 PM Samuel Cozannet samnco@gmail.com wrote:

OK. I was asking as in my case the (equivalent of your) admin role is
owned by another team, and I have to request permissions.

so
aws --profile name cloudformation describe-stacks --stack-name bucket-name

might have failed.

Anyway, in my case I wanted to understand exactly what the various roles
and users were doing, so I split my users as:

  • *iam *is the main user in the IAM account
  • *gc-iam *(for Get Credentials IAM) is the MFA user in the IAM account.
    It only exists to relay the MFA information. and can be combined with the
    IAM user. Consider it just for the sake of clarity.
  • np is my non production user
  • *p *is my production user

My ~/.aws/config looks like:

[default]
output = json
region = eu-west-1

[profile gc-iam]
mfa_serial=arn:aws:iam::IamAccount:mfa/MyUser
get_session_token_duration_seconds=86400

[profile iam]
output = json
region = eu-west-1

[profile np]
role_arn =
arn:aws:iam::NonProductionAccount:role/CrossAccountAdministratorAccess
source_profile = iam
output = json
region = eu-west-1

[profile p]
role_arn = arn:aws:iam::ProdAccount:role/CrossAccountAdministratorAccess
source_profile = iam
output = json
region = eu-west-1

Now my ~/.aws/credentials is like:

[default]
aws_access_key_id = Foo
aws_secret_access_key = Bar

[gc-iam]
aws_access_key_id = Baz
aws_secret_access_key = Boo

Note that I intentionally let a default profile in both config and
credentials, as the framework sometimes fails when it is not there. So I
keep a dummy default profile for the sake of having one.

So now, would unset all my AWS ENV variables and reset them for a given
profile

unset AWS_SESSION_TOKEN AWS_SECRET_ACCESS_KEY AWS_ACCESS_KEY_ID
AWS_SECURITY_TOKEN
eval $(assume-role np)

From now on,

sls deploy

would work.

In order to populate the right settings, I have this script:

#!/bin/bash

# Parameter 1 is the name of the profile that is actually used by the
# holder, and carries the role of the user in a specific account.
MAIN_PROFILE="$1"

# Parameter 2 is the name of the profile that calls the
# session token service.
# It must contain IAM keys and mfa_serial configuration
GET_CREDENTIALS_PROFILE="$2"

# The STS response contains an expiration date/ time.
# This is checked to only set the keys if they are expired.
EXPIRATION=$(aws configure get expiration --profile "${MAIN_PROFILE}")

RELOAD="true"
if [ -n "${EXPIRATION}" ];
then
  # get current time and expiry time in seconds since 1-1-1970
  NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

  # if tokens are set and have not expired yet
  if [[ "${EXPIRATION}" > "$NOW" ]];
  then
    echo "Will not fetch new credentials. They expire at (UTC)
${EXPIRATION}"
    RELOAD="false"
  fi
fi

if [ "${RELOAD}" = "true" ];
then
  echo "Need to fetch new STS credentials"
  MFA_SERIAL=$(aws configure get mfa_serial --profile
"${GET_CREDENTIALS_PROFILE}")
  DURATION=$(aws configure get get_session_token_duration_seconds
--profile "${GET_CREDENTIALS_PROFILE}")
  read -p "Input current token for MFA Device (${MFA_SERIAL}): "
TOKEN_CODE

  aws sts get-session-token \
    --profile "${GET_CREDENTIALS_PROFILE}" \
    --output json \
    --serial-number ${MFA_SERIAL} \
    --duration-seconds ${DURATION} \
    --token-code ${TOKEN_CODE} > /tmp/tmpCreds.json

  SECRET_ACCESS_KEY="$(jq --raw-output '.Credentials.SecretAccessKey'
/tmp/tmpCreds.json)"
  SESSION_TOKEN="$(jq --raw-output '.Credentials.SessionToken'
/tmp/tmpCreds.json)"
  EXPIRATION="$(jq --raw-output '.Credentials.Expiration'
/tmp/tmpCreds.json)"
  ACCESS_KEY_ID="$(jq --raw-output '.Credentials.AccessKeyId'
/tmp/tmpCreds.json)"

  aws configure set aws_secret_access_key "${SECRET_ACCESS_KEY}"
--profile "${MAIN_PROFILE}"
  aws configure set aws_session_token "${SESSION_TOKEN}" --profile "${
MAIN_PROFILE}"
  aws configure set aws_access_key_id "${ACCESS_KEY_ID}" --profile "${
MAIN_PROFILE}"
  aws configure set expiration "${EXPIRATION}" --profile "${MAIN_PROFILE}"

On Tue, Aug 7, 2018 at 2:17 PM AndrΓ©s Mijares notifications@github.com
wrote:

@SaMnCo https://github.com/SaMnCo yeah, in fact theaws cli works
perfect outside serverless

β€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/serverless/serverless/issues/3833#issuecomment-411035775,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ACN4dxT1eh2-uEkFuWtxHo5ZtIMC9mNFks5uOYVJgaJpZM4OC159
.

--
SaM'n'Co
R'U Ready? I was BORN ready!

--
SaM'n'Co
R'U Ready? I was BORN ready!

@SaMnCo thank you for detailed explanation, sadly i didnt work but I've found a detail that I'm not sure how to solve.

After I do eval $(assume-role roleName) I get everything I need, a few variables are exported aws_access_key_id, access_key, session_token BUT they are not source, so if I change my bash session or open a new one, variables are not set there, that's ok I can live with it, but when the serverless framework is going to look for the keys, it will go directly to the ~/.aws/credentials file where I set the previous keys (used to authenticated)... this means, if after I assume the role, I copy and paste the new keys to the credentials file it works.

This means the problem is on the way the sls get the creds, give this information, any ideas to help this bro out?

Yes, assume-role exports ENV to the local terminal session, which is why they put the eval in it. If you swap your bash, you will have to run the same function again (so eventually if you have a single role you can add that to your ~/.bashrc as needed).

Sorry the previous comments are a mess, I thought GitHub would interpret the email I sent. Not very nice as is, I can add new answers from the web page if that helps.

Anyway: when you do

$ eval $(assume-role name) $ export AWS_SDK_LOAD_CONFIG=1
you set ENV variables in your session. So when you do

$ sls deploy

it will try to load from the ENV that have been set by assume-role. It is effectively using the role name, with the temporary credentials that have been loaded by assume-role

Now if you run

$ sls deploy --aws-profile name

sls will be using the configuration file, which does NOT have the temporary credentials in it, and it will not try to use the ENV you just set, nullifying the output of assume-role (it would have the same results with or without running assume-role first)

This is why when you copy the ENV to ~/.aws/credentials it does work. You are taking the output of assume-role, and putting them in the file that is loaded by --aws-profile.

Does this clarify the sequence? Can do hangout session if needed (may be faster than long thread)

@SaMnCo dude! thank u a lot for you explanation, I was able to debug it all down, my problem was that I was exporting the AWS_PROFILE variable and somehow it was creating problems, thank u a lot.

That is good knowledge for myself and team as well, thanks for sharing.
I'll add an unset for that one in our makefiles.

I am glad you were able to sort it out, have fun with serverless now :)

On Aug 7, 2018 22:27, "AndrΓ©s Mijares" notifications@github.com wrote:

@SaMnCo https://github.com/SaMnCo dude! thank u a lot for you
explanation, I was able to debug it all down, my problem was that I was
exporting the AWS_PROFILE variable and somehow it was creating problems,
thank u a lot.

β€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/serverless/serverless/issues/3833#issuecomment-411190679,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ACN4d_fGTud6pUIuaJhF0OHPVX5RV7wZks5uOfgqgaJpZM4OC159
.

Hey guys same problem here.

No MFA account though.

my ~/.aws/credentials look like:

[default]
aws_access_key_id = xxxxx
aws_secret_access_key = xxxxx

[staging]
aws_access_key_id = yyyyy
aws_secret_access_key = yyyyy

and then my ~/.aws/config looks like:

[default]
output = json
region = us-east-1

[profile staging]
region = us-east-1

Then I tried the following things:
1)

export AWS_PROFILE='staging'
export AWS_SDK_LOAD_CONFIG=1
sls deploy --stage staging -v

Errors because it tries to use the account id of the default instead of staging.

2) Explicitly exporting the credentials:

export AWS_ACCESS_KEY_ID='xxxxxxxxx'
export AWS_SECRET_ACCESS_KEY='yyyyyyy'
export AWS_PROFILE='staging'
export AWS_SDK_LOAD_CONFIG=1
sls deploy --stage staging -v

3) tried running it like this:
sls deploy --stage staging --aws-profile staging -v
error by saying staging is not found

4) tried removing export AWS_PROFILE

5) tried removing AWS_SDK_LOAD_CONFIG=1

Not sure what to do.

Do I have to use assume-role even though my account is not mfa protected?

Any help will be much appreciated!! πŸ™ πŸ™

@vayias mfa protected and assume roles are related but not the same, are u sure you policy enforce your user to assume a role?

@vayias can you share the output of the sls commands that fail and the result of env?

Thx

@vayias Did you figure it out? I am experiencing the same issue. Simplest case, not working. When trying to deploy with the 2nd profile:

serverless deploy --aws-profile secondprofile

It actually keeps deploying to the _default_ profile and creating the stack there.... πŸ˜•

I have found it more efficient, and "working" to define the profile inside the serverless.yml file
Hopefully this helps a bit

Example:

service: randomMe

frameworkVersion: ">=1.0.0 <2.0.0"

provider:
  name: aws
  runtime: nodejs6.10
  stage: dev
  profile: CustomProfileX
  region: us-east-1
  memorySize: 512

With that, I always found that its super useful to define the region, since things like us-gov-west-1 don't always work without it although they are defined in the .aws/config and .aws/credentials files

I got same issue too, and looked into why this occurs.
aws-sdk-js seems to not load default config path( ~/.aws/config ) automatically except we set AWS_SDK_LOAD_CONFIG=1.
So if you are putting correct config on ~/.aws/config, set AWS_SDK_LOAD_CONFIG=1 solves this issue.

However, it is weird for me to set the variable of aws-sdk for using serverless.
aws-adk loads ~/.aws/config if we pass filepath explicitly, so I suggest that serverless try to pass default config path(~/.aws/config) automatically(if it exists and no other reason that should not be) πŸ€”

If it is good for us, I'll try to create a patch.
Let me hear your opinion.

In my case the aws config file covers a switch role and even using AWS_SDK_LOAD_CONFIG=1 and making this account the _default_ one, I receive an error:

ServerlessError: User: arn:aws:iam::1234567489:user/svc.user-auto is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:1234567489:stack/example/*

Notice that 1234567489 is the same account.

@alexdebrie thanks for responding on Twitter...

Here's my setup:

EC2 instance is running with an instance role in account BAD_ACCOUNT. I want to deploy in account GOOD_ACCOUNT.

$HOME/.aws/config configured with:

[default]
region = us-east-1
output = json
role_arn = ${ROLE_ARN}
external_id = ${EXTERNAL_ID}
credential_source = Ec2InstanceMetadata

Running aws sts get-caller-identity gives me:

{
     "UserId": "ARO_REDACTED:botocore-session-0000",
     "Arn": "arn:aws:sts::GOOD_ACCOUNT:assumed-role/GOOD_ROLE/botocore-session-0000",
     "Account": "GOOD_ACCOUNT"
}

which tells me that the AWS SDK configuration is correct (at least for the CLI) and that there are no permission issues assuming the role from the instance.

The immediate next thing I do is sls deploy, which gives me:

ServerlessError: User: arn:aws:sts::BAD_ACCOUNT:assumed-role/BAD_ROLE/i-0000 is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:BAD_ACCOUNT:stack/REDACTED/*

I have tried using assume-role as described above to assume the role; I've tried creating a non-default profile and referencing it using AWS_PROFILE (sls doesn't like this at all and complains Profile xyzzy does not exist, I think because there is no corresponding entry in .aws/credentials -- at least that's what I'm getting from serverless/lib/plugins/aws/provider/awsProvider.js:86 which is the line that errors out when I try this). AWS_SDK_LOAD_CONFIG does nothing to help that I can see.

My interpretation at this point is that sls is being _very_ clever about trying to understand the intricacies of the AWS SDK config, and that is what's getting in the way.

Your Environment Information -----------------------------
   OS:                     linux
   Node Version:           8.12.0
   Serverless Version:     1.32.0

Thoughts?

@glb This is hacky, but what if you added the following in ~/.aws/credentials:

[default]
aws_access_key_id = 'abc'
aws_secret_access_key = 'def'

It should just skip over those creds and get some by calling AssumeRole, but it looks like it'll barf if there's not an entry there, which is frustrating.

@alexdebrie thanks for the suggestion, trying now... I'll try both with the default profile in ~/.aws/config and then with a profile if that doesn't work.

Trying with default profile: failed: ServerlessError: The security token included in the request is invalid.

~/.aws/config:

[default]
region = us-east-1
output = json
role_arn = ${ROLE_ARN}
external_id = ${EXTERNAL_ID}
credential_source = Ec2InstanceMetadata

~/.aws/credentials:

[default]
aws_access_key_id = FAKE
aws_secret_access_key = FAKE

Transcript:
16:13:03 + export AWS_SDK_LOAD_CONFIG=1 16:13:03 + aws sts get-caller-identity 16:13:04 { 16:13:04 "UserId": "ARO_REDACTED:botocore-session-0000", 16:13:04 "Account": "GOOD_ACCOUNT", 16:13:04 "Arn": "arn:aws:sts:: GOOD_ACCOUNT:assumed-role/REDACTED/botocore-session-0000" 16:13:04 } 16:13:04 + SLS_DEBUG=* sls deploy 16:13:04 Serverless: Load command config 16:13:04 Serverless: Load command config:credentials 16:13:04 Serverless: Load command create 16:13:04 Serverless: Load command install 16:13:04 Serverless: Load command package 16:13:04 Serverless: Load command deploy 16:13:04 Serverless: Load command deploy:function 16:13:04 Serverless: Load command deploy:list 16:13:04 Serverless: Load command deploy:list:functions 16:13:04 Serverless: Load command invoke 16:13:04 Serverless: Load command invoke:local 16:13:04 Serverless: Load command info 16:13:04 Serverless: Load command logs 16:13:04 Serverless: Load command login 16:13:04 Serverless: Load command logout 16:13:05 Serverless: Load command metrics 16:13:05 Serverless: Load command print 16:13:05 Serverless: Load command remove 16:13:05 Serverless: Load command rollback 16:13:05 Serverless: Load command rollback:function 16:13:05 Serverless: Load command slstats 16:13:05 Serverless: Load command plugin 16:13:05 Serverless: Load command plugin 16:13:05 Serverless: Load command plugin:install 16:13:05 Serverless: Load command plugin 16:13:05 Serverless: Load command plugin:uninstall 16:13:05 Serverless: Load command plugin 16:13:05 Serverless: Load command plugin:list 16:13:05 Serverless: Load command plugin 16:13:05 Serverless: Load command plugin:search 16:13:05 Serverless: Load command config 16:13:05 Serverless: Load command config:credentials 16:13:05 Serverless: Load command rollback 16:13:05 Serverless: Load command rollback:function 16:13:05 Serverless: Invoke deploy 16:13:05 Serverless: Invoke package 16:13:05 Serverless: Invoke aws:common:validate 16:13:05 Serverless: Invoke aws:common:cleanupTempDir 16:13:05 Serverless: Packaging service... 16:13:05 Serverless: Excluding development dependencies... 16:13:05 Serverless: Invoke aws:package:finalize 16:13:05 Serverless: Invoke aws:common:moveArtifactsToPackage 16:13:05 Serverless: Invoke aws:common:validate 16:13:05 Serverless: Invoke aws:deploy:deploy 16:13:06 16:13:06 Serverless Error --------------------------------------- 16:13:06 16:13:06 ServerlessError: The security token included in the request is invalid. 16:13:06 16:13:06 Stack Trace -------------------------------------------- 16:13:06 16:13:06 ServerlessError: ServerlessError: The security token included in the request is invalid. 16:13:06 at AwsDeploy.BbPromise.bind.then.catch (/usr/local/lib/node_modules/serverless/lib/plugins/aws/deploy/lib/createStack.js:90:15) 16:13:06 From previous event: 16:13:06 at AwsDeploy.createStack (/usr/local/lib/node_modules/serverless/lib/plugins/aws/deploy/lib/createStack.js:81:13) 16:13:06 From previous event: 16:13:06 at Object.aws:deploy:deploy:createStack [as hook] (/usr/local/lib/node_modules/serverless/lib/plugins/aws/deploy/index.js:102:10) 16:13:06 at BbPromise.reduce (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:390:55) 16:13:06 From previous event: 16:13:06 at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:390:22) 16:13:06 at PluginManager.spawn (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:408:17) 16:13:06 at AwsDeploy.BbPromise.bind.then (/usr/local/lib/node_modules/serverless/lib/plugins/aws/deploy/index.js:95:48) 16:13:06 From previous event: 16:13:06 at Object.deploy:deploy [as hook] (/usr/local/lib/node_modules/serverless/lib/plugins/aws/deploy/index.js:91:10) 16:13:06 at BbPromise.reduce (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:390:55) 16:13:06 From previous event: 16:13:06 at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:390:22) 16:13:06 at PluginManager.run (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:421:17) 16:13:06 at variables.populateService.then.then (/usr/local/lib/node_modules/serverless/lib/Serverless.js:157:33) 16:13:06 at runCallback (timers.js:810:20) 16:13:06 at tryOnImmediate (timers.js:768:5) 16:13:06 at processImmediate [as _immediateCallback] (timers.js:745:5) 16:13:06 From previous event: 16:13:06 at Serverless.run (/usr/local/lib/node_modules/serverless/lib/Serverless.js:144:8) 16:13:06 at serverless.init.then (/usr/local/lib/node_modules/serverless/bin/serverless:43:50) 16:13:06 at <anonymous>

Same error when I use a profile and a hardcoded fake key.

My hypothesis at this point: the AWS provider in serverless is pulling the credentials from the ~/.aws/credentials file and trying to use them.

In this case the AWS provider should not be trying to do all this work to read the SDK config and replicate the functionality; it should let the SDK do its thing. I _may_ be able to figure out how to hack out the misbehaving code, but someone familiar with the code would likely be able to do it a lot faster and with fewer negative side effects.

@glb Yep, I agree with you that it should just follow the SDK default behavior. I'm worried that it would be a breaking change at this point. We'd need to do a deeper look to be sure.

One additional idea -- can you set the AWS_SHARED_CREDENTIALS_FILE before running?

export AWS_SHARED_CREDENTIALS_FILE=$HOME/.aws/config

@alexdebrie sure ... my interpretation of AWS_SHARED_CREDENTIALS_FILE is that it should point to ~/.aws/credentials but I guess that's why you want to try changing it?

Trying now...

No go:

ServerlessError: User: arn:aws:sts::BAD_ACCOUNT:assumed-role/BAD_ROLE/i-REDACTED is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:us-east-1:BAD_ACCOUNT:stack/REDACTED/*

~/.aws/config:

[default]
region = us-east-1
output = json
role_arn = ${ROLE_ARN}
external_id = ${EXTERNAL_ID}
credential_source = Ec2InstanceMetadata
export AWS_SDK_LOAD_CONFIG=1
export AWS_SHARED_CREDENTIALS_FILE=$HOME/.aws/config
SLS_DEBUG='*' sls deploy

(and yes, aws sts get-caller-identity still shows that it's getting the correct role)

@glb Damn, I'm out of good ideas.

Your best option is likely to use the assume-role CLI tool to set credentials from your assumed role into your environment. Not great though.

@alexdebrie sadly, I tried assume-role and it completely failed to take effect.

assume-role myrole sls deploy still showed the EC2 instance role. I fell out of my chair in disbelief.

Thanks for trying. πŸ‘

My approach to breaking changes ("fixing changes" in this instance? πŸ˜„) would be to wrap the new behaviour in a parameter / setting that defaults to off, advertise that change is coming, then take advantage of a major version when it comes to make the breaking change.

However, I'm not sure that fixing this would actually be a breaking change ... after all, the current provider code seems to pull credentials out of ~/.aws/config and ~/.aws/credentials the same way that the SDK does for the limited set of scenarios that it handles; it's just not able to handle all of the scenarios that the SDK does.

The behaviours that are different are that the current code will also look for AWS_{stage}_* environment variables and will look at the aws-profile setting -- a hypothetical PR for this issue could contemplate copying the values (if present) from the non-standard locations into the standard environment variables and leveraging the standard SDK functionality, and wouldn't break anything. 🀞

I'm about to head out for a few days but will be back to this next Thursday. I _really_ don't want to create keys, but may be forced to if I can't figure out a solution (which may involve the aforementioned patch / PR) quickly.

Not sure if you have tested this so sharing. This is what we use:

unset AWS_SESSION_TOKEN AWS_SECRET_ACCESS_KEY AWS_ACCESS_KEY_ID
AWS_SECURITY_TOKEN
export AWS_SDK_LOAD_CONFIG=1
eval $(assume-role DesiredRole)

the unset command you need to adapt (you might unset AWS*), especially if
you have an AWS_PROFILE or AWS_DEFAULT_PROFILE in there you must remove
absolutely.
the second line is about forcing to use the SDK config
The third to assume the right role

It is the only config that works for us on dev laptops. Not great but it
works...

On Fri, Oct 12, 2018 at 11:08 PM Geoff Baskwill notifications@github.com
wrote:

My approach to breaking changes ("fixing changes" in this instance? πŸ˜„)
would be to wrap the new behaviour in a parameter / setting that defaults
to off, advertise that change is coming, then take advantage of a major
version when it comes to make the breaking change.

However, I'm not sure that fixing this would actually be a breaking change
... after all, the current provider code seems to pull credentials out of
~/.aws/config and ~/.aws/credentials the same way that the SDK does for
the limited set of scenarios that it handles; it's just not able to handle
all of the scenarios that the SDK does.

The behaviours that are different are that the current code will also look
for AWS_{stage}_* environment variables and will look at the aws-profile
setting -- a hypothetical PR for this issue could contemplate copying the
values (if present) from the non-standard locations into the standard
environment variables and leveraging the standard SDK functionality, and
wouldn't break anything. 🀞

β€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/serverless/serverless/issues/3833#issuecomment-429462481,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ACN4dxxhUv7sBF9H_6c5s7TPgb0EhXgmks5ukQSxgaJpZM4OC159
.

--
SaM'n'Co
R'U Ready? I was BORN ready!

Thanks @SaMnCo ... tried that and still got the EC2 instance role when using sls deploy. I used env and aws sts get-caller-identity to confirm that everything should be OK, but for some reason sls is persistently using the instance role.

unset AWS_SESSION_TOKEN AWS_SECRET_ACCESS_KEY AWS_ACCESS_KEY_ID AWS_SECURITY_TOKEN
export AWS_SDK_LOAD_CONFIG=1
eval $(assume-role my-role)
env
aws sts get-caller-identity
SLS_DEBUG='*' sls deploy

PS assume-role my-role sls deploy works beautifully on my dev laptop, it's just not working on my CI machine with an instance role.

@glb The assume-role utility doesn't work for you, because the aws-sdk-go added the support for credential_source a few days ago: https://github.com/aws/aws-sdk-go/pull/2201

The aws-sdk-js is still open for this feature: https://github.com/aws/aws-sdk-js/issues/1916 :(

@EmiiKhaos that's very interesting, thank you! assume-role appears to be setting the environment variables correctly for a session with my new role, it seems like what you're saying is that the JS SDK is silently failing to do the AssumeRole call?

πŸ€” I wonder if there's something I can do here...

The assume-role workaround does work, but it is very tedious for us.

We have an AWS account for federated IAM users, and from there we assume roles in the actual AWS accounts. In addition to that, we have MFA enabled. If we use the workaround prefixed for each command, we would have to enter an MFA code for every command (and as they are one-time only, you have to wait 30 seconds to get another one). Or then we would have to run the assume-role command to export the config as env variables, but it is dangerous to set default credentials when you have several AWS accounts. Now I'm considering to move from Serverless to SAM, or to fix this somehow.

Do note that the AWS CLI tools themselves produce a cache for assumed roles, and store it in ~/.aws/cli/cache.

We use this same cache in our own Python tooling via botocore's credential provider cache:

def create_botocore_session(profile):
    session = botocore.session.get_session()
    session.set_config_variable('profile', profile)
    provider = session.get_component('credential_provider').get_provider('assume-role')
    provider.cache = credentials.JSONFileCache('~/.aws/cli/cache')
    return session

+1. Same here, had to implement an ugly workaround to assume role in order for our CI server to properly reach to our other accounts. aws cli natively works great assuming roles in ec2, it would be highly appreciated if serverless could implement a similar approach.

Hey folks, MFA assume roles stuff with AWS_SDK_LOAD_CONFIG should work on v1.33.1! #5432 is the relevant PR. It worked for my MFA based assume role case. Let me know if it works for y'all.

With v1.33.1, the AWS_SDK_LOAD_CONFIG seems to work, but it does not cache the session token as the sls cli asks for the MFA for every command.

Just to clarify, in ~/.aws/config I have the target profile:

[profile targetprofile]
region = our_region
source_profile=federationprofile
mfa_serial=arn:aws:iam::1234567890:mfa/myfederateduser
role_arn=arn:aws:iam::0987654321:role/RoleToAssumeInTargetAccount

In ~/.aws/credentials I have the access keys of my user in the federation account:

[federationprofile]
aws_access_key_id = AKIAFOO
aws_secret_access_key = foofoosecret

With this setup, I can successfully use e.g. aws s3 ls --profile targetprofile, and it will prompt the MFA and cache the session.

Then, in serverless.yml, I have:

provider:
  name: aws
  profile: targetprofile

If I run sls info, first without any AWS environment variables set, I expectedly get:

Error --------------------------------------------------
Profile targetprofile does not exist

And if I set the environment variables, AWS_SDK_LOAD_CONFIG=true sls info:

Enter MFA code for arn:aws:iam::1234567890:mfa/myfederateduser: 123456

This works, but it is not cached.

Correct. It only caches for the duration of the command (in memory).

Oh, ok. Well in that case I'd say this issue is then still open (as the title remains valid).

If I want to deploy and run a function with sls deploy -f exporter && sls invoke -f exporter, I would then have to enter an MFA code, wait 30 seconds and enter a second MFA code.

thanks @Vilsepi it is working Now as you explain

Hi,
You can make it work by using the right declaration style in your ~/.aws/credentials file :

[dev]
role_arn = <cross_account_role>
source_profile = <another_profile>
....

instead of :

[profile dev]
role_arn = <cross_account_role>
source_profile = <another_profile>
....

That's not the syntax according to the docs.

I ran into similar problem and would like to share my solution here in case it would save someone the time I had to spend on debugging this behaviour.

In my scenario I wanted to deploy Lambda functions cross account with target account defined by stage. Deployment happens from an instance in service account running with IAM role. Normally in a similar case I'd use custom aws credentials file with following format:

[stage]
credential_source = Ec2InstanceMetadata
role_arn = arn:aws:iam::0123456789:role/someRole

And I'd point aws cli to this file by exporting AWS_SHARED_CREDENTIALS_FILE= variable.

However since JS SDK doesn't support credential_source yet I had to find some workaround. Here's a bash snippet I ended up using:

# Use custom credentials file
export AWS_SHARED_CREDENTIALS_FILE="$(pwd)/.credentials"

# Assume deployment role manually
assumed_role_creds=$(aws sts assume-role --role-arn arn:aws:iam::${ACCOUNT_ID}:role/deploy-lambda |  jq -r '.Credentials.AccessKeyId, .Credentials.SecretAccessKey, .Credentials.SessionToken')
IFS=" " readarray -t parts <<< "$assumed_role_creds"

# Populate credentials file with access keys and session token
aws configure set aws_access_key_id "${parts[0]}" --profile deploy-lambda-${STAGE}
aws configure set aws_secret_access_key "${parts[1]}" --profile deploy-lambda-${STAGE}
aws configure set aws_session_token "${parts[2]}" --profile deploy-lambda-${STAGE}

# Define profile (by setting at least region) in ~/.aws/config otherwise serverless won't find it
export AWS_SDK_LOAD_CONFIG=1
aws configure set region ${REGION} --profile deploy-lambda-${STAGE}

# Validate configuration
aws configure list
aws configure list --profile deploy-lambda-${STAGE}

# Deploy Lambda function (stage specific profile defined in serverless.yml)
serverless deploy --stage ${STAGE}

I would highly recommend using aws-vault. It works like a charm by simply run aws-vault exec <profile-name> --sls deploy

You can use AWS Profiles with Severless, including IAM cross-account role assumption, if you set this environment variable:

export AWS_SDK_LOAD_CONFIG=1

This enables any tool which uses the AWS SDK for Go (e.g. Serverless framework) to use AWS Profiles.

This worked brilliantly. I did the following

export AWS_PROFILE=prod
export AWS_SDK_LOAD_CONFIG=1
serverless deploy --stage prod --alias prod

This command asked me to enter MFA and then its successfully deployed

Can anyone summarize the outcome of this issue? I upgraded to serverless 1.52.0 and it still prompts for my MFA code every time I run a serverless command (with AWS_PROFILE as an assume-role profile and AWS_SDK_LOAD_CONFIG=1). It's hard to tell from the comments whether that is the intended behavior.

Was this page helpful?
0 / 5 - 0 ratings