AWS ライブラリを使用して Powershell スクリプトを介して AWS EC2 ubuntu インスタンスに渡そうとする単純な bash スクリプトがあります。
#!/bin/bash
apt-get update
apt-get upgrade
base64 でファイルの内容をエンコードし、EC2 インスタンスを開始するコマンドレットを呼び出す PowerShell スクリプトを次に示します。
$fileContent = Get-Content $UserDataTarget
$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$MasterInstance = New-EC2Instance -ImageId ami-4c7a3924 -MinCount 1 -MaxCount 1 -KeyName AWSKey -SecurityGroups $SecurityGroup -InstanceType "t1.micro" -UserData $fileContentEncoded
これは、クラウドの初期化ログのスニペットです。
Cloud-init v. 0.7.5 running 'modules:final' at Fri, 02 Oct 2015 21:05:24 +0000. Up 33.88 seconds.
/bin/bash: apt-get update apt-get upgrade: No such file or directory
2015-10-02 21:05:24,294 - util.py[WARNING]: Failed running /var/lib/cloud/instance/scripts/part-001 [127]
2015-10-02 21:05:24,298 - cc_scripts_user.py[WARNING]: Failed to run module scripts-user (scripts in /var/lib/cloud/instance/scripts)
2015-10-02 21:05:24,298 - util.py[WARNING]: Running scripts-user (<module 'cloudinit.config.cc_scripts_user' from '/usr/lib/python2.7/dist-packages/cloudinit/config/cc_scripts_user.pyc'>) failed
/var/lib/cloud/instance/scripts/part-001 の ubuntu インスタンスに読み込まれたユーザー データ スクリプトのスニペットを次に示します。
#!/bin/bash apt-get update apt-get upgrade
010 Editor と Cygwin を使用して Windows ファイルを Linux に変換しようとしました。CRLF バイトを LF バイトに置き換えてみました。結果は同じです。bash スクリプト全体が 1 行に圧縮され、すべての改行が削除され、初回起動時にユーザー データ スクリプトの読み込みに失敗します。
更新: 改行変換を行うために使用した両方のコード スニペットを含めました。どちらもピア ソース (SO) から精査されました。何らかの理由で、Linux インスタンスにスクリプトが改行文字なしで表示されます。
スニペット 1
function ConvertTo-LinuxLineEndings($path) {
$oldBytes = [io.file]::ReadAllBytes($path)
if (!$oldBytes.Length) {
return;
}
[byte[]]$newBytes = @()
[byte[]]::Resize([ref]$newBytes, $oldBytes.Length)
$newLength = 0
for ($i = 0; $i -lt $oldBytes.Length - 1; $i++) {
if (($oldBytes[$i] -eq [byte][char]"`r") -and ($oldBytes[$i + 1] -eq [byte][char]"`n")) {
continue;
}
$newBytes[$newLength++] = $oldBytes[$i]
}
$newBytes[$newLength++] = $oldBytes[$oldBytes.Length - 1]
[byte[]]::Resize([ref]$newBytes, $newLength)
[io.file]::WriteAllBytes($path, $newBytes)
}
ConvertTo-LinuxLineEndings($UserDataTarget)
スニペット 2
try{
# get the contents and replace line breaks by U+000A
$contents = [IO.File]::ReadAllText($UserDataSource) -replace "`r`n", "`n"
# create UTF-8 encoding without signature
$utf8 = New-Object System.Text.UTF8Encoding $false
# write the text back
[IO.File]::WriteAllText($UserDataTarget, $contents, $utf8)
}
catch [Exception]
{
echo $_.Exception|format-list -force
}