deployment - Como defino registrar uma variável para persistir entre execuções no ansible?




(2)

Use um host fictício e suas variáveis

Por exemplo, para passar o token e o hash K8S do mestre para os trabalhadores.

No mestre

- name: "Cluster token"
  shell: kubeadm token list | cut -d ' ' -f1 | sed -n '2p'
  register: K8S_TOKEN

- name: "CA Hash"
  shell: openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'
  register: K8S_MASTER_CA_HASH

- name: "Add K8S Token and Hash to dummy host"
  add_host:
    name:   "K8S_TOKEN_HOLDER"
    token:  "{{ K8S_TOKEN.stdout }}"
    hash:   "{{ K8S_MASTER_CA_HASH.stdout }}"

- name:
  debug:
    msg: "[Master] K8S_TOKEN_HOLDER K8S token is {{ hostvars['K8S_TOKEN_HOLDER']['token'] }}"

- name:
  debug:
    msg: "[Master] K8S_TOKEN_HOLDER K8S Hash is  {{ hostvars['K8S_TOKEN_HOLDER']['hash'] }}"

No trabalhador

- name:
  debug:
    msg: "[Worker] K8S_TOKEN_HOLDER K8S token is {{ hostvars['K8S_TOKEN_HOLDER']['token'] }}"

- name:
  debug:
    msg: "[Worker] K8S_TOKEN_HOLDER K8S Hash is  {{ hostvars['K8S_TOKEN_HOLDER']['hash'] }}"

- name: "Kubeadmn join"
  shell: >
    kubeadm join --token={{ hostvars['K8S_TOKEN_HOLDER']['token'] }}
    --discovery-token-ca-cert-hash sha256:{{ hostvars['K8S_TOKEN_HOLDER']['hash'] }}
    {{K8S_MASTER_NODE_IP}}:{{K8S_API_SERCURE_PORT}}

Eu tenho um manual ansible, onde eu gostaria que uma variável que eu registrasse em uma máquina estivesse disponível em outra.

No meu caso, eu gostaria de executar um comando no localhost , neste caso git rev-parse --abbrev-ref HEAD , para que eu possa anotar o ramo atual do git e sha1 e registrar essa saída, para Posso me referir a isso mais tarde, quando estiver trabalhando em qualquer máquina do grupo main , na segunda peça.

No entanto, não está claro para mim como eu registro uma variável no localhost, para que eu possa acessá-la do main. Quando tento acessar a variável na segunda reprodução, recebo esta mensagem:

TASK: [debug msg={{ app_git_sha1.stdout }}] ***********************************
fatal: [main] => One or more undefined variables: 'app_git_sha1' is undefined

Aqui está a peça que estou usando. Existe algo óbvio que eu deveria estar fazendo?

---
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - name: register current branch
      command: git rev-parse --abbrev-ref HEAD
      register: git_branch
      sudo: no
      when: vagrant
      tags:
        - debugsha

    - debug: msg={{ git_branch.stdout }}
      tags:
        - debugsha

    - name: register the SHA1 of the branch being deployed
      command: git rev-parse origin/{{ git_branch.stdout }}
      register: app_git_sha1
      sudo: no
      tags:
        - slack
        - debugsha

    - debug: msg={{ app_git_sha1.stdout }}
      tags:
        - debugsha



- hosts: main
  sudo: yes
  roles:
    - role: productscience.deploy_user
    # TODO reprovision using these roles, for consistency
    # - role: app.essentials
    # - role: zenoamaro.postgresql
    - role: productscience.papertrailapp
    - role: jdauphant.nginx
  tasks:
    - include: setup.yml
    # - include: db.yml

    - name: checkout source control when deploying to remote servers
      include: source.yml
      when: not vagrant
      tags:
          - deploy

    - include: django.yml
      tags:
          - deploy


    - name: include vagrant specific dependencies for local development
      include: vagrant.yml
      when: vagrant

  handlers:
    - name: restart postgres
      sudo: yes
      service: name=postgresql state=restarted
    - name: start restart uwsgi
      sudo: yes
      service: name={{ app }} state=restarted

- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - name: register the SHA1 of the branch being deployed
      when: not vagrant
      command: git rev-parse origin/{{ git_branch }}
      register: git_sha
      tags:
        - slack

    - name: Send notification message via Slack all options
      when: not vagrant
      tags:
        - slack
      local_action:
        module: slack
        token: "{{ wof_slack_token }}"
        msg: "Deployment of `{{ git_branch }}` to {{ app_url }} completed with sha `{{ git_sha.stdout }}`"
        channel: "#wof"
        username: "Ansible deploy-o-tron"

Eu tive problemas semelhantes com o mesmo host, mas em diferentes peças. É importante lembrar que fatos e não variáveis ​​são as coisas que persistem entre as peças. Aqui está como eu contornar o problema.

#!/usr/local/bin/ansible-playbook --inventory=./inventories/ec2.py
---
- name: "TearDown Infrastructure !!!!!!!"
  hosts: localhost
  gather_facts: no
  vars:
    aws_state: absent
  vars_prompt:
    - name: "aws_region"
      prompt: "Enter AWS Region:"
      default: 'eu-west-2'
  tasks:
    - name: Make vars persistant
      set_fact:
        aws_region: "{{aws_region}}"
        aws_state: "{{aws_state}}"




- name: "TearDown Infrastructure hosts !!!!!!!"
  hosts: monitoring.ec2
  connection: local
  gather_facts: no
  tasks:
    - name: set the facts per host
      set_fact:
        aws_region: "{{hostvars['localhost']['aws_region']}}"
        aws_state: "{{hostvars['localhost']['aws_state']}}"


    - debug:
        msg="state {{aws_state}} region {{aws_region}} id {{ ec2_id }} "

- name: last few bits
  hosts: localhost
  gather_facts: no
  tasks:
    - debug:
        msg="state {{aws_state}} region {{aws_region}} "

resulta em

Enter AWS Region: [eu-west-2]:


PLAY [TearDown Infrastructure !!!!!!!] ***************************************************************************************************************************************************************************************************

TASK [Make vars persistant] **************************************************************************************************************************************************************************************************************
ok: [localhost]

PLAY [TearDown Infrastructure hosts !!!!!!!] *********************************************************************************************************************************************************************************************

TASK [set the facts per host] ************************************************************************************************************************************************************************************************************
ok: [XXXXXXXXXXXXXXXXX]

TASK [debug] *****************************************************************************************************************************************************************************************************************************
ok: [XXXXXXXXXXX] => {
    "changed": false,
    "msg": "state absent region eu-west-2 id i-0XXXXX1 "
}

PLAY [last few bits] *********************************************************************************************************************************************************************************************************************


TASK [debug] *****************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "msg": "state absent region eu-west-2 "
}

PLAY RECAP *******************************************************************************************************************************************************************************************************************************
XXXXXXXXXXXXX              : ok=2    changed=0    unreachable=0    failed=0
localhost                  : ok=2    changed=0    unreachable=0    failed=0