Running command in UserData as a not-root user
Asked Answered
C

2

6

I am trying to install airflow using an EC2 UserData script. I need to run some commands using a not-root user (ec2-user). See the script below:

  UserData:
    Fn::Base64: !Sub |
      #!/bin/bash
      set -xe
      # Install GCC
      yum install -y gcc
      # Install Dependencies
      pip install boto3 awscli markupsafe six


      export AIRFLOW_GPL_UNIDECODE=yes
      export AIRFLOW_HOME=/home/ec2-user/airflow
      pip install apache-airflow[crypto,postgres]


      su - ec2-user
      whoami
      PATH=$PATH:/usr/local/bin
      airflow initdb

I just investigated the log and it seems that the command su - ec2-user is not working a whoami is returning root user.

+ su - ec2-user
Last login: Sat Aug 10 15:59:37 UTC 2019 from ip-10-1-13-234.us-west-2.compute.internal on pts/0
+ whoami
root
Crouch answered 10/8, 2019 at 16:6 Comment(0)
F
18

You can use sudo -u to run a single command as a non-root user.

sudo -u ec2-user whoami

You can also start a subshell if you want to run multiple commands.

sudo -u ec2-user bash -c 'whoami;PATH=$PATH:/usr/local/bin;airflow initdb'

Ferretti answered 10/8, 2019 at 22:25 Comment(0)
D
14

For who is searching how to run user-data as ec2-user, the easiest solution I found was using sudo -u and -i options:

#!/bin/bash
sudo -u ec2-user -i <<'EOF'

cmd1
cmd2
cmd3

EOF
Dombrowski answered 28/3, 2022 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.