Ansible:无法将命令存储在变量中并在其他主机中使用

时间:2019-03-27 17:28:13

标签: ansible

我正在尝试使用kubernetes来建立kubeadm集群

我想获取加入命令(在master节点上完成)并在工作节点上运行它。

以下方法无效:

- name: kubernetes.yml --> Get the join command
  shell: kubeadm token create --print-join-command
  register: rv_join_command
  when: inventory_hostname in (groups['masters'] | last)
  become: yes


- name: kubernetes.yml --> Store the join command
  set_fact:
    join_command: "{{ rv_join_command.stdout }}"
  run_once: true
  when: inventory_hostname in (groups['masters'] | last)


- name: DEBUG kubernetes.yml --> Print the join command
  debug:
    var: rv_join_command.stdout
  when: inventory_hostname in (groups['masters'] | last)


- name: kubernetes.yml --> Run the join command on kubernetes nodes
  shell: "{{ join_command }}"
  when: inventory_hostname in groups['nodes']

由于失败而出现:

  

'join_command'未定义

但是下面的方法也失败了:

- name: kubernetes.yml --> Run the join command on kubernetes nodes
  shell: "{{ rv_join_command.stdout }}"
  when: inventory_hostname in groups['nodes']
  become: yes
  

错误是:“字典对象”没有属性“ stdout”

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

如上面的larsks注释中所指出的,您只为单个主机(groups ['masters'] | last)存储join_command变量,并且仅在其中可用。

同时,可以从任何地方从其他主机访问var。

您基本上有两个选择:

  1. 修改set_fact以将主节点上的结果中的var存储在每个节点上
  2. 修改连接命令运行以在每个节点上的master上使用存储的var

选项1

    public boolean isInIncreasingOrder(Item it) {
        boolean sorted = true;
        for(int i = 1; i < list.size(); i++) {
          if(list.get(i-1).compareTo(list.get(i)) > 0){
            sorted = false;
          }
        }
        return sorted;

    }

选项2

- name: kubernetes.yml --> Store the join command
  set_fact:
    join_command: "{{ hostvars[groups['masters'] | last].rv_join_command.stdout }}"
  when: inventory_hostname in groups['nodes']
# Now you can use join_command on each node