To demonstrate how the ambassador pattern works, we will use The Movie DB (TMBD). Head over to the website and register (it's free) to get an API key.
The Movie DB website offers a REST API where you can get information about the movies. We have implemented an ambassador container that listens on path /movies
, and whenever it receives a request, it will make an authenticated request to the API of The Movie DB.
Here's the snippet from the code of the ambassador container:
func TheMovieDBServer(w http.ResponseWriter, r *http.Request) {
apiKey := os.Getenv("API_KEY")
resp, err := http.Get(fmt.Sprintf("<https://api.themoviedb.org/3/discover/movie?api_key=%s>", apiKey))
// ...
// Return the response
}
We will read the API_KEY
environment variable and then make a GET request to the URL. Note if you try to request to URL without the API key, you'll get the following error:
$ curl <https://api.themoviedb.org/3/discover/movie>
{"status_code":7,"status_message":"Invalid API key: You must be granted a valid key.","success":false}
Before we can create the Pod, we need to create a Secret with the API key. Let's do that first:
$ kubectl create secret generic themoviedb --from-literal=apikey=<INSERT YOUR API KEY HERE>
secret/themoviedb created
You can now store the Pod YAML in ambassador-container.yaml
file and create it with kubectl apply -f ambassador-container.yaml
.
apiVersion: v1
kind: Pod
metadata:
name: themoviedb
spec:
containers:
- name: main
image: radial/busyboxplus:curl
args:
- sleep
- "600"
- name: ambassador
image: startkubernetes/ambassador:0.1.0
env:
- name: API_KEY
valueFrom:
secretKeyRef:
name: themoviedb
key: apikey
ports:
- name: http
containerPort: 8080
When Kubernetes creates the Pod (you can use kubectl get po
to see the status), you can use the exec
command to run the curl
command inside the main
container:
$ kubectl exec -it themoviedb -c main -- curl localhost:8080/movies
{"page":1,"total_results":10000,"total_pages":500,"results":[{"popularity":2068.491,"vote_count":
...
Since containers within the same Pod share the network, we can make a request against localhost:8080
, which corresponds to the port on the ambassador container.