I am working on deploying a web app I created and in order to automate the deployment of that web application I have been having to pass bash scripts to the EC2 instance. These bash scripts completely configure the instance and download/setup everything it needs.
One thing I wanted to do in these bash scripts is to have the server email me its public ip address at the end of the bash deployment script.
Enter Sed
Sed is a fantastic command line tool that you can use to easily perform various transformations on files (and even piped data that you pipe into it). And so sed
is the perfect tool for this job!
Note that this use case is slightly artificial as I usually already know the public ip address of my EC2 instances because they use elastic ips.
Here is json file that I want to use with aws ses send-email
to email the public ip address of this EC2 instance:
deployment_complete.json
{
"Subject": {
"Data": "Deployment Complate at: IPADDRESS",
"Charset": "UTF-8"
},
"Body": {
"Text": {
"Data": "Deployment is now complete at: IPADDRESS",
"Charset": "UTF-8"
},
"Html": {
"Data": "Deployment is now complete at: IPADDRESS",
"Charset": "UTF-8"
}
}
}
Note that I want to replace IPADDRESS
with the current public ip address.
Luckily, I am already getting the external ip with the following command in the shell script:
current_ip=$(wget -qO- http://ipecho.net/plain ; echo)
Using sed
Now I am going to use sed
to replace every instance of IPADDRESS
with the variable in current_ip
sed -i -e 's/IPADDRESS/'$current_ip'/g' deployment_complete.json
The -i
flag means to edit the file in place.
We need ''
around $current_ip
since we are substituting the value in that variable.
More sed options
-i - edit the file in place
If this example confuses you then here is another sed example:
sed 's/find/replace/' filename
And that is it!
Comments
comments powered by Disqus