shell 如何强制Amazon Elastic Beanstalk get-config在输出为YAML时引用所有字符串

scyqe7ek  于 2023-02-05  发布在  Shell
关注(0)|答案(1)|浏览(123)

我正在导出所有AWS ElasticBeanstalk环境变量,并使用xargs将输出作为命令行参数。

export $(/opt/elasticbeanstalk/bin/get-config --output YAML environment | sed -r 's/: /=/' | xargs)

get-config的YAML输出中的大多数字符串都没有用引号引起来,因此当遇到值中有空格的任何环境变量时,上面的命令片段就会中断,因为export命令使用空格来分隔新键值对的开头。
例如,假设我有一个名为TEST_VARIABLE的环境变量,其值为THIS STRING,则上面的命令将失败,并显示错误:

-bash: export: `THIS STRING': not a valid identifier

本质上,我的问题是,如何让/opt/elasticbeanstalk/bin/get-config --output YAML environment给所有字符串加引号?

insrf1ej

insrf1ej1#

我将使用下面的env.yaml文件作为示例(我不使用AWS BS,所以我不知道是否会有严重的语法差异),下次请提供一个编辑的示例:

环境名称

env1: this the 1st
env2: this the 2nd

在任何情况下,管道到xargs都很难保留引号(因为它们最终会被shell解释,但随后您需要重新引用它们)。
相反,您应该尝试生成等效的(几个)导出行,以便由运行的shell使用,例如source <( output with several export x="..." lines)行(bashzsh以及其他行的有效语法)。
粘贴以下两种可能性:

仅使用sed

下面的解决方案(我选择了单引号),假设没有单引号值。

$ sed -E "s/(.+): (.+)/export \1='\2'/" env.yaml
export env1='this the 1st'
export env2='this the 2nd'
$ source <(sed -E "s/(.+): (.+)/export \1='\2'/" env.yaml)
$ env|egrep ^env
env1=this the 1st
env2=this the 2nd

使用yq

使用https://github.com/kislyuk/yq进行所需的引用,然后使用sed进行:替换:

$ yq '.. style="single"' env.yaml|sed -e 's/^/export /' -e 's/: /=/'
export env1='this the 1st'
export env2='this the 2nd'
$ source <(yq '.. style="single"' env.yaml|sed -e 's/^/export /' -e 's/: /=/')
$ env|egrep ^env
env1=this the 1st
env2=this the 2nd

相关问题