您好,我正在尝试通过传递 ip 文件和名称来引导到多个节点。下面是我的代码
输出:它应该从 ip.txt 文件中获取 ip,并从 name.txt 文件中获取名称
IP=`cat ip.txt`
USER="ubuntu"
KEY="test.pem"
NAME=`cat name.txt`
for ip in $IP; do
knife bootstrap $ip -ssh-port 22 --ssh-user $USER --sudo --i $KEY --no-host-key-verify -N $NAME --run-list "role[webserver]"
done
exit $?
答案1
#!/bin/bash
# Read ip.txt and names.txt into arrays 'ips' and 'names'. This assumes that
# the files have the same number of lines, and that both files are in the
# correct order (i.e. line N of ip.txt corresponds to line N of name.txt),
# so that the indices for both arrays match.
mapfile -t ips < ip.txt
mapfile -t names < name.txt
# Don't use all-caps variable names in your own scripts, they're probably already
# used by other programs. $USER certainly is. Use lowercase variable names.
user="ubuntu"
key="test.pem"
for i in "${!ips[@]}"; do
knife bootstrap "${ips[$i]}" -ssh-port 22 \
--ssh-user "$user" --sudo --i "$key" \
--no-host-key-verify -N "${names[$i]}" --run-list "role[webserver]"
done
注意:mapfile
是bash
内置的。它是 的同义词readarray
。
另请注意:我不在chef
这里运行,所以我不知道您的knife bootstrap
命令是否会执行您想要的操作。我假设语法是正确的并且您已经使用了适当的选项。
答案2
使用现代脚本编写巴什:
ip=$(< ip.txt)
user="ubuntu"
key="test.pem"
name=$(< name.txt)
for i in $ip; do
knife bootstrap $i -ssh-port 22 \
--ssh-user $user --sudo --i $key \
--no-host-key-verify -N $name --run-list "role[webserver]"
done
不确定是什么
"role[webserver]"
如果它是关联数组中的值,那么它应该写为
"${role[webserver]}"
答案3
我实际上试图通过从两个不同的文件传递 $IP 和 $NAME 来获取以下格式的输出
1.1.1.1 网站1
2.2.2.2 网页2
3.3.3.3 网页3