0
rolebinding="apiVersion: rbac.authorization.k8s.io/v1beta1\nkind: RoleBinding\nmetadata:\n  name: $rolebindingname\n  namespace: $namespace\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: ClusterRole\n  name: admin\nsubjects:\n- kind: ServiceAccount\n  name: $accountname"
echo -e  $rolebinding |  kubectl apply -f -

I want to make space at the end the script so it can be as below:

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: monitoring-gitlab-rolebinding
  namespace: mdep
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin
subjects:
- kind: ServiceAccount
  name: monitoring-gitlab

2 Answers2

0

There are two pieces to this.

The first part is properly building a multi-line string. The following is one thread that talks about this: How to assign a heredoc value to a variable in Bash? .

The second part is a little more subtle, if the first part wasn't subtle enough for you.

You have to echo out the value in a particular way, otherwise it won't preserve the line endings.

If the variable is "stuff", the following will echo it out preserving line endings:

echo "$stuff"

Doing it this way will lose the line endings:

echo $stuff
David M. Karr
  • 14,317
  • 20
  • 94
  • 199
0

Drop the variable & echo command. Just use a "heredoc" as input to kubectl. The quotes around 'EOF' preserve whitespace:

kubectl apply -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: $rolebindingname
  namespace: $namespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin
subjects:
- kind: ServiceAccount
  name: $accountname
EOF
Eric Bolinger
  • 2,722
  • 1
  • 13
  • 22