Linux Shell Scritping - 带命令的变量内部变量

时间:2016-08-21 17:03:55

标签: linux shell kubernetes

我正在尝试创建一个脚本来自动完成设置并安装Kubernetes主节点的进程。 我无法弄清楚下面的代码是否有错,目标太简单了,无法设置工作节点信息。

让我分享我的代码段。

function create_worker()
{

  echo "Generate the Kubernetes Worker Keypairs ...";

  WORKER_NUMBER=3
  WORKERS_FQDN=("worker1" "worker2" "worker3")
  WORKERS_IP=("192.168.0.10" "192.168.0.11" "192.168.0.12")
  MASTER_IP=("192.168.0.20")
  K8S_SERVICE_IP=10.3.0.1

  for ((i=0; i <= $WORKER_NUMBER; i++));
  do
     openssl genrsa -out ${WORKERS_FQDN[i]}-worker-key.pem 2048
     WORKER_IP="${WORKERS_IP[i]}" openssl req -new -key "${WORKERS_FQDN[i]}"-worker-key.pem -out "${WORKERS_FQDN[i]}"-worker.csr -subj "/CN="${WORKERS_FQDN[i]}"" -config worker-openssl.cnf
     WORKER_IP="${WORKERS_IP[i]}" openssl x509 -req -in "${WORKERS_FQDN[i]}"-worker.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out "${WORKERS_FQDN[i]}"-worker.pem -days 365 -extensions v3_req -extfile worker-openssl.cnf
    echo ${WORKERS_IP[i]}  ${WORKERS_FQDN[i]}
    sleep 2;
  done

  echo "Done ...";

  create_adminkey

}

这是输出:

+ WORKER_IP=
+ openssl req -new -key -worker-key.pem -out -worker.csr -subj /CN= -config worker-openssl.cnf
Error Loading request extension section v3_req
139752372545168:error:220A4076:X509 V3 routines:a2i_GENERAL_NAME:bad ip address:v3_alt.c:476:value=
139752372545168:error:22098080:X509 V3 routines:X509V3_EXT_nconf:error in extension:v3_conf.c:95:name=subjectAltName, value=@alt_names
+ WORKER_IP=
+ openssl x509 -req -in -worker.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out -worker.pem -days 365 -extensions v3_req -extfile worker-openssl.cnf
Error Loading extension section v3_req
140642872743568:error:220A4076:X509 V3 routines:a2i_GENERAL_NAME:bad ip address:v3_alt.c:476:value=
140642872743568:error:22098080:X509 V3 routines:X509V3_EXT_nconf:error in extension:v3_conf.c:95:name=subjectAltName, value=@alt_names

我无法在其他变量中读取变量的值,并在该变量中执行命令。

所以有任何想法可以帮助我吗?

由于

2 个答案:

答案 0 :(得分:1)

您不会说您是在循环的第一次迭代或最后一次迭代中看到该错误。根据我对shell脚本的看法,我假设后者。

如果我将脚本简化为:

echo "Generate the Kubernetes Worker Keypairs ..."

WORKER_NUMBER=3
WORKERS_FQDN=("worker1" "worker2" "worker3")
WORKERS_IP=("192.168.0.10" "192.168.0.11" "192.168.0.12")
MASTER_IP=("192.168.0.20")
K8S_SERVICE_IP=10.3.0.1

for ((i=0; i <= $WORKER_NUMBER; i++)); do
    echo WORKER_IP="${WORKERS_IP[i]}"
done

echo "Done ...";

我看作输出:

Generate the Kubernetes Worker Keypairs ...
WORKER_IP=192.168.0.10
WORKER_IP=192.168.0.11
WORKER_IP=192.168.0.12
WORKER_IP=
Done ...

最后一次迭代,其中WORKER_IP=没有显示任何值,是由于你的循环中的错误比较。你有:

for ((i=0; i <= $WORKER_NUMBER; i++)); do

这将迭代值0,1,2和3.您的列表只有三个值,即${WORKERS_IP[0]}${WORKERS_IP[2]}。没有${WORKERS_IP[3]}。将你的循环改为:

for ((i=0; i < $WORKER_NUMBER; i++)); do

......事情应该按预期运作。

现在,说到这一点,你可以通过这样做来使事情变得更容易管理:

for WORKER_IP in "${WORKERS_IP[@]}"; do
    echo WORKER_IP="$WORKER_IP"
done

这并不需要跟踪$WORKERS_IP的长度。

答案 1 :(得分:0)

我找到了问题,然后在我的解决方法之后。

ggmap

现在一切正常。

谢谢大家。

亲切的问候,