2016-07-08 24 views
0

在廚師,屬性看起來如下:如何把每個數組元素,在雙引號

default['cluster']['ipaddress'] = ["10.211.130.108", "10.211.242.203"] 

在廚師的食譜,我已經把每個數組元素,在雙引號,使用map

json_nodes = node['consul']['cluster']['ipaddress'].map { |s| "#{s.to_s}:8300" } 

bash 'configuring file.json' do 
    code <<-EOH 
    echo #{json_nodes} > "/home/user1/file.json" 
    EOH 
end 

我得到的文件/home/user1/file.json內輸出如下:

[10.211.130.108:8300, 10.211.242.203:8300] 

釷Ë輸出應該有雙引號,如下所示:

["10.211.130.108:8300", "10.211.242.203:8300"] 
+0

輸出是真的如你所描述的,不'「10.211.130.108:8300,10.211.242.203:8300」'? – StephenKing

+0

你如何在廚師「輸出」這個? – StephenKing

+0

我編輯了我的問題。請幫助我。謝謝@StephenKing – meallhour

回答

1

如何:

json_nodes = node['cluster']['ipaddress'].map { |s| "#{s.to_s}:8300" } 

我沒有你的數據,但這裏是從我的控制檯例如:

[3] pry(main)> arr = [1,2,3,4,5] 
=> [1, 2, 3, 4, 5] 
[4] pry(main)> arr.map { |s| "#{s.to_s}:3000" } 
=> ["1:3000", "2:3000", "3:3000", "4:3000", "5:3000"] 

注當我把.join放到最後時,它將它們全部串聯在一個字符串中。

[8] pry(main)> arr.map { |s| "#{s.to_s}:3000" }.join(',') 
=> "1:3000,2:3000,3:3000,4:3000,5:3000" 
+0

我沒有看到雙引號。輸出仍然是'[10.211.130.108:8300,10.211.242.203:8300]' – meallhour

+0

你還在做結尾的.join(',')嗎?如果是這樣,那將把所有元素連接成逗號分隔的字符串。如果你想要數組的元素被雙引號,我的答案應該工作。 – andrunix

+0

它不工作。你能幫我最近發佈的答案 – meallhour

0

此代碼對你在你自己的答案指定的。這有點奇怪,但你正在瞄準的字符串看起來像一個數組聲明。

a = ['10.211.130.108','10.211.242.203'] 
a.map! { |s| "\"#{s}:8300\"" } 
result = "[#{a.join(',')}]" 
puts result 
# Output: ["10.211.130.108:8300","10.211.242.203:8300"] 
+0

我沒有看到雙引號。輸出仍爲'[10.211.130.108:8300,10.211.242.203:8300]' – meallhour

+0

我編輯了我的答案,請再試一次。 – BrunoFacca

+0

通過用'each'替換'map',我仍然沒有得到雙引號。請檢查你的結局。 – meallhour

1

事情變得容易很多,當你使用廚師的方式(並不稱爲bash ..)。你的問題轉化爲在廚師解決它:

file "/home/user1/file.json" do 
    content node['consul']['cluster']['ipaddress'].map { |s| "#{s}:8300" }.to_s 
end 

如果您需要非root所有權和讀權限,看看在owner and mode options of the file resource

-1

我能夠用得到雙引號如下:

json_nodes = node['cluster']['ipaddress'].map { |s| "\"#{s.to_s}:8300\"" } 
+0

當然,但如果你仍然使用'bash'資源,那麼你只是完全錯誤地使用Chef。你不應該這樣做,那麼你不會遇到這個引用問題,因爲你不必逃避bash命令。 – StephenKing

相關問題