Reputation: 711
I want to use aws SSM to do ssm:DescribeInstanceInformation on ec2 instances (i-0691847a77) by assuming an IAM role (iam_ssm_role) which has below policy defined.
both the IAM roles are on same aws account & iam_base_role arn has been added as trusted policy in iam_ssm_role.
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ssm:*",
"ec2:DescribeImages",
"cloudwatch:PutMetricData",
"ec2:DescribeInstances",
"lambda:InvokeFunction",
"ec2:DescribeTags",
"ec2:DescribeVpcs",
"cloudwatch:GetMetricStatistics",
"ec2:DescribeSubnets",
"ec2:DescribeKeyPairs",
"cloudwatch:ListMetrics",
"ec2:DescribeSecurityGroups"
],
"Resource": "*"
}
I am running below code on an ec2 instance with IAM role (iam_base_role)
import boto3
from boto3.session import Session
def assume_role(arn, session_name):
client = boto3.client('sts')
response = client.assume_role(RoleArn=arn, RoleSessionName=session_name)
session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken'])
client = session.client('sts')
account_id = client.get_caller_identity()["Account"]
print(response['AssumedRoleUser']['AssumedRoleId'])
assume_role('arn:aws:iam::000001:role/iam_ssm_role', 'ssm_session')
client = boto3.client('ssm', region_name = 'us-east-1')
ssm_response = client.describe_instance_information(
InstanceInformationFilterList=[
{
'key': 'InstanceIds',
'valueSet': [
'i-0f0099877fgg'
]
}
]
)
print(ssm_response)
I am getting access denied error , the assumed role shows as "iam_ssm_role" but it looks like the SSM is running using iam_base_role not iam_ssm_role
AROAV6BDS6PTVQBU:iam_ssm_role
botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the DescribeInstanceInformation operation: User: arn:aws:sts::000001:assumed-role/iam_base_role/i-0691847a77 is not authorized to perform: ssm:DescribeInstanceInformation on resource: arn:aws:ssm:us-east-1:000001:*
Upvotes: 1
Views: 10598
Reputation: 711
Ok, I found the issue with my previous code , I was not using the assumed iam role's credentials in boto3.client SSM part.
I can now run the code successfully , I am using below code now.
import boto3
boto_sts=boto3.client('sts')
stsresponse = boto_sts.assume_role(
RoleArn="arn:aws:iam::000001:role/iam_ssm_role",
RoleSessionName='newsession'
)
newsession_id = stsresponse["Credentials"]["AccessKeyId"]
newsession_key = stsresponse["Credentials"]["SecretAccessKey"]
newsession_token = stsresponse["Credentials"]["SessionToken"]
client = boto3.client('ssm',
region_name = 'us-east-1',
aws_access_key_id=newsession_id,
aws_secret_access_key=newsession_key,
aws_session_token=newsession_token)
ssm_response = client.describe_instance_information(
InstanceInformationFilterList=[
{
'key': 'InstanceIds',
'valueSet': [
'i-0f0099877fgg'
]
}
]
)
print(ssm_response)
Upvotes: 4