0

I am getting the below error while executing a shell script: (Bash)

An error occurred (InvalidID) when calling the CreateTags operation: The ID ‘{‘ is not valid”

so when I look in to the shell script there are two lines of the script which is causing the problem, what i find is the output of Line 1 is used as a input of Line 2 (--resource $remote_snapshot_id) in my case:

Line 1:

remote_snapshot_id=$(aws ec2 copy-snapshot --region us-east-1 --source-region $region --source-snapshot-id $snapshot_id --description $snapshot_id)

Line 2:

aws ec2 create-tags --region us-east-1 --resource $remote_snapshot_id --tags Key=CreatedBy,Value=AutomatedBackup

When I try to execute Line 1, as a single command in Linux Terminal:

aws --region us-east-1 ec2 copy-snapshot --source-region us-west-1 --source-snapshot-id snap-00220030300040 --description "Automated_Backup_425"

Output:

{
    "SnapshotId": "snap-00880090900090"
}

But the Line 2 only require the value snap-00880090900090 from Line 1 Output. (as it is currently picking entire out put starting from "{ it is giving such error as it only require snap-00880090900090)

So my question is how can i grep snap-00880090900090 & store that output to feed for Line 2 (--resource $remote_snapshot_id)

can any one help to fix this please?

2

How can I grep snap-00880090900090 [from { "SnapshotId": "snap-00880090900090" }]?

Since the format you intend to extract from is JSON, this is best accomplished using JSON-aware tools. I would recommend jq if you can get it installed:

command | jq -r .SnapshotId

If command outputs the JSON snippet you mentioned, then the jq command will output just snap-00880090900090 (without quotes, or "raw", thanks to option -r).

If you cannot install a proper JSON-aware tool, can live with a more fragile solution, and know that the snaphot ID will always have the form shown in your example ("snap-" followed by a sequence of digits), then you can extract it like this, using GNU grep:

command | grep -o 'snap-[0-9]\+'
  • Thanks @dhag jq did the trick for me, also out of curiosity i am asking as i see GNU grep is also useful but in my case the "snap-" is not followed only by digit it will be alpha numeric (ex: it will be like "snap-091u9a956mdd426h4") so the GNU grep syntax will be command | grep -o 'snap-[0-9][a-z]\+ ? is that correct. Thanks once again for the jq command – Subash Feb 9 '17 at 7:27
  • Close; you would have to specify digits and letters in the same range, e.g. snap-[0-9a-z]\+. – dhag Feb 9 '17 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.