1

I am completely new to ansible this is my second day working with ansible, What I'm ultimately trying to do is configure a kubernetes cluster which has a master node and one worker node. But my problem is I've been asked to add an apt-key without using a hardcoded url. So I have an ansible playbook called kube-repos.yml which is as follows:

- hosts: all
  become: yes
  tasks:

  - name: add Kubernetes apt-key
    apt_key:
      url: "https://packages.cloud.google.com/apt/doc/apt-key.gpg"
      state: present

  - name: add Kubernetes' APT repository
    apt_repository:
      repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
      state: present

where I add the apt-key I need to use another method to add the apt-key where it needs to be defined per-host. If anyone knows of other ways of adding an apt-key I would really like to hear them so I can look further into alternate ways of adding an apt-key. Thanks in advanced for any help or points in the right direction.

1

Add the key per host or per group in your inventory. Below example is for an all-in-one yaml inventory. See How to build you inventory for all options to organize your vars (I suggest you read this documentation in depth).

inventory/example.yml

---
all:
  hosts:
    master1.tld.local:
    master2.tld.local:
    worker1.tld.local:
    worker2.tld.local:
      # This will be used only for this node and will
      # override group var as it is more specific
      # see: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#understanding-variable-precedence
      my_apt_key: https://some.server.com/custom_node_key.gpg
    worker3.tld.local:

  children:
    master:
      vars:
        # This will be applied to all machines in group
        my_apt_key: https://some.server.com/master_key.gpg
      hosts:
        master1.tld.local:
        master2.tld.local:

    worker:
      vars:
        my_apt_key: https://some.server.com/worker_key.gpg
      hosts:
        worker1.tld.local:
        worker2.tld.local:
        worker3.tld.local:

Modify your task in your playbook. As a good practice, I'll add a default value so it does not break if the var is not defined. You can drop this if this is not the behavior you want:

playbook.yml

  - name: add Kubernetes apt-key
    apt_key:
      url: "{{ my_apt_key | default('https://some.server.com/default.gpg) }}"
      state: present

Then enjoy:

ansible-playbook -i inventory/example.yml playbook.yml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.