【问题标题】:How to Attach IAM role for multiple instances in a one shot如何一次性为多个实例附加 IAM 角色
【发布时间】:2019-01-18 22:10:47
【问题描述】:

我想将我新创建的 IAM 角色附加到我存在的所有 250 个实例上,是否有任何“一次性”方式,因为我不想为所有 250 个实例一个接一个地附加。

谢谢

【问题讨论】:

    标签: amazon-web-services cloud amazon-iam policy


    【解决方案1】:

    在 Daniel 的解决方案的背后,我创建了一些对我有用的更易读的东西

    #!/bin/bash
    
    #### Variables
    region=eu-west-2
    profile_id=<insert_profile_from_/.aws/credentials>
    iam_instance_profile=<insert_IAM_instance_profile>
    instances=$(aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' --profile $profile_id --region $region | awk '{print $1}' | sed 's/[]","[]//g')
    
    assign_instances()
    {
      for instance in $instances; do aws ec2 associate-iam-instance-profile --instance-id $instance --iam-instance-profile Name=$iam_instance_profile --region $region --profile $profile_id; done
    }
    assign_instances
    

    【讨论】:

      【解决方案2】:

      Python 等价物是这样的:

      import boto3
      
      ec2 = boto3.client('ec2', region_name='ap-southeast-2')
      
      instances = ec2.describe_instances()
      
      for reservation in instances['Reservations']:
          for instance in reservation['Instances']:
              response = client.associate_iam_instance_profile(
                  IamInstanceProfile={Name='XYZ'},
                  InstanceId=instance['InstanceId']
              )
      

      (我没测试过!)

      【讨论】:

        【解决方案3】:

        没有一种 API 可以一次将一个实例角色分配给多个实例,但是编写一些可以在命令行中执行此操作的命令应该很容易。如果您更喜欢编程方法,还有适用于大多数语言的 SDK。

        要为您的问题添加一点颜色,您需要创建一个与您的角色相关联的实例配置文件,然后将该实例配置文件附加到您的每个实例,而不是直接的角色。

        https://aws.amazon.com/blogs/security/new-attach-an-aws-iam-role-to-an-existing-amazon-ec2-instance-by-using-the-aws-cli/ 具有执行此操作所需的所有命令,因此您只需遍历列表并为尚未设置正确配置文件的每个实例执行此操作。

        如果您在编程方面需要帮助,您应该自己编写一些代码,将其粘贴到此处,我们可以进一步提供帮助。

        更新:由于您似乎还没有准备好跳入本文的代码末尾,所以我将让您在我最喜欢的临时执行环境 posix shell 中开始:

        iprofile="your-instance-profile-name"
        aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' \
        | xargs -n 1 -P 25 $aws ec2 associate-iam-instance-profile \
          YourInstanceId --iam-instance-profile Name=${iprofile} --instance-id 
        

        这应该列出您的所有实例,然后以 25 个并行组的形式将 $iprofile 与每个实例关联。

        【讨论】:

        • 感谢您的回复,但这不是我问题的确切解决方案,我按照您共享的上述链接进行操作,$aws ec2 associate-iam-instance-profile --instance-id YourInstanceId -- iam-instance-profile Name=YourNewRole-Instance-Profile 这是我需要根据该链接对我的所有 250 个 EC2 实例逐一运行的代码,请您给我任何其他可以将新角色附加到所有人的解决方案我的实例。再次感谢:)
        • @NamanJoshi - 丹的回答是正确的。没有 AWS 功能可以一次将角色附加到多个实例。您需要通过 CLI 编写脚本,或者用 Python(这很简单)或您喜欢的语言编写程序。
        猜你喜欢
        • 2020-09-02
        • 2019-08-23
        • 2018-07-09
        • 2021-11-10
        • 2021-07-24
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        相关资源
        最近更新 更多