"The security token included in the request is invalid" serverless framework, STS AssumeRole

Viewed 32

I am trying to deploy a lambda function with serverless framework, I want to automatically deploy to multiple accounts in aws, for this I create a bitbucket pipeline where I write the account id and the function will deploy to that account. I use AssumeRole to create temporary credentials. To configure serverless, I only need the access key and secret key, and I have nowhere to put the session token. I've been looking for a solution but I haven't found any so far, if anyone can help me or advise me on a new approach.

hello.py

import boto3
import subprocess

client = boto3.client('organizations',
                    aws_access_key_id="<ACCESS_KEY>",
                    aws_secret_access_key="<SECRET_ACCESS_KEY>")
sts_client = boto3.client('sts',
                        aws_access_key_id="<ACCESS_KEY>",
                        aws_secret_access_key="<SECRET_ACCESS_KEY")
id_account=0000

def set_account():
    account_set=[]
    paginator = client.get_paginator('list_accounts')
    page_iterator = paginator.paginate()
    for page in page_iterator:        
        for acct in page['Accounts']:
            # print("Name"+acct['Name']+"  Id "+ acct['Id'])
            if int(acct['Id'] ) == int(id_account):
                # try:

                assumed_role_object=sts_client.assume_role(
                RoleArn="arn:aws:iam::{}:role/OrganizationAccountAccessRoleNew".format(acct['Id']),
                RoleSessionName="AssumeRoleSession1")

                credentials=assumed_role_object['Credentials']

                bashCommand = "serverless config credentials --provider aws --key {} --secret {}".format(credentials['AccessKeyId'],credentials['SecretAccessKey'])
                process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
                output, error = process.communicate()
                print("1",output)
                print("2",error)

                bashCommands = "sls deploy --stage dev --region eu-west-2 "
                processs = subprocess.Popen(bashCommands.split(), stdout=subprocess.PIPE)
                outputs, errors = processs.communicate()
                print("3",outputs)
                print("4",errors)

bitbucket-pipelines.yml

pipelines:
  branches:
    master:
      - step:
          image: node:12.13.0-alpine
          caches:
            - node
          script:
            - apk add python3
            - apk add --update py3-pip
            - npm install -g serverless
            - pip3 install boto3
            - python3 hello.py

Output pipeline: enter image description here

0 Answers
Related