将变量传递给AWS CLI内联JSON

我写了一个脚本在本地堆栈上创建sqs资源。我想将从一个cli命令获得的值传递给下一个命令,但要放在一个内嵌json中。以下是有问题的脚本部分。

arn=$(aws --endpoint-url=http://localhost:4576 sqs get-queue-attributes \
--queue-url http://localhost:4576/my_dead_letter_queue_url \
--query 'Attributes.QueueArn' \
--output text)

aws --endpoint-url=http://localhost:4576 sqs create-queue \
--queue-name my_queue \
--attributes \
'{"RedrivePolicy":"{\"deadLetterTargetarn\":\"$arn\",\"maxReceiveCount\":\"5\"}"}'

因此,我尝试传递“ arn”变量,但cli将其作为字符串并尝试找到URL为“ $ arn”的sqs并失败。我也尝试删除报价。在这种情况下,错误是字符串格式错误。

如果我使用arn值代替那里的arn变量,它将代替arn变量。

有人可以告诉我如何在行内json中传递该变量吗?

感谢您阅读:)

Shahed

jinmingh 回答:将变量传递给AWS CLI内联JSON

这里的问题是您试图在单引号内扩展bash变量。像这样使用单引号通常是将一堆字符串和不可输出的东西作为一个参数传递。如果您不能用双引号代替它们,那么您将不得不使用肮脏的eval骇客,我不建议这样做。

这里是一个例子:

$ arn=foobar
$ echo '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"$arn\",\"maxReceiveCount\":\"5\"}"}'
{"RedrivePolicy":"{\"deadLetterTargetArn\":\"$arn\",\"maxReceiveCount\":\"5\"}"}
$ eval echo '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"$arn\",\"maxReceiveCount\":\"5\"}"}'
{RedrivePolicy:{"deadLetterTargetArn":"foobar","maxReceiveCount":"5"}}

有关更多信息,我建议检查How eval worksExpansion of variables inside single quotes

,

我能够成功执行以下操作,并授予它不处理json的权限(为此,我只是通过sed替换令牌),但是我更新了示例并至少在bash中对其进行了测试,我在做:

#!/bin/bash
export awscmd="aws --region us-east-1 iam"
function setArn() {
  ${awscmd} list-policies --query 'Policies[?PolicyName==`'${1}'`].{ARN:Arn}' --output text
}

arn=$(setArn "some-policy-name")
echo '{"RedrivePolicy":"{"deadLetterTargetArn":"'$arn'","maxReceiveCount":"5"}"}'

$ ./somearntest.sh
{"RedrivePolicy":"{"deadLetterTargetArn":"arn:aws:iam::############:policy/some-policy-name","maxReceiveCount":"5"}"}

请注意使用单个tic来连接字符串之外的输出结果。这是在bash 4中,我删除了转义的\“,因为我认为这是错误添加的; ymmv。

本文链接:https://www.f2er.com/2463044.html

大家都在问