有没有一种方法可以将一个 AWS CLI 命令的输出作为输入传递给另一个命令?

Is there a way to pipe the output of one AWS CLI command as the input to another?

我正在尝试调用 运行-instances 并将生成的实例 ID 作为输入传递给 create-tags,如下所示:

aws ec2 run-instances \
    --image-id ami-1234 \
    --output text \
    --query Instances[*].InstanceId | \
aws ec2 create-tags \
    --tags 'Key="foo",Value="bar"'

尝试此操作时,我得到以下信息:

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 --resources is required

这样的事情是可能的还是必须求助于使用变量(或者我没有考虑过的其他方式)?

其他背景

问这个问题的动机是,使用适用于 Windows PowerShell 的 AWS 工具可以实现类似的事情;我希望用 AWS CLI 完成同样的事情。

等效的 PowerShell 示例:

New-EC2Instance -ImageId ami-1234 |
    ForEach-Object Instances |
    ForEach-Object InstanceId |
    New-EC2Tag -Tag @{key='foo';value='bar'}

可以通过利用 xargs -I 捕获实例 ID 将其输入到 create-tags 的 --resources 参数中来完成。

aws ec2 run-instances \
    --image-id ami-1234 \
    --output text \
    --query Instances[*].[InstanceId] | \
xargs -I {} aws ec2 create-tags \
    --resources {} \
    --tags 'Key="foo",Value="bar"'

请注意,与原始问题中的示例不同,重要的是将 --query 参数值的“InstanceId”部分括在括号中,这样如果调用 运行-instances with --count 更大多于一个,返回的多个实例 ID 将作为单独的行输出,而不是用制表符分隔。参见 http://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html#controlling-output-format