What's the best way to configure the AWS CLI when launching new instances?

I want to build a Docker image in my CI pipeline, and have it pushed to some registry, and then launch some EC2 instances running that image. I am creating some EC2 instances using Terraform with a launch configuration like so:

resource "aws_launch_configuration" "test" { image_id = var.ami_id instance_type = var.ec2_instance_size security_groups = [aws_security_group.test.id] user_data = file("launch.sh") ... } 

with the content of launch.sh being:

#!/bin/bash export AWS_ACCESS_KEY_ID=XXXXXXXXXXXXXXXXXXXXXXXX export AWS_SECRET_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <accountId>.dkr.<region>.amazonaws.com/test sudo docker run -d -p 8080:8080 <some-docker-image> 

Now, I know this is terrible and I shouldn't be doing it.

My question is, what's the best way to achieve the same thing? Baking the secrets into the AMI seems just as bad.

submitted by
---