How to run a python script within a bash script
Earlier today I authored a Jenkins Bash script to deploy an AWS Service Catalog. I used aws servicecatalog describe-record --id ID --region REGION
to check the status of the provisioned product after running aws servicecatalog provision-product ...
. Running ProvisionProduct returns a record detail with a JSON object structure including the RecordId
,
{
"RecordDetail": {
"RecordId": "A_RECORD_ID",
// ...
}
}
As I'm not yet a Bash pro, I hacked a quick and dirty python script embedded within the Jenkins bash deploy script to grab the RecordId
and run DescribeRecord. This is what is looks like ->
#!/bin/bash
aws servicecatalog provisionproduct ...... > record_detail.json
cat << EOF > parse_product_record_detail.py
#!/usr/bin/python
import json
with open('./record_detail.json', 'r') as opened_file:
record = json.load(opened_file)
record_id = record['RecordDetail']['RecordId']
with open('record_id.txt', 'w') as opened_file:
opened_file.write(record_id)
EOF
chmod 755 parse_product_record_detail.py
./parse_product_record_detail.py
record_id=$(<record_id.txt)
echo "Record id: ${record_id}"
# "A_RECORD_ID", from the above record_detail.json
aws servicecatalog describe-record --id ${record_id} --region ${best_region_ever}
The echo "Record id: ${record_id}"
command outputs Record id: A_RECORD_ID
, which seems both kinda neat and kinda hacky. More elegant solutions abound, but if the situation allows and you don't feeling like parsing JSON in Bash, this seems a quick, dirty, and effective solution 🤷🏻♂️ ymmv