'Why my role on aws is not correctly assumed?

On AWS I created a role on main account via terraform "My-role-ReadOnly" I am trying to assume this role from another account but if I am checking now command "aws sts get-caller-identity" , it is not correctly assumed, I assume that should be other identity? Please correct me if I'm wrong.

resource "aws_iam_role" "My-role-ReadOnly" {
  name = "My-role-ReadOnly"

   assume_role_policy = <<EOF
  {
   "Version": "2012-10-17",
   "Statement": [
  {
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::<my_not_main_account_id>:root"
  },
  "Action": "sts:AssumeRole",
  "Condition": {}
   }
  ]
  }
  EOF
  }

   data "aws_iam_policy" "ReadOnlyAccess" {
   arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
  }

  resource "aws_iam_policy_attachment" "test-attach" {
  name       = "test-attachment"
  roles      = [aws_iam_role.My-role-ReadOnly.name]
  policy_arn = data.aws_iam_policy.ReadOnlyAccess.arn
  }


 H:\tf>aws sts assume-role --role-arn "arn:aws:iam::<main-account-id>:role/My-role-ReadOnly" --role- 
 session-name AWSCLI-Session
 {
"AssumedRoleUser": {
    "AssumedRoleId": "ARO:AWSCLI-Session",
    "Arn": "arn:aws:sts::<main-account-id>:assumed-role/My-role-ReadOnly/AWSCLI-Session"
},
"Credentials": {
    "SecretAccessKey": "/rV380jxxxxx",
    "SessionToken": "FwoGZXxxxxx",
    "Expiration": "2021-02-01T12:34:28Z",
    "AccessKeyId": "ASxxxxxx"
}
}

H:\tf>aws sts get-caller-identity
{
"Account": "<my_not_main_account_id>",
"UserId": "AIxxxxxxxx",
"Arn": "arn:aws:iam::<my_not_main_account_id>:user/terraform_user"
}


Solution 1:[1]

aws sts assume-role returns temporary credentials for the new role, it does not change the current environment, it does not change who / what you are currently logged in as.
You need to export the retrieved credentials into the environment. You can e.g. do that using jq:

credentials=$(aws sts assume-role --role-arn "$provider_arn" --role-session-name "$provider_session_name" | jq ".Credentials")
export AWS_ACCESS_KEY_ID=$(echo $credentials | jq -r ".AccessKeyId")
export AWS_SECRET_ACCESS_KEY=$(echo $credentials | jq -r ".SecretAccessKey")
export AWS_SESSION_TOKEN=$(echo $credentials | jq -r ".SessionToken")

(the syntax for this depends on your OS / shell) E.g. if you are on Windows use set instead of export.

Only after the credentials are exported will aws sts get-caller-identity return the new identity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1