I have a terraform stack which will deploy vault-consul on Google Kubernetes Engine. Now, I need to automate the vault initialization instead of doing it manually using “vault operator init”.
So, created a kubernetes_job_v1 resource which will initialize the vault using /v1/sys/init Vault API endpoint. Additionally, I added few things like, if the initialization is successful, a kubernetes secret should be created out of the json output got while initializing which contains root_token and unseal_keys of the vault. And if the initialization is not successful, the job should get restarted and retry to initialize the vault.
Below is my kubernetes job
resource "kubernetes_job_v1" "create_secret_job" {
metadata {
name = "init-vault"
namespace = kubernetes_namespace_v1.helper.metadata[0].name
}
spec {
ttl_seconds_after_finished = 1200
template {
metadata {
name = "init-vault"
}
spec {
service_account_name = kubernetes_service_account_v1.init_vault.metadata[0].name
container {
name = "init-vault"
image = "ubuntu"
command = ["/bin/sh", "-c"]
args = [
<<-EOT
apt-get update -y && apt-get install jq -y && apt-get install curl -y && apt-get install -y telnet && \
curl -LO https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl && \
chmod +x kubectl && mv kubectl /usr/local/bin/ && kubectl version && mkdir /mnt/secret && \
cd /mnt/secret && echo '{"recovery_shares": 5, "recovery_threshold": 3, "stored_shares": 5}' > payload.json && \
curl -k --request PUT --data @payload.json https://vault-0.vault-internal.vault.svc.cluster.local:8200/v1/sys/init > output.json && \
curl -k --request GET --data @payload.json https://vault-0.vault-internal.vault.svc.cluster.local:8200/v1/sys/init > getresponse.json && \
cat getresponse.json && \
initialized_value=$(jq -r '.initialized' getresponse.json); \
if [ "$initialized_value" = "true" ]; then \
echo 'Vault is initialized'; \
kubectl create secret generic my-secret --from-file=/mnt/secret/output.json; \
exit 0; \
else \
echo 'Vault is not initialized. Restarting the job...'; \
exit 1; \
fi
EOT
]
}
restart_policy = "Never"
}
}
backoff_limit = 10
}
wait_for_completion = true
}
Now, I need to provide the content of output.json in terraform output.
Tried with below
data "kubernetes_secret_v1" "my_secret" {
metadata {
name = "my-secret"
namespace = "helper"
}
depends_on = [ kubernetes_job_v1.create_secret_job ]
}
output "my_secret_data" {
value = data.kubernetes_secret_v1.my_secret.data["output.json"]
}
But it’s returning error as it has nothing except null value.
I am using terraform cloud to create the k8s stack. As per my understanding, terraform is unable to understand about the resource which is not created using terraform resource “kubernetes_secret”. Got stucked at how to display the secret data on terraform output.
Can anyone please help me to solve this? Thanks in Advance!