我有一个约200行的shell脚本,想用它引导ec2实例。是否有工具可用于将shell脚本转换为userdata?
我有一个约200行的shell脚本,想用它引导ec2实例。是否有工具可用于将shell脚本转换为userdata?
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)
你需要考虑特殊字符,例如'、*、\等。这对我来说有效,但我不确定是否完全覆盖了每种情况。
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"