1

I need to automate aws configure, connect to ec2 and runs commands inside EC2 instance using shell scripting.

echo "Do you need to configre AWS configure [y/n]?"
read -r aws_configure


if [ y = $aws_configure ]; then
    echo "######################################"
    echo "             AWS Configure            "
    echo "######################################"
    aws configure
else 
    echo "Skipped AWS Configuration !"
    echo "---------------------------"
fi

echo "######################################"
echo "     Connecting to EC2 Instance       "
echo "######################################"

echo "Which swarm that you need to create [private(a) or public(b)]?"
read -r swarm 

ssh -i ~/Documents/AWS/eu_instance_key.pem ec2-user@<EC2 Instance IP address>
**docker image ls ==> I need to run this command on EC2 instance**

I can connect to EC2 instance by sending ssh request to the instance. But I can't switch EC2 instance to my other commands.

I want to run some commands on EC2 server after connected to the instance using bash script.

I could not find a way to do that and I'm new the shell scripting.

Any help would be appreciated! Thank you.

2 Answers 2

2

If you must use SSH for this, try using aws configure set to configure credentials, region and other properties without reading from standard input and complicating your script. More here https://docs.aws.amazon.com/cli/latest/reference/configure/set.html

Also, instead of setting credentials explicitly, you can associate an IAM Role with your EC2 instance and it will generate and rotate temporary credentials automatically, so you don't need to script around that. More here: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html

Or better yet, use AWS Systems Manager to manage servers and execute scripts. More here: https://docs.aws.amazon.com/systems-manager/latest/userguide/execute-remote-commands.html

Check out this tutorial to get started with that: https://aws.amazon.com/getting-started/tutorials/remotely-run-commands-ec2-instance-systems-manager/

Sign up to request clarification or add additional context in comments.

1 Comment

your answer is very helpful and I will try this way later sure. but I actually need the way to excute commands on EC2 by running bash script.
1

I had to create another bash script for this. when I send the ssh request to EC2 instance to connect and also pass and excute my newly created bash file in locally.

ssh -i $Path_to_PemFile_Private ec2-user@$Private_Instance_IP 'bash -s' < ./private_instance.sh 2> /tmp/Error

so second bash which is private_instance.sh use to run commads which I need to run inside EC2 instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.