Ansible Playbook嵌套调用的变量配置与执行条件疑问
Fixing Your Ansible Playbook Issues: Variable Control and Cross-Play Access
Let’s walk through fixing your two problems step by step, with corrected playbook code and clear explanations.
1. Resolving the is_done Variable and Conditional Execution of slave.yaml
Your original master.yaml has a syntax error: you tried to place the include statement inside the vars block, which isn’t allowed. Plus, the conditional logic for running slave.yaml was misplaced. Here’s the fixed version:
# master.yaml - hosts: master remote_user: "{{ ansible_user }}" vars: # Set default value here, or override via command line with `-e "is_done=true"` is_done: "false" tasks: - name: Get user group name command: id -g -n {{ lookup('env', '$USER') }} register: group_user # Use include_playbook for conditional execution of the slave playbook - include_playbook: slave.yaml vars: # Pull the registered group_user value from the master host sethostname: "{{ hostvars['master'].group_user.stdout }}" worker_target_group: worker # Only run slave.yaml if is_done is set to "true" when: hostvars['master'].is_done == "true"
Key Fixes:
- Moved
is_doneto the propervarsblock in the master play. To trigger the slave playbook, run your playbook with:ansible-playbook master.yaml -e "is_done=true" - Used
include_playbook(instead of the misplacedinclude) to loadslave.yamlas a separate play, with a top-levelwhencondition. - Accessed the
group_userregistered variable from the master host usinghostvars['master'].group_user.stdout—variables from one play aren’t automatically available to others, so we explicitly reference the master host’s data.
2. Accessing Variables in slave.yaml
Your slave.yaml can easily access variables passed from master.yaml, plus inventory group data since you’ve already defined the worker group. Here’s the updated slave.yaml:
# slave.yaml # Use the passed worker group variable, with a default fallback to the "worker" inventory group - hosts: "{{ worker_target_group | default('worker') }}" remote_user: "{{ ansible_user }}" tasks: - name: Write group name to setup file copy: content: "{{ sethostname }}" dest: "/home/ubuntu/test.txt" # Fixed typo from test.text to test.txt - name: Example: Access worker group inventory data debug: msg: "All hosts in worker group: {{ groups['worker'] }}"
How Variable Access Works:
- The
sethostnameandworker_target_groupvariables passed frommaster.yamlare directly usable inslave.yamltasks. - To access the
workerinventory group itself (like listing all hosts in the group), usegroups['worker']—Ansible automatically makes inventory group data available to all plays. - The
| default('worker')ensures your play still runs ifworker_target_groupisn’t passed, adding flexibility to your setup.
内容的提问来源于stack exchange,提问作者TechChain
相关产品推荐
相关产品推荐

