简体   繁体   English

如何仅使用 Boto3 创建附加托管策略的 AWS IAM 角色

[英]How to create AWS IAM role attaching managed policy only using Boto3

I am trying to use Boto3 to create a new instance role that will attach a managed policy only.我正在尝试使用 Boto3 创建一个仅附加托管策略的新实例角色。

I have the following:我有以下内容:

Policy Name: my_instance_policy策略名称: my_instance_policy

Policy ARN: arn:aws:iam::123456789012:policy/my_test_policy政策 ARN: arn:aws:iam::123456789012:policy/my_test_policy

I want to create the role called 'my_instance_role' attaching attaching the above policy only.我想创建名为“my_instance_role”的角色,仅附加上述策略。

Boto3 client has the create_role() function like below: Boto3 客户端具有如下create_role()函数:

import boto3
client = boto3.client('iam')
response = client.create_role(
    Path='string',
    RoleName='string',
    AssumeRolePolicyDocument='string',
    Description='string'
)

Here, I do not see an option to use the policy ARN or name.在这里,我没有看到使用策略 ARN 或名称的选项。 My understanding is that AssumeRolePolicyDocument variable needs the JSON formatted policy document converted in to text.我的理解是AssumeRolePolicyDocument变量需要将 JSON 格式的策略文档转换为文本。

Is it possible the way I am looking for?这可能是我正在寻找的方式吗?

You would have to create the role (as you are doing above) and then separately attach the managed policy to the role like this:您必须创建角色(如上所述),然后将托管策略单独附加到角色,如下所示:

response = client.attach_role_policy(
    RoleName='MyRole', PolicyArn='<arn of managed policy>')

I had a similar question in regard to how to supply the AssumeRolePolicyDocument when creating an IAM role with Boto3.在使用 Boto3 创建 IAM 角色时,我对如何提供AssumeRolePolicyDocument有类似的问题。

I used the following code...我使用了以下代码...

assume_role_policy_document = json.dumps({
    "Version": "2012-10-17",
    "Statement": [
        {
        "Effect": "Allow",
        "Principal": {
            "Service": "greengrass.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
        }
    ]
})

create_role_response = self._iam.create_role(
    RoleName = "my-role-name,
    AssumeRolePolicyDocument = assume_role_policy_document
)

Note that the AssumeRolePolicyDocument is about defining the trust relationship and not the actual permissions of the role you are creating.请注意, AssumeRolePolicyDocument是关于定义信任关系,而不是您正在创建的角色的实际权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM