9

Background

I want to automatically configure an EC2 via a build, using the aws cli and ssm.

The (manual) setup for the container looks something like this:

  • Create an EC2
  • Run a shell script as root
  • Run a shell script as a specific user

Question

Is it possible to run a command on an ec2 utilising a tool such as aws ssm send-command specifying the linux user which will execute the command?

Assuming the command is a shell script, would specifying the user inside the script do the same job? e.g using sudo su my_user

1

2 Answers 2

10

I didn't find anything on AWS or boto3 docs that allows for that, but I was able to execute as a different user using the runuser command. In theory, you could do the same thing with a combination of sudo and su commands, but this one is pretty simpler.

For that, you can do as follows:

runuser -l  userNameHere -c '/path/to/command arg1 arg2'

Since send-command executes as root, you don't have any issues.

Note: I thought that send-command uses in some way a session managed by the SSM Session Manager, but I was wrong. I spent a good time configuring SSM Session Manager preferences and tagging IAM resources according to this doc and this one, but send-command always execute as root as far I saw.

Sources:

2
  • Thank you! This also helped me when trying to execute a script via AWS Systems Manager - Run Command, since su - username wasn't allowing me to switch the user from root.
    – Leo Folsom
    Commented Feb 9, 2022 at 19:03
  • 1
    Thank you so much for this, you saved my day. Documentation is so weak. And running command after or with sudo su - username did not work at all, even if I send it in same command separated with ; or as list of command.
    – MohitC
    Commented Dec 7, 2023 at 17:15
1

If you need to run more than one command, this is what I found works best for me is to pass this as the command array where each line is an item in the array:

#!/bin/bash
sudo -Hiu username bash << END
command1 arg1 arg2
command2 arg3 arg4
command3 arg5 arg6
END

Whole command will look something like this:

aws ssm send-command --instance-ids i-xxxx --document-name AWS-RunShellScript --parameters commands='["#!/bin/bash","sudo -Hiu username bash << EOF","command1 arg1 arg2","command2 arg3 arg4","command3 arg5 arg6","END"]'
1
  • your solution saved a hell lot of my rest of the day, I was actually struggling to invoke a remote command on VM running on EC2 from scheduled python lambda function via boto3's ssm.send_command. Your way of sending this commands saved my day :) Many thanks again! +1 to your answer
    – Dhwanit
    Commented Sep 13 at 7:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.