0

I am learning Ansible & dealing with Kubernetes clusters. I would like to have an Ansible task which can change the value in .kube/config in my local Ansible host. For example, the .kube/config content looks like this:

apiVersion: v1
clusters:
- cluster:
    server: xxx
  name: xxx

contexts:
- context:
    cluster: yyy
    user: yyy
  name: yyy

users:
- name: xxx
  user: xxx

I basically would like to have an Ansible task to be able to do the following things:

  1. change those values of xxx, yyy in the file .kube/config on ansible host.

  2. append new content under each section of clusters, context & users if the values do not exist.

Is there a Kubernetes module or plugin I could directly use to achieve it? If not, could someone guide me how to achieve it?

==== I tried this ====

I tried :

- name: Update value to foo
  replace:
    path: ~/.kube/config
    regexp: 'yyy'
    regexp: 'foo'
  delegate_to: localhost

When running the task, the file content doesn't change at all. Why? (Task has been executed based on logs)

U880D
  • 8,601
  • 6
  • 24
  • 40
user842225
  • 5,445
  • 15
  • 69
  • 119

1 Answers1

0

Is there a kubernetes module or plugin I could directly use to achieve it?

Since your input file looks like valid YAML at a first glance, you could simply read it in via include_vars module – Load variables from files, dynamically within a task.

A minimal example playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Read kubeconfig
    include_vars:
      file: kubeconfig
      name: kubeconfig

  - debug:
      msg: "{{ kubeconfig }}"

  - name: Write kubeconfig
    copy:
      content: "{{ kubeconfig | to_nice_yaml }}"
      dest: kubeconf # for testing with new file name

resulting into an output of

TASK [debug] ********
ok: [localhost] =>
  msg:
    apiVersion: v1
    clusters:
    - cluster:
        server: xxx
      name: xxx
    contexts:
    - context:
        cluster: yyy
        user: yyy
      name: yyy
    users:
    - name: xxx
      user: xxx

~/test$ cat kubeconf
apiVersion: v1
clusters:
-   cluster:
        server: xxx
    name: xxx
contexts:
-   context:
        cluster: yyy
        user: yyy
    name: yyy
users:
-   name: xxx
    user: xxx

Then do your data manipulation steps like changing values or append new content. After that write the data structure back into a new file or overwrite the existing one.

By following this approach one can keep the use case simple and by using out-of-box functionality.

Further Q&A

Further Documentation

Since it is not possible to change or update existing variables, but register new ones with the same name, you may also have a look into

U880D
  • 8,601
  • 6
  • 24
  • 40