Search code examples
bashyamlkubectl

kubectl YML : what type of file is this and how to run it


I can see a way to create kubectl command like this where I can pass some parameterize values ad well.

My question is, with what type of file we will save this, Is this a bash script? and how to run and supply the parameter?

export SECRET_NAME="my-app.secret"

cat <<EOF | kubectl apply -f -
 apiVersion: v1
 kind: Secret
 metadata:
 name: $SECRET_NAME
 type: Opaque
 data:
 password: $(echo -n "s33msi4" | base64 -w0)
 username: $(echo -n "jane" | base64 -w0)
EOF

Solution

  • Yes, it can be treated as a bash script. As Jetchisel already mentioned in his comment, it contains a structure called Here Document used with cat command but it also contains export command which sets and exports a variable. So as a whole it can be treated as a simple bash script with 2 instructions.

    In order to run it and create a new Secret object (which is your ultimate goal), follow these steps:

    1. Fix the indentation which is crucial in yaml files:
    export SECRET_NAME="my-app.secret"
    
    cat <<EOF | kubectl apply -f -
     apiVersion: v1
     kind: Secret
     metadata:
       name: $SECRET_NAME
     type: Opaque
     data:
       password: $(echo -n "s33msi4" | base64 -w0)
       username: $(echo -n "jane" | base64 -w0)
    EOF
    
    1. Save the above content as a file. You can call it secret.sh.
    2. Source it (source and . are the same command):
    . secret.sh
    
    1. You should see the following message:
    secret/my-app.secret created
    

    Alternatvely you can paste it directly into the console. As you can see, it also works:

    ### don't copy it, this is the example console output 
    ### you will see once you paste the above script in your bash shell
    
    $ export SECRET_NAME="my-app.secret"
    $
    $ cat <<EOF | kubectl apply -f -
    >  apiVersion: v1
    >  kind: Secret
    >  metadata:
    >    name: $SECRET_NAME
    >  type: Opaque
    >  data:
    >    password: $(echo -n "s33msi4" | base64 -w0)
    >    username: $(echo -n "jane" | base64 -w0)
    > EOF
    secret/my-app.secret created