我有一个大约200行的shell脚本。我想用它来引导ec2实例。是否有可用于将shell脚本转换为userdata 的工具?
答案 0 :(得分:3)
你可以使用perl(从我的一个Bash脚本中提取):
SOURCE_FILE=$1
perl -p -e 's/\"/\\"/g;' "${SOURCE_FILE}" | # Escape of "
perl -p -e 's/^(.*)$/"\1\\n",/g;' ; # Add a " at the beginning of each lines + Add a " at the end of each lines \n",
echo '""'
# Add "" as the last line of the file (to match the , from the previous line)
答案 1 :(得分:0)
您需要考虑特殊字符,例如',*,\等。这对我有用,但我不确定它是否完整涵盖每个案例。
echo -n '"' ; sed ':again; N; $!b again; s/\\/\\\\/g; s/"/\\"/g; s/\n/\\n/g; s/$/\\n/;' $1 | tr -d '\n' ; echo '"'
这将生成一个长字符串,可以放入" UserData":{" Fn :: Base64":字段。这是一个示例shell脚本:
#!/bin/bash
echo $(date "+%F %R:%S") ":: get metadata"
MD=/etc/profile.d/metadata.sh
echo "# AWS metadata" > $MD
metadata=$(curl -sf http://169.254.169.254/latest/dynamic/instance-identity/document)
echo declare -x metadata=\'$metadata\' >> $MD
echo $(date "+%F %R:%S") ":: yum update"
yum -y update
echo $(date "+%F %R:%S") ":: awscli update"
yum -y install python-pip
rm -rf /tmp/pip-build-root/ ; pip install awscli --upgrade
echo $(date "+%F %R:%S") ":: set a cronjob"
echo '*/15 * * * * ~/bin/cronjob.sh' > /var/spool/cron/root
echo $(date "+%F %R:%S") ":: userdata complete"
转换为CloudFormation:
"#!/bin/bash\n\necho $(date \"+%F %R:%S\") \":: get metadata\"\nMD=/etc/profile.d/metadata.sh\necho \"# AWS metadata\" > $MD\nmetadata=$(curl -sf http://169.254.169.254/latest/dynamic/instance-identity/document)\necho declare -x metadata=\\'$metadata\\' >> $MD\n\necho $(date \"+%F %R:%S\") \":: yum update\"\nyum -y update\n\necho $(date \"+%F %R:%S\") \":: awscli update\"\nyum -y install python-pip\nrm -rf /tmp/pip-build-root/ ; pip install awscli --upgrade\n\necho $(date \"+%F %R:%S\") \":: set a cronjob\"\necho '*/15 * * * * ~/bin/cronjob.sh' > /var/spool/cron/root\n\necho $(date \"+%F %R:%S\") \":: userdata complete\"\n"