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

青春壹個敷衍的年華 提交于 2019-12-18 15:29:45

问题


I'm attempting to call run-instances and pass the resulting instance IDs as the input to create-tags as a one-liner as follows:

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

When attempting this, I get the following:

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

Is something like this possible or does one have to resort to using variables (or some other way I'm not thinking about)?

Additional Background

The motivation for asking this question is that something like this is possible with the AWS Tools for Windows PowerShell; I was hoping to accomplish the same thing with the AWS CLI.

Equivalent PowerShell example:

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

回答1:


It can be done by leveraging xargs {} to capture the instance IDs to feed it into the --resources parameter of create-tags.

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"'

Note that unlike the example in the original question, it's important to wrap the "InstanceId" portion of the --query parameter value in brackets so that if one calls run-instances with --count greater than one, the multiple instance IDs that get returned will be outputted as separate lines instead of being tab-delimited. See http://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html#controlling-output-format



来源:https://stackoverflow.com/questions/38148397/is-there-a-way-to-pipe-the-output-of-one-aws-cli-command-as-the-input-to-another

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