#!/usr/bin/env bash
#taken from
#https://duncanlock.net/blog/2022/02/24/templating-json-data-into-variable-bash/
set -ex
# Your printf template string
template='{ "IpPermissions": [ { "IpProtocol": "tcp", "FromPort": 8443, "ToPort": 8443, "IpRanges": [ { "Description": "%s", "CidrIp": "%s" } ] } ] }'
# Variable to store your rendered template JSON string
data=""
#security group id
SGID="sg-9837432894dn"
AWS_PROFILE="dev"
# Some variables to substitute into the template
DESCRIPTION="$(echo $USER allow api call)"
IP_ADDR="$(curl -q http://checkip.amazonaws.com)/32"
# Render the template, substituting the variable values and save the result into $data
printf -v data "$template" "$DESCRIPTION" "$IP_ADDR"
# Print it out
echo "$data"
#execute command with json
aws ec2 authorize-security-group-ingress --group-id ${SGID} --cli-input-json "${data}" --profile ${AWS_PROFILE}