简体   繁体   中英

Assumed role python error is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::xxxxxxxxx

I have executed Python script on the ubuntu terminal on EC2 already and is working well. Now I am running it at the Azure devops pipeline but the assumed role in the python is giving this error: It seems am not getting to write the assumed role in the python script correctly. The role in having trust relationship with the Azure Pipeline role which is already principal. Any help?

Traceback (most recent call last):
  File "/home/ubuntu/azp/_work/1/s/infra/step_function.py", line 16, in <module>
    assumed_role_object = sts_client.assume_role (
  File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/botocore/client.py", line 395, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/botocore/client.py", line 725, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:sts::xxxxxxxxxxxxx:assumed-role/ServiceRoleForsampleAzurePipelines/i-0dabf23 is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::xxxxxxxxxx:assumed-role/sample-Pipeline-Role
##[error]The process '/opt/hostedtoolcache/Python/3.8.12/x64/bin/python' failed with exit code 1

Code: Python script

import os

from datetime import datetime
from typing import Tuple
import time
from time import sleep
import boto3
import json
from botocore.exceptions import ClientError


sts_client = boto3.client('sts')

   
assumed_role_object = sts_client.assume_role (
            RoleArn = 'arn:aws:iam::xxxxxxxxx:assumed-role/sample-Pipeline-Role',
            RoleSessionName = 'sample-Pipeline-Role'   
        )     
iam_client = boto3.client('iam',
                                  aws_access_key_id=assumed_role_object['Credentials']['AccessKeyId'],
                                  aws_secret_access_key=assumed_role_object['Credentials']['SecretAccessKey'],
                                  aws_session_token=assumed_role_object['Credentials']['SessionToken']
                                  )  



sf_client = boto3.client('stepfunctions',  region_name="us-west-2")
sf_output = sf_client.start_execution (
    stateMachineArn = 'arn:aws:states:us-west-2:xxxxxxxx:stateMachine:samplesPipelineOrchestration-LOs7dddd',
    name = 'samplesPipelineOrchestration-LOs7dddd',
    input = json.dumps({})
)

while True:
    time.sleep(15) 

    sf_response = sf_client.describe_execution(executionArn=sf_output['executionArn'])
    step_status = sf_response['status'] 

    print("%s: %s" % ("> Status...", step_status))

    if step_status == 'RUNNING':
        continue
    elif step_status == 'FAILED':
        raise Exception("%s: %s" % ("! ERROR ! Execution FAILED: ", sf_response))
    else: # SUCCEEDED
        break



   
    print(step_status)
    print (f'##vso[task.setvariable variable=step_status]{step_status}')

Code: Pipeline Script:

trigger:
  none

variables:
  - group: aws_creds_sample


pool:
  name: AWS Ubuntu 2004


   
jobs:
  - job: determine_the_stepfunction_status
    steps:

      - task: AWSAssumeRole@1
        displayName: 'Login to AWS'
        inputs:
          RoleArn: 'arn:aws:iam::$(AWS_ACCOUNT_ID):role/sample-Pipeline-Role'
          SessionName: 'sample-Pipeline-Role'
          ConfigureAWSCLIEnvironmentVariables: true
      - task: UsePythonVersion@0
        inputs:
          versionSpec: '3.8'
        
      - script: python -m pip install --upgrade pip boto3 setuptools sqlalchemy snowflake.sqlalchemy
        displayName: 'Install python tools'
 

      - task: PythonScript@0
        env:
          STEP_STATUS: $(step_status)
          
        inputs:
          scriptSource: 'filePath' 
          scriptPath: 'infra/step_function.py'# Required when scriptSource == filePath
          arguments:  --environment  $(ENVIRONMENT)
          failOnStderr: false 

The first cause of this error message is an incorrectly configured 'Trusted relationship' on a role that will be assumed.
You'll get this error when the attached condition in the trusted relationship of having MFA isn't met:

"Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}}

To allow the account (even if it's the same) to assume the role, you must also change the Trust relationship for the role.

  1. In the console, open the role you want to assume.
  2. Select "Trust Relationships" tab
  3. Select "Edit RelationshipShip"
  4. Add a statement for the account you wish to add (typically only the ec2 service in "Trusted 4. Add a statement for the account you wish to add (typically only the ec2 service in "Trusted Entities").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM