How to set ENV var in Heroku preview app postdeploy script - heroku

I want to set the HOST env var to $HEROKU_APP_NAME.herokuapps.com on a preview app. It doesn't look like I can do this in app.json since this is a computed value.
I was hoping to do it in a "postdeploy" script like this
heroku config:set HOST="`heroku config:get HEROKU_APP_NAME -a neon-dev-pr-520`.herokuapps.com"
but it wants to authenticate me as a Heroku user. Alas, this doesn't work either:
export HOST=$HEROKU_APP_NAME.herokuapps.com
Any suggestions?

Worked out with the assistance of Heroku's awesome support team a few years ago. We needed to set a reflexive environment variable for a middleware (parse-server) to know what to connect to. It's set manually on our Staging and Production apps, but to get it set on our review apps:
My app.json incldues:
"scripts": {
"postdeploy": "bin/bootstrap"
},
...
"env": {
"HEROKU_APP_NAME": {
"required": true
},
"HEROKU_PARENT_APP_NAME": {
"required": true
},
...
bin/bootstrap is:
#!/usr/bin/env bash
echo $HEROKU_APP_NAME
export SERVER_URL=https://$HEROKU_APP_NAME.herokuapp.com/parse
SERVER_URL is available (and correct) in my review apps. It's been 👍no problems since we implemented.

I found this post which suggests that you can use the Heroku PlatformAPI.
In this case as a Rails Rake task which is run as the postdeploy:
desc 'Bootstrap review app'
task bootstrap: ['db:schema:load', 'db:seed'] do
heroku = PlatformAPI.connect_oauth(ENV['HEROKU_API_TOKEN'])
heroku.config_var.update(ENV['HEROKU_APP_NAME'], 'WWW_HOSTNAME' => "#{ENV['HEROKU_APP_NAME']}.herokuapp.com")
end

Take a look at the documentation for review apps https://devcenter.heroku.com/articles/github-integration-review-apps#heroku_app_name-and-heroku_parent_app_name
As long as you declare HEROKU_APP_NAME or HEROKU_PARENT_APP_NAME as required or optional in your app.json file, they will be available for you to use in your postdeploy script so you can just do:
HOST="$HEROKU_APP_NAME.herokuapp.com"

Using python requests within a postdeploy script:
import requests
result = requests.patch(f"https://api.heroku.com/apps/{os.environ.get('HEROKU_APP_NAME')}/config-vars",
data=json.dumps({"YOUR_KEY": "SOME_VALUE"}),
headers={"Content-Type": "application/json",
"Accept": "application/vnd.heroku+json; version=3",
"Authorization": f"Bearer {os.environ.get("HEROKU_API_KEY")}"}
)
Or using curl when logged:
curl -n -X PATCH https://api.heroku.com/apps/$HEROKU_APP_NAME/config-vars \
-d '{
"FOO": "bar",
"BAZ": "qux"
}' \
-H "Content-Type: application/json" \
-H "Accept: application/vnd.heroku+json; version=3"
And when not logged in add the header, where an app token has been generated:
-H "Authorization: Bearer $HEROKU_API_KEY"
https://2.python-requests.org/en/master/user/authentication/#netrc-authentication
https://devcenter.heroku.com/articles/platform-api-reference#curl-examples

Related

How to automate a task on remote server. How can I take value from one response to be added in next command?

I want to transfer old db_backups to some cold storage(Azure blob storage). How can I automate the task to transfer the files when the size reaches some specific limit, all ths should be done on remote server which I access through ssh in terminal.
Also how to read the response from which I can extract access_token and
can use that in my next command to be run automatically.
can anyone give me some example regarding this or any article to read?
How to add curl post request in bash script?
curl -X POST 'https://server.domain.com/v2/jobs/28723316-9373-44ba-9229-7c796f21b099/runs?project_id=aff59748-260a-476e-9578-b4f4a93e7a92' -H 'Content-Type: application/json' -H "Authorization: Bearer $token" -d ''
output is something like this :
{
"keys": [
{
"keyName": "key1",
"value": "FD0o1y8eSPutze",
"permissions": "FULL"
},
{
"keyName": "key2",
"value": "RLQ59xAi8Eg6p8VpIYx",
"permissions": "FULL"
}
]
}
I want to know how the above command will be run in a shell script. I want to take key1 value from the response and echo it.
but right now I am having trouble in adding $token in the bearer authorization.
can anyone tell me the right format for this in shell script.

Spring boot and RAML

I tried to build and run this project
https://github.com/adorsys/raml-springboot-example
I build the project as right click and Maven install.That time raml-springboot-impl.jar is not generating under raml-springboot-impl project.
Do you have any idea about this.
Try to type or copy+paste the following commands in the terminal/bash as shown in the git repos README.md:
(I'll post my example from Mac, you'll probably have to modify it sensibly)
cd to the repo-s root:
cd /Users/username/Documents/RAML/raml-springboot-example
generate the package:
mvn clean package
run project:
java -jar raml-springboot-impl/target/raml-springboot-impl.jar
Create a new Todo:
curl -i -X POST -H 'Content-Type: application/json' -d '{ "task": "Design the API", "priority": 1 }' localhost:8080/api/todos
List all Todos
curl -i -H 'Accept: application/json' localhost:8080/api/todos
Get one Todo by id
curl -i -H 'Accept: application/json' localhost:8080/api/todos/1
If you feel more comfortable if you can see stuff in the browser, you can just paste the last two links in Chrome or whatever you're using ;)
Also, you can try https://www.getpostman.com/ for testing endpoints that accept other than 'GET' requests (like the first one here) ;)

upload zip file to google drive using curl

I am trying to upload a zip file to Google drive account using curl.
The file is uploaded successfully but the filename is not getting updated. It gets uploaded with default filename i.e. "Untitled".
I am using below command.
curl -k -H "Authorization: Bearer cat /tmp/token.txt" -F "metadata={name : 'backup.zip'} --data-binary "#backup.zip" https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart
You can use Drive API v3 to upload the zip file. The modified curl code is as follows.
curl -X POST -L \
-H "Authorization: Bearer `cat /tmp/token.txt`" \
-F "metadata={name : 'backup.zip'};type=application/json;charset=UTF-8" \
-F "file=#backup.zip;type=application/zip" \
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"
In order to use this, please include https://www.googleapis.com/auth/drive in the scope.
The answer above works fine and was the command I used in uploading my file to Google Drive using Curl. However, I didn't understand what scope was and all of the initial setup required to make this command work. Hence, for documentation purposes. I'll give a second answer.
Valid as at the time of writing...
Visit the Credentials page and create a new credential (this is assuming you have created a project). I created credentials for TVs and Limited devices, so the work flow was similar to:
Create credentials > OAuth client ID > Application Type > TVs and Limited Input devices > Named the client > Clicked Create.
After doing this, I was able to copy the Client ID and Client Secret when viewing the newly created credential.
NB: Only the variables with double asterisk from the Curl commands should be replaced.
Next step was to run the Curl command:
curl -d "client_id=**client_id**&scope=**scope**" https://oauth2.googleapis.com/device/code
Scope in this situation can be considered to be the kind of access you intend to have with the credential having the inputted client_id. More about scope from the docs For the use case in focus, which is to upload files, the scope chosen was https://www.googleapis.com/auth/drive.file.
On running the curl command above, you'll get a response similar to:
{ "device_code": "XXXXXXXXXXXXX", "user_code": "ABCD-EFGH",
"expires_in": 1800, "interval": 5, "verification_url":
"https://www.google.com/device" }
Next step is to visit the verification_url in the response in your browser, provide the user_code and accept requests for permissions. You will be presented with a code when all prompts have been followed, this code wasn't required for the remaining steps (but there may be some reasons to use it for other use cases).
Next step is to use the Curl command:
curl -d client_id=**client_id** -d client_secret=**client_secret** -d device_code=**device_code** -d grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code https://accounts.google.com/o/oauth2/token
You will get a response similar to:
{ "access_token": "XXXXXXXXX", "expires_in": 3599,
"refresh_token": "XXXXXXXXX", "scope":
"https://www.googleapis.com/auth/drive.file", "token_type": "Bearer"
}
Now you can use the access token and follow the accepted answer with a Curl command similar to:
curl -X POST -L \
-H "Authorization: Bearer **access_token**" \
-F "metadata={name : 'backup.zip'};type=application/json;charset=UTF-8" \
-F "file=#backup.zip;type=application/zip" \
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"

Kyestone client commands fails when called inside bash script

I am making a small bash script that tries to install keystone and create the initial admin user, tenant, etc..
I tried it with various keystone subcommands and they all fail saying:
Unable to establish connection to httx://10.0.2.100:35357/v2.0/tenants
I tried sourcing the env variables via a file, using export and in last resort even running the command with --os-token and --os-endpoint. Here is the latest version that I used inside the script:
keystone --debug --os-token secret --os-endpoint httx://10.0.2.100:35357/v2.0 tenant-list
The full message with debug is the following:
WARNING: Bypassing authentication using a token & endpoint (authentication credentials are being ignored).
DEBUG:keystoneclient.session:REQ: curl -i -X GET httx://10.0.2.100:35357/v2.0/tenants -H "User-Agent: python-keystoneclient" -H "X-Auth-Token: secret"
INFO:urllib3.connectionpool:Starting new HTTP connection (1): 10.0.2.100
Unable to establish connection to httx://10.0.2.100:35357/v2.0/tenants
But if I ran the same command directly on the bash shell I have no issues. Here is the debug output for it:
keystone --debug --os-token secret --os-endpoint httx://10.0.2.100:35357/v2.0 tenant-list
WARNING: Bypassing authentication using a token & endpoint (authentication credentials are being ignored).
DEBUG:keystoneclient.session:REQ: curl -i -X GET httx://10.0.2.100:35357/v2.0/tenants -H "User-Agent: python-keystoneclient" -H "X-Auth-Token: secret"
INFO:urllib3.connectionpool:Starting new HTTP connection (1): 10.0.2.100
DEBUG:urllib3.connectionpool:Setting read timeout to 600.0
DEBUG:urllib3.connectionpool:"GET /v2.0/tenants HTTP/1.1" 200 256
DEBUG:keystoneclient.session:RESP: [200] {'date': 'Tue, 17 Mar 2015 14:28:20 GMT', 'vary': 'X-Auth-Token', 'content-length': '256', 'content-type': 'application/json', 'x-distribution': 'Ubuntu'}
RESP BODY: {"tenants_links": [], "tenants": [{"description": "Admin Tenant", "enabled": true, "id": "17008f66b9b54ca39654846e0b5e7af2", "name": "admin"}, {"description": "Service Tenant", "enabled": true, "id": "3a6823c10e454f4294aebdfec8b0c5dd", "name": "service"}]}
+----------------------------------+---------+---------+
| id | name | enabled |
+----------------------------------+---------+---------+
| 17008f66b9b54ca39654846e0b5e7af2 | admin | True |
| 3a6823c10e454f4294aebdfec8b0c5dd | service | True |
+----------------------------------+---------+---------+
So it seems that only when the script tries to run the command it fails...
I cannot figure out why...Any help is appreciated.
PS. I had to replace http with httx in order to be able to post as I do not have enough reputation points.
A few hours later... I have finally figured out what is wrong. In my script I first restart the keystone service so that the changes to the "/etc/keystone/keystone.conf" file would be taken into account and I run the keystone commands right after. It seems that it does take some time for keystone to be up before answering my commands. I added "sleep 1" in between the two commands and now it works. Maybe it will be useful to somebody :-)

GitHub issue creation API

I'm trying to create an issue with a GitHub repository:
curl -d '{"title":"my-new-repo","body":"my new issue description"}' https://api.github.com/repos/np98765/BattleKits/issues
This just returns:
{
"message": "Not Found"
}
I'm authenticating like this:
curl -u "user:password" https://api.github.com
What am I doing wrong?
http://developer.github.com/v3/issues/#create-an-issue
You don't seem to call POST in your curl request.
You could at least try (following "REST-esting with cURL"):
curl -X POST -i -d '{"title":"my-new-repo","body":"my new issue description"}' https://api.github.com/repos/np98765/BattleKits/issues
With -i for having a look at the response headers.
Just tried curl -u "$REPORTER":"$TOKEN" https://api.github.com/repos/$OWNER/$REPO/issues -d #$JSON_WITH_ISSUE and it worked.
This uses token authentication and reporter is my user, while owner of the repo is the user to whom I'm reporting the issue.

Resources