2017-03-16 102 views
0

试图制作一个可重复使用的函数,最多可以使用4个参数(尽管解决方案应该是任意的)。我想zip这些与AWS CloudFormation参数,如果我没有通过位置参数update_stack它不会包含在CF_ARGS处理可选的函数参数

## 
# Update the stack with the given template 
# @param: stack_name 
# @param: template_body 
# @param: [tags] 
# @param: [parameters] 
## 
update_stack() { 
    # Handle optional func parameters 
    CF_PARAMS=("--stack-name" "--template-body" "--tags" "--parameters") 
    # Only include a param if we have a value supplied as an argument. (+1 to ignore script name) 
    CF_ARGS=($(for i in "${!CF_PARAMS[@]}"; do j=$(($i+1)); if [ -n "${!j}" ]; then echo "${CF_PARAMS[$i]} ${!j}"; fi; done)) 

    # Should make the call as "aws cloudformation create-stack --stack-name $1 --template-body $2" 
    # If $3 or $4 are not supplied then it should not add them to CFG_ARGS 
    aws cloudformation create-stack "${CFG_ARGS[@]}" 
} 

我想我已经得到了CF_ARGS建设按预期工作我只是不知道在bash函数调用如何apply参数和我的谷歌技能都未能就如何找到一个解决方案。请帮忙!

谢谢, 亚历克斯

PS。我从awscli得到错误的是(也许是双引号):

usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters] 
To see help text, you can run: 

    aws help 
    aws <command> help 
    aws <command> <subcommand> help 
aws: error: argument --stack-name is required 

EDIT(1):

感谢@Barmar你的第一个解决方案。这让我这个错误:

Unknown options: Description:, Handles, Authentication, &, Access, permissions, Resources:, ##, #, Policies, ##, PolicyDevelopers:, Type:, AWS::IAM::Policy, Properties:, PolicyName:, Developers-cf, #, @todo:, Remove, suffix, PolicyDocument:, Version:, "2012-10-17", Statement:, -, Effect:, Allow, NotAction:, -, iam:*, -, sts:AssumeRole, ... 

的“--template体”的说法是一个多行字符串(YAML文件是精确的),反正是有双引号的每个参数? :/

回答

1

您正在将CF_ARGS设置为单个字符串,而不是数组。你需要在它周围包围另一组括号来获得一个数组。

CF_ARGS=($(for i in "${!CF_PARAMS[@]}"; do j=$(($i+1)); if [ -n "${!j}" ]; then echo "${CF_PARAMS[$i]} ${!j}"; fi; done)) 

,并使其治疗输出的每一行从for环路作为一个参数,你可以设置IFS只包含换行符:

IFS=$'\n' 
CF_ARGS=($(for i in "${!CF_PARAMS[@]}"; do j=$(($i+1)); if [ -n "${!j}" ]; then echo "${CF_PARAMS[$i]} ${!j}"; fi; done)) 
+0

太棒了!谢谢你,我已经遇到了另一个问题。我已经更新了原始问题跟进,有什么建议吗? –

+0

@AlexLatchford我已经为此更新了答案。 – Barmar

+0

我不得不使用'IFS = $“;”'作为多行字符串分裂也太棒了!仍然没有完全工作,但会为下一位打开一个新的问题:) –