Невозможно взять на себя роль в AWS через код PythonPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Невозможно взять на себя роль в AWS через код Python

Сообщение Anonymous »

У меня есть требование, когда мне нужно запустить пару виртуальных машин EC2, когда это запрашивается. Я могу использовать AWS CLI, но мне пришлось бы предоставлять код MFA каждый раз, когда я запускаю запрос AWS. >import boto3
from botocore.exceptions import ClientError

MFA_ARN = "arn:aws:iam::6963451289992:mfa/User.Name"
ROLE_ARN = "arn:aws:iam::196354236187:role/high-access"
SESSION_NAME = "EC2StartInstanceSession"

def get_user_session():
"""
Create a boto3 session using the default profile.
"""
try:
session = boto3.Session(profile_name='default')
return session
except Exception as e:
print(f"Error getting user session: {e}")
exit(1)

def assume_role_with_mfa(user_session, region):
"""
Assume a role using MFA and return a new boto3 session with the temporary credentials.
"""
sts_client = user_session.client('sts')
mfa_code = input("Enter MFA code: ")
try:
response = sts_client.assume_role(
RoleArn=ROLE_ARN,
RoleSessionName=SESSION_NAME,
SerialNumber=MFA_ARN,
TokenCode=mfa_code,
DurationSeconds=3600 # 1 hour; adjust as needed
)
credentials = response['Credentials']
print("Assumed credentials:", credentials) # Debug print of temporary credentials

# Create a new session explicitly with the temporary credentials and region
session = boto3.Session(
region_name=region,
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
return session
except ClientError as e:
print(f"Error assuming role: {e}")
exit(1)

def print_assumed_identity(session, region):
"""
Explicitly create an STS client using the temporary credentials and print the assumed identity.
"""
creds = session.get_credentials().get_frozen_credentials()
print("Using temporary credentials:", creds)
sts_client = boto3.client(
'sts',
region_name=region,
aws_access_key_id=creds.access_key,
aws_secret_access_key=creds.secret_key,
aws_session_token=creds.token
)
try:
identity = sts_client.get_caller_identity()
print("Assumed identity:", identity)
except ClientError as e:
print(f"Error getting caller identity: {e}")

def start_ec2_instance(session, instance_id, region):
"""
Start the specified EC2 instance using the provided session.
"""
ec2 = session.client('ec2', region_name=region)
try:
ec2.start_instances(InstanceIds=[instance_id])
print(f"Instance {instance_id} in {region} is starting...")
except ClientError as e:
print(f"Error starting instance {instance_id} in {region}: {e}")

def main():
user_session = get_user_session()
region = input("Enter the AWS Region (e.g., ap-south-1): ") or "us-east-1"
session = assume_role_with_mfa(user_session, region)

# Verify that the assumed credentials are active by printing the identity
print_assumed_identity(session, region)

instance_id = input("Enter the Instance ID: ")
start_ec2_instance(session, instance_id, region)

if __name__ == "__main__":
main()`
< /code>
Но когда я запускаю приведенный выше код, я получаю следующую ошибку < /p>
Запуск ошибок в AP-South-2: произошла ошибка (Authfailure ) При вызове операции «Начальные работы»: AWS не смог подтвердить предоставленные учетные данные.
Если приведенный выше код работает, мой следующий шаг состоял в том, чтобы ввести секретный ключ для AWS MFA в коде и использовать PYOTP, чтобы процесс MFA мог быть автоматизирован. Я бы выполнил код с моей локальной машины, это не должно быть проблемой для хардкодов, это то, что я подумал. AWS CLI Config заключается в следующем < /p>
Вот моя настройка AWS CLI < /p>
[default]
region = us-east-2
output = text
role_arn = arn:aws:iam::6963451289992:user/user.name
mfa_serial = arn:aws:iam::6963451289992:mfa/User.Name
source_profile=default

[profile high-access]
role_arn = arn:aws:iam::196354236187:role/high-access
mfa_serial = arn:aws:iam::6963451289992:mfa/User.Name
source_profile=default
region = us-east-2
< /code>
Если я использую приведенный ниже код, он работает < /p>
import boto3

def get_filtered_instances(regions, instance_types_to_exclude, name_suffix):
instances = []

for region in regions:
try:
# Create a session using your default profile
session = boto3.Session(profile_name='high-access')

# Create an EC2 client for the specified region
ec2_client = session.client('ec2', region_name=region)

# Describe instances
response = ec2_client.describe_instances()

for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_type = instance['InstanceType']
instance_name = 'N/A'

# Check for Name tag
if 'Tags' in instance:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
instance_name = tag['Value']
break

# Apply filters
if instance_type not in instance_types_to_exclude and instance_name.endswith(name_suffix):
instances.append({
'InstanceName': instance_name,
'InstanceType': instance_type,
'Region': region
})

except Exception as e:
print(f"An error occurred in region {region}: {e}")

return instances

def write_instances_to_file(instances, output_file):
with open(output_file, 'w') as file:
for instance in instances:
file.write(f"InstanceName: {instance['InstanceName']}, InstanceType: {instance['InstanceType']}, Region: {instance['Region']}\n")

if __name__ == "__main__":
# Define the regions to check
regions = ['us-east-1', 'us-east-2', 'ca-central-1', 'eu-west-2']

# Define the instance types to exclude
instance_types_to_exclude = ['r5a.large', 't3a.medium']

# Define the name suffix to filter
name_suffix = 'p01'

# Get filtered instances
filtered_instances = get_filtered_instances(regions, instance_types_to_exclude, name_suffix)

# Write the results to a text file
output_file = 'filtered_instances.txt'
write_instances_to_file(filtered_instances, output_file)

print(f"Filtered instances written to {output_file}")
< /code>
В приведенном выше коде я пытаюсь найти экземпляры типа имени и экземпляра, которые не являются r5a.large или t3a.medium. < /p>
Проблема с вышеуказанным кодом заключается в том, что я должен ввести код MFA для каждого региона один раз. Если я хочу выполнять сложные операции и несколько вызовов в EC2, я должен вводить код MFA каждый раз. может полностью пропустить шаг ввода MFA.

Подробнее здесь: https://stackoverflow.com/questions/794 ... ython-code
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • GCP и AWS: облачная функция: невозможно взять на себя роль AWS.
    Anonymous » » в форуме Python
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • GCP и AWS: облачная функция: невозможно взять на себя роль AWS.
    Anonymous » » в форуме Python
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • Невозможно взять на себя роль в AWS через код Python
    Anonymous » » в форуме Python
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous
  • WEB API .net 8, вызывающий AWS aws_signing_helper и aws sts, берут на себя роль в поддержке Linux/Rancher
    Гость » » в форуме Linux
    0 Ответы
    46 Просмотры
    Последнее сообщение Гость
  • Регрессия PyTorch LSTM: взять только последнее выходное значение или взять все выходные значения LSTM?
    Anonymous » » в форуме Python
    0 Ответы
    35 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»