AWS CLI:在sts-assume-role之后获取父用户详细信息

时间:2019-04-15 20:17:54

标签: amazon-web-services amazon-ec2

我正在尝试使用Ansible剧本自动进行一些标记。我要完成的一件事情是用创建者的用户名标记资源。问题是sts-assume-role混淆了顶级帐户的用户数据。

# cat ~/.aws/credentials
[default]
aws_secret_access_key = gggggggggggggggggggggggggggggggggg
aws_access_key_id = JJJJJJJJJJJJJJJJJJJJ

[childaccount]
role_arn = arn:aws:iam::0123456789:role/child-acct-admin
source_profile = default

# aws iam get-user
{
    "User": {
        "Arn": "arn:aws:iam::4567891230:user/someuser",
        "UserName": "someuser",
        "UserId": "CCCCCCCCCCCCCCCCC",
        "Path": "/",
        "CreateDate": "2018-01-04T15:21:51Z",
        "PasswordLastUsed": "2019-01-11T15:24:32Z"
    }
}

# aws opsworks --region us-east-1 describe-my-user-profile
{
    "UserProfile": {
        "IamUserArn": "arn:aws:iam::4567891230:user/someuser",
        "Name": "someuser",
        "SshUsername": "someuser"
    }
}

# export AWS_DEFAULT_PROFILE=childaccount
# aws opsworks --region us-east-1 describe-my-user-profile
{
    "UserProfile": {
        "SshUsername": "child-acct-admin-botocore-sess",
        "Name": "child-acct-admin/botocore-session-123456789",
        "IamUserArn": "arn:aws:sts::234567898:assumed-role/child-acct-admin/botocore-session-123456789"
    }
}

# aws iam get-user

An error occurred (ValidationError) when calling the GetUser operation: Must specify userName when calling with non-User credentials

我需要执行一些命令以提供顶级帐户详细信息。我能想到的唯一途径是解析凭据文件,并尝试并使用假定的角色名称映射回加载的配置文件和父配置文件。然后直接传递顶级帐户的密钥(在此示例中为默认值)以提供实际的用户名。它比应有的要复杂得多。

1 个答案:

答案 0 :(得分:0)

我走了很长一段路。此方法假定凭据和子帐户角色在〜/ .aws / credentials文件中定义。用Ansible撰写。

- name: Query AWS role loaded
  shell: aws opsworks --region us-east-1 describe-my-user-profile --query 'UserProfile.Name' | awk -F'["/]' '{print $2}'
  register: role_in_use

- name: Discover AWS profile loaded
  shell: awk '/\[/{prefix=$0; next} $1{print prefix $0}' ~/.aws/credentials | grep role/{{ role_in_use.stdout }} | awk -F'[][]' '{print $2}'
  register: profile_in_use

- name: Find AWS source profile
  shell: awk '/\[/{prefix=$0; next} $1{print prefix $0}' ~/.aws/credentials| grep "\[{{ profile_in_use.stdout }}\]source_profile =" | awk '{print $3}'
  register: src_profile

- name: Set AWS source user
  shell: aws opsworks --region us-east-1 describe-my-user-profile --query 'UserProfile.Name' --profile {{ src_profile.stdout }} | awk -F'["/]' '{print $2}'
  register: src_user

从那里,您可以引用用户名ala:{{src_user.stdout}}