Convery yaml array to string array

时光总嘲笑我的痴心妄想 提交于 2020-07-22 05:52:11

问题


I have a yq read command as below,

groups=$(yq read  generated/identity-mapping.yaml "iamIdentityMappings.[0].groups")

It reads iamIdentityMappings from below yaml:

iamIdentityMappings:
- groups:
  - Appdeployer
  - Moregroups

It stores group as below,

- Appdeployer
- Moregroups

But I want to store groups as below.(comma separated values)

groups="Appdeployer","Moregroups"

How to do this in bash?


回答1:


yq is just a wrapper for jq, which supports CSV output:

$ groups="$(yq -r '.iamIdentifyMappings[0].groups | @csv' generated/identity-mapping.yaml)"
$ echo "$groups"
"Appdeployer","Moregroups"

The yq invocation in your question just causes an error. Note the fixed version.




回答2:


Use mapfile and format a null delimited list with yq:

mapfile -d '' -t groups < <(
  yq -j '.iamIdentityMappings[0].groups[]+"\u0000"' \
  generated/identity-mapping.yaml
)
typeset -p groups

Output:

declare -a groups=([0]="Appdeployer" [1]="Moregroups")

And now you can fulfill this second part of your question: Construct a command based upon a count variable in bash

# Prepare eksctl's arguments into an array
declare -a eksctl_args=(create iamidentitymapping --cluster "$name" --region "$region" --arn "$rolearn" )

# Read the groups from the yml into an array
mapfile -d '' -t groups < <(
  yq -j '.iamIdentityMappings[0].groups[]+"\u0000"' \
  generated/identity-mapping.yaml
)

# Add arguments per group
for group in "${groups[@]}"; do
  eksctl_args+=(--group "$group")
done

# add username argument
eksctl_args+=(--username "$username")

# call eksctl with its arguments
eksctl "${eksctl_args[@]}"


来源:https://stackoverflow.com/questions/62926327/convery-yaml-array-to-string-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!