1

I stuck a bit with ansible and autogenerated id, I have multiple mysql master - slaves server for that I need to generate a server-id.

my idea was to do something like this:

   - name: generate repli-id
      shell: hostname -I | sed -e 's/ \+\([a-z0-9]\+\:\)\+[a-z0-9]\+//' | sed -e 's/ /\n/' | grep -v '^$' | tail -1 | awk -F. '{print $3 * 256 + $4}'
      register:  slave_repli

    - debug: var=slave_repli.stdout_lines

    - name: rewrite
      template: src=templates/root.j2 dest=/root/test.conf

so I get the id generated

TASK [debug] *******************************************************************
task path: /Users/miwi/ansible/roles/test/main.yml:32
ok: [mysqls5slave] => {
    "slave_repli.stdout_lines": [
        "3698"
    ]
}
ok: [mysqls5master] => {
    "slave_repli.stdout_lines": [
        "3699"
    ]
}

my question is now how do I pass it over to my var file

slave_server_id: {{ slave_server_id }}

0

Instead of generating your ID from within your playbook, this is where you may want to define a custom fact. On your mysql server, you'ld do something like this:

mkdir -p /etc/ansible/facts.d
cat <<EOF >/etc/ansible/facts.d/mysql.fact
#!/bin/sh
echo "[mysql]"
echo server_id=`hostname -I | sed -e 's/ \+\([a-z0-9]\+\:\)\+[a-z0-9]\+//' | sed -e 's/ /\n/' | grep -v '^$' | tail -1 | awk -F. '{print $3 * 256 + $4}'`
EOF
chmod +x /etc/ansible/facts.d/mysql.fact

Run ansible -m setup your.mysql.ip.address to make sure your fact is properly executed. You should have some ansible_local['mysql']['mysql']['server_id'] defined.

Say you'ld want ansible to deploy this fact, you may do something like:

- name: install fact
  copy: src=myfact dest=/etc/ansible/facts.d/mysql.fact owner=root group=root mode=0755
  register: fact_installed
- name: reload facts
  setup: filter=ansible_local
  when: fact_installed is defined and fact_installed.changed == True

After which, you may include your template, referring to your server_id variable.

0

You could use the copy module in addition with local_action to save the variable to a local file on your control machine and use it later on your next playbook:

- local_action: copy content="slave_server_id: {{ slave_repli.stdout_lines[0] }}" dest=/path/to/var/file
0

You have two options to use the generated value in your template:

Option 1: Use slave_repli.stdout_lines in your template:

# in templates/root.j2:
...
slave_server_id: {{ slave_repli.stdout_lines[0] }}
...

Option 2: Assign a variable

In your playbook:

- name: rewrite
  vars:
    slave_server_id: "{{ slave_repli.stdout_lines[0] }}"
  template:
    src: templates/root.j2
    dest: /root/test.conf

In your template:

# in templates/root.j2:
...
slave_server_id: {{ slave_server_id }}
...

I prefer the second approach as it's much cleaner.

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.