Search code examples
linuxamazon-ec2user-data

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

Solution

  • 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'