我试图通过cron在AWSElasticbean茎(EB)上运行django manage.py
任务。
*/10 * * * * root /usr/local/bin/notification_cron.sh > /dev/null
notification_cron.sh
脚本调用django manage.py
任务。
Django需要EB的环境变量(如RDS_PORT、RDS_DB_NAME、RDS_PASSWORD等)。因此,我将这些环境变量保存到部署时的文件中,并在也调用manage.py任务的bash脚本中重新加载这些变量。
这是我在.ebextensions
中部署配置的一部分。
commands:
001_envvars_to_bash_source_file:
command: |
# source our elastic beanstalk environment variables
/opt/elasticbeanstalk/bin/get-config --output YAML environment|perl -ne "/^\w/ or next; s/: /=/; print qq|\$_|" > /usr/local/bin/envvars
chmod 755 /usr/local/bin/envvars
files:
"/usr/local/bin/notification_cron.sh":
mode: "000755"
owner: root
group: root
content: |
#!/usr/bin/env bash
AWS_CONFIG_FILE="/home/ec2-user/.aws/config"
set -o allexport
# Loading environment data
source /usr/local/bin/envvars
set +o allexport
cd /opt/python/current/app/
source /opt/python/run/venv/bin/activate
python manage.py my_management_task
这个问题是由线路引起的。
/opt/elasticbeanstalk/bin/get-config --output YAML environment|perl -ne "/^\w/ or next; s/: /=/; print qq|\$_|" > /usr/local/bin/envvars
或替换sed等效
/opt/elasticbeanstalk/bin/get-config environment --output yaml | sed -n '1!p' | sed -e 's/^\(.*\): /\1=/g' > /usr/local/bin/envvars
/usr/local/bin/envvars
的内容并不总是在引号中:
PYTHONPATH="/opt/python/current/app/mydjangoapp:$PYTHONPATH"
DJANGO_SETTINGS_MODULE=mydjangoapp.settings
AWS_ACTIVE='true'
RDS_PORT='5432'
RDS_HOSTNAME=hostname.host.us-east-1.rds.amazonaws.com
RDS_USERNAME=master
RDS_DB_NAME=ebdb
RDS_PASSWORD=My&Password
这会在环境变量具有"&“字符的情况下引起麻烦。
'RDS_PASSWORD': My&Password
在调用django的source /usr/local/bin/envvars
之前,Bash将其拆分为"&“字符,然后将它们导入到脚本中。
Phew.我的问题是:
如何在不中断其他行(如RDS_PASSWORD="My&Password"
)的情况下在/usr/local/bin/envvars
文件中获得RDS_PORT='5432'
(注意所需双引号)
发布于 2017-01-12 02:53:09
使用GNU sed
,你可以做如下的事情,
sed -r 's/RDS_PASSWORD=([[:graph:]]+)/RDS_PASSWORD="\1"/' /usr/local/bin/envvars
PYTHONPATH="/opt/python/current/app/mydjangoapp:$PYTHONPATH"
DJANGO_SETTINGS_MODULE=mydjangoapp.settings
AWS_ACTIVE='true'
RDS_PORT='5432'
RDS_HOSTNAME=hostname.host.us-east-1.rds.amazonaws.com
RDS_USERNAME=master
RDS_DB_NAME=ebdb
RDS_PASSWORD="My&Password"
然后,您可以将-i
标志添加到sed
到就地替换。我使用了字符类[[:graph:]]
,它是
‘[:graph:]’
Graphical characters: ‘[:alnum:]’ and ‘[:punct:]’.
作为[:punct:]
的一部分的特殊字符包括
! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
因此,如果上述任何字符构成了sed
变量,则RDS_PASSWORD
可以处理替换。
您可以使用的语法是
/opt/elasticbeanstalk/bin/get-config environment --output yaml | \
sed -n '1!p' | sed -e 's/^\(.*\): /\1=/g' | \
sed -r 's/RDS_PASSWORD=([[:graph:]]+)/RDS_PASSWORD="\1"/' > /usr/local/bin/envvars
https://stackoverflow.com/questions/41610788
复制相似问题