TRY AND ERRΦR

気になったこと、勉強したこと、その他雑記など色々メモしていきます。。Sometimes these posts will be written in English.,

Cannot get EC2 hostname from environment variables on CronJob

Assume having some EC2 instances and these have the same CronJob, When CronJobs attempts to put logs into S3 with EC2 hostname to identify which instance had put it, faced above problem and I had little bit struggled against it.
The problem occurred only in case of being run in CronJob, but not in normal script.

For example, python, you can access environment variables HOSTNAME like this.

from os
print(os.environ.get('HOSTNAME', '')) # 'ip-10-0-6-113'

But this script on CronJob cannot access HOSTNAME.

from os
print(os.environ.get('HOSTNAME', 'cannot get hostname')) # 'cannot get hostname' 


CronJobs are generally run in the different shell from one which you logged in. So it hasn't been set almost all environment variables you could access as login user. In the case in which you cannot use environment variables, you should get it with socket api.

from socket import gethostname
print(gethostname()) # 'ip-10-0-6-113'

It worked!