Not able to use IAM role assigned to EC2 instance at startup


I am trying to create an autoscaling group with EC2 instances, I need to completed few tasks as an instance starts up and have created a shell + python3(boto3 script). I need to assign some elastic Ips etc. the instance has an IAM role assigned to it to complete the tasks. I assigned this role while creating the autoscaling group and launch configuration. I add the script as 'user-data' to the instance startup.

I tested the script independently and it works, but unfortunately it doesn't work when the instance is launched and the script is invoked. I get an error "unauthorized" when it tries to run it. Although I can see that the IAM role gets correctly assigned to the instance. I also tried by adding a wait time of about 30 seconds so the role may correctly get assigned to the instance, but that still didn't work.

If I manually invoke the script after logging into the instance, it works. I have tried running the script as both only boto3 and as aws cli commands, I still get unauthorized for both.

Other ways to do it would be that I invoke lambda functions as a target lifecycle hook during startup, but in that case I do not have a way to send the instance id to the function, which I needed for my script.

Not sure what I am doing wrong here. Is there some other way I should invoke the script?

preguntada hace 4 años277 visualizaciones
1 Respuesta

I was able to do this now, turned out the ec2 image I was using had an aws key configured for its root user, which was conflicting with the role assigned to the instance, after removing the configuration of the root user I was successfully able to run my scenario.

respondido hace 4 años

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas