我试图使用ansible为由2个mysql主机组成的主机组设置mysql主从复制。
这是我的场景:
我在第一台主机上运行一个任务并跳过第二台主机,因此第一个任务(即主复制状态)返回一些值,例如位置、文件等。
然后,我在第二个主机中运行另一个任务(跳过第一个主机),该任务使用第一个任务的返回值,如 master.Position、master.File 等。
现在,当我运行剧本时,第一个任务的变量似乎不适用于第二个任务
库存文件
[mysql]
stagmysql01 ansible_host=1.1.1.1 ansible_ssh_user=ansible ansible_connection=ssh
stagmysql02 ansible_host=1.1.1.2 ansible_ssh_user=ansible ansible_connection=ssh
大师的任务
- name: Mysql - Check master replication status.
mysql_replication: mode=getmaster
register: master
- debug: var=master
从机上的任务
- name: Mysql - Configure replication on the slave.
mysql_replication:
mode: changemaster
master_host: "{{ replication_master }}"
master_user: "{{ replication_user }}"
master_password: "{{ replication_pass }}"
master_log_file: "{{ master.File }}"
master_log_pos: "{{ master.Position }}"
ignore_errors: True
主输出
TASK [Mysql_Base : Mysql - Check master replication status.] ****************
skipping: [stagmysql02]
ok: [stagmysql01]
TASK [Mysql_Base : debug] ***************************************************
ok: [stagmysql01] => {
"master": {
"Binlog_Do_DB": "",
"Binlog_Ignore_DB": "mysql,performance_schema",
"Executed_Gtid_Set": "",
"File": "mysql-bin.000003",
"Is_Master": true,
"Position": 64687163,
"changed": false,
"failed": false
}
}
ok: [stagmysql02] => {
"master": {
"changed": false,
"skip_reason": "Conditional result was False",
"skipped": true
}
}
从机输出
TASK [Mysql_Base : Mysql - Configure replication on the slave.] *************
skipping: [stagmysql01]
fatal: [stagmysql02]: FAILED! => {"failed": true, "msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'File'\n\nThe error appears to have been in '/root/ansible/roles/Mysql_Base/tasks/replication.yml': line 30, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Mysql - Configure replication on the slave.\n ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'dict object' has no attribute 'File'"}
...ignoring
正如您在上面看到的,由于未定义的变量,第二个主机的第二个任务失败。然而,所需的变量存在于第一台主机的第一个任务中。
如何在另一个任务的第二台主机中使用从第一台主机返回的变量?
P.S:我已经看到了使用 {{ hostvars['inventory_hostname']['variable'] }} 的方法。
然而,我对这种方法很困惑,因为需要直接添加 inventory_hostname 或 IP 地址。我一直在寻找一个可用于不同库存文件和剧本的通用模板。