Search code examples
python-3.xamazon-ec2boto3multi-factor-authentication

Increase aws session token expiration time


I am using a python script that login to AWS account with an IAM user and MFA (multi-factor authentication) enabled. The script runs continuously and does some operations (IoT, fetching data from devices etc etc).

As mentioned, the account needs an MFA code while starting the script, and it does perfectly. But the problem is script fails after 36 hours because the token expires. Can we increase the session token expiration time or automate this task not to ask MFA code again and again?


Solution

  • You can't extend the expiration, but you can circumvent the protections (at your own risk). In principle, you can store the MFA secret used to generate TOTP codes (e.g., what QR setup codes provide) and have your script generate OTP codes to perform MFA challenges automatically. For example, using the PyOTP library. Of course, if your MFA requirements require more than TOTP (like enforced biometrics or physical touch keys) then this won't work.

    But it would probably be easier to just setup a solution that avoids the need for MFA to begin with. For example, deploy your script to run on an EC2 instance with an instance role with necessary permissions or create an IAM user that does not have MFA requirements.