Chintamani
Chintamani

Reputation: 1166

Copy aws secrets manager from one account to another account using aws codepipeline

I created a secret using cloudformation template and keep it inside a variable.

AUTH_AWS_SECRET_DEV=$(aws secretsmanager get-secret-value --region $AWS_DEFAULT_REGION --secret-id "sample_auth_aws_secret" --output text) 

The output of this reference variable I am getting is

arn:aws:secretsmanager:us-east-1:56875858585:secret:sample_auth_aws_secret-yfw3B2 2022-02-23T15:13:14.166000+00:00 sample_auth_aws_secret {"clientId":"sample123","secret":"wjwjwjwjwjwjwjsjsjsj"} a62a2e90-c2dc-4936-82a1-014c72ac62e5 VERSIONSTAGES AWSCURRENT

I need to run aws create secret commands using bash scripts so that it will create the same secrets in aws another account.

The command example as per the aws doc is

aws secretsmanager create-secret \
    --name sample_auth_aws_secret \
    --description "My test secret created with the CLI." \
    --secret-string "{\"clientId\":\"sample123\",\"secret\":\"wjwjwjwjwjwjwjsjsjsj\"}"

How can I take these required values from that reference variable dynamically in bash script?

Upvotes: 1

Views: 1751

Answers (1)

Nick
Nick

Reputation: 199

It can be achieved easily using simple JSON processing. I have used jq to demo it for you. but there are multiple out there which can be cherry-picked for the job.

AWS cli supports multiple output formats, and extracting data from JSON is the most efficient way to tackle the task.

jq is an external package, It will require installing before use. refer to the link on the steps.

Below is the format get-secret-value with output as JSON will follow.

enter image description here

Using jq you can extract the specific key from the JSON string and pass it to the next command.

enter image description here

Note: I have used cat output to be piped for filtering for the demo, but it can be replaced with AWS CLI command to retrieve secret. Example in the final section.


Summing it up

Putting it all together, you get your solution. The --output flag is changed to JSON instead of text. This can be configured in the .credentials file to apply the setting globally.

secretValue=$(aws secretsmanager get-secret-value --region $AWS_DEFAULT_REGION --secret-id "sample_auth_aws_secret" --output json | jq '.SecretString')
secretName=$(aws secretsmanager get-secret-value --region $AWS_DEFAULT_REGION --secret-id "sample_auth_aws_secret" --output json | jq '.Name')

secretsmanager create-secret \
--name $secretName \
--description "My test secret created with the CLI." \
--secret-string $secretValue

Note: I have purposely simplified the script, it can be Optimised. Instead of making two aws call output can be stored in a variable to retrieve multiple keys.

Upvotes: 1

Related Questions