Luca
Luca

Reputation: 11016

Create file and persist environment variable via Amazon EC2 User Data script

I have a small confusion regarding the userdata that can be made available to an AWS machine during instance creation. So I have a bash script where I am generating a file as follows:

#!/bin/bash
echo "Creating a file" >> /files/test.txt
export MY_VARIABLE=/files/test.txt

Now I pass this script as the userdata variable when using the boto3 ec2 instance creation as:

import boto3
ec2 = s.resource('ec2')

with open('script.sh', r) as file:
    user_data = file.read()
res = ec2.create_instances(... UserData=user_data)

Am I correct in assuming that the file and the environment variable created through the script will be available to the created instance?

Upvotes: 0

Views: 1180

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270224

The User Data script runs as the root user when the instance boots for the first time.

It is likely that there is no /files/ directory on the instance, so the file creation would fail. You should create that directory first.

The EXPORT probably won't work because the script is being run as root, whereas you will normally login as ec2-user. To persist an environment variable for a user, you would need to add it to a profile file.

See: How to permanently set environmental variables

Upvotes: 2

Related Questions