Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running command in UserData as a not-root user

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
like image 397
p.magalhaes Avatar asked Aug 22 '26 17:08

p.magalhaes


1 Answers

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'

like image 135
Vikyol Avatar answered Aug 25 '26 14:08

Vikyol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!