Search code examples
python-3.xboto3aws-iam-policy

How to attach all the EC2 instances with same role programmatically AWS CLI way?


I am trying to tag all the EC2 instances that don't have any role to be attached to an existing role. Is there an AWS CLI for it? So, far I am trying with boto3 with no luck.


Solution

  • import boto3
    
    
    ec2_list = ['instanca_1','instanca_2']
    
    for ec2_instance_id in ec2_list:
        client = boto3.client("ec2")
        response = client.associate_iam_instance_profile(
            IamInstanceProfile={
                 "Arn": "arn:aws:iam::AWS-ACCOUNT:instance-profile/SSMInstanceProfile",
                "Name": "SSMInstanceProfile",
            },
            InstanceId=ec2_instance_id,
        )
    
        print(response)
    

    Above code snippet worked perfectly as per my need. I don't think AWS CLI has looping functionality like for or while.