Home > Net >  Assume role IAM Role from within an SSM command
Assume role IAM Role from within an SSM command

Time:11-02

My use case is from lambda to issue a command to an ec2 that the instance profile role does not have access too. I used SSM to try and assume my target role but I get a very generic error that the configured profile does not exist. However I know the configured profile does exist and I am able to successfully assume the role locally after SSH'ing in.

def lambda_handler(event,context):

    ssm_client = boto3.client('ssm')
    response = ssm_client.send_command(
                InstanceIds=['i-xxxxxxxxx'],
                DocumentName="AWS-RunShellScript",
                Parameters={'commands': ['aws sts assume-role 
--role-arn arn:aws:iam::xxxxxxxxx:role/myrole
--role-session-name "RoleSession1" 
--profile test> assume-role-output.txt' ]} )

    time.sleep(2)
    command_id = response['Command']['CommandId']

    
    output = ssm_client.get_command_invocation(
          CommandId=command_id,
          InstanceId='i-xxxxxxxxxx',
        )
 
    return output

This returns "StandardErrorContent": "\nThe config profile (test) could not be found\nfailed to run commands: exit status 255",

For anyone see's this do not use sts assume role from ssm, rather use the profile as an argument aws s3 ls --profile test

CodePudding user response:

Per the SSM Agent technical reference:

On Linux and macOS [EC2 instances], SSM Agent runs as the root user. Therefore, the environment variables and credentials file that SSM Agent looks for in this process are those of the root user only (/root/.aws/credentials). SSM Agent doesn't look at the environment variables or credentials file of any other user accounts on the instance during the search for credentials.

Your AWS config file containing the test profile was probably added as the ec2-user, or ubuntu on Ubuntu, hence it's not available to the root user.

You could either su ec2-user to the ec2-user or provide the config file to the root user in the appropriate location (probably /root/.aws/).

  • Related