Variables¶
Variables make configurations reusable and dynamic. Use system facts and custom variables throughout your configuration.
Defining Variables¶
Inline Variables¶
External Variable Files¶
vars/common.yml:
Dynamic Variable Loading¶
Using Variables¶
In Shell Commands¶
In File Paths¶
In File Content¶
- vars:
api_key: secret123
- file:
path: /tmp/config.txt
state: file
content: |
api_key: {{api_key}}
environment: production
In Templates¶
config.yml:
nginx.conf.j2:
System Facts¶
Mooncake automatically provides system information as variables.
Basic Facts¶
# Operating system
os: "linux" # linux, darwin, windows
arch: "amd64" # amd64, arm64, 386, etc.
hostname: "myserver"
user_home: "/home/user"
Distribution Info¶
distribution: "ubuntu" # ubuntu, debian, centos, macos, etc.
distribution_version: "22.04" # Full version
distribution_major: "22" # Major version only
Hardware Facts¶
Software Detection¶
package_manager: "apt" # apt, yum, brew, pacman, etc.
python_version: "3.10.0" # Installed Python version
Network Facts¶
GPU Facts¶
Storage Facts¶
Network Interfaces¶
network_interfaces:
- name: "eth0"
mac_address: "00:11:22:33:44:55"
- name: "wlan0"
mac_address: "AA:BB:CC:DD:EE:FF"
Viewing System Facts¶
Run mooncake explain to see all available facts:
Output shows: - Operating system details - CPU and memory - GPUs - Storage devices - Network interfaces - Package manager - Python version
Using System Facts¶
OS Detection¶
Distribution-Specific Commands¶
- shell: apt install package
when: distribution == "ubuntu" || distribution == "debian"
- shell: yum install package
when: distribution == "centos" || distribution == "fedora"
Architecture Detection¶
- shell: install-amd64-binary
when: arch == "amd64"
- shell: install-arm64-binary
when: arch == "arm64"
Memory-Based Decisions¶
Package Manager Detection¶
Variable Precedence¶
When the same variable is defined in multiple places:
-
Template vars (highest priority)
-
Step-level vars
-
Included vars
-
System facts (lowest priority)
Variable Scoping¶
Variables are available to all subsequent steps:
# Step 1: Define
- vars:
app_name: myapp
# Step 2: Use in same file
- shell: echo "{{app_name}}"
# Step 3: Use in included files
- include: ./tasks/setup.yml # Can use app_name
Register Variables¶
Capture command output as variables:
- shell: whoami
register: current_user
- shell: echo "User is {{current_user.stdout}}"
- file:
path: "/home/{{current_user.stdout}}/config"
state: file
Loop Variables¶
Special item variable in loops:
- vars:
users: [alice, bob]
- name: Create directory for {{item}}
file:
path: "/home/{{item}}"
state: directory
with_items: "{{users}}"
Best Practices¶
-
Use descriptive names
-
Quote version strings
-
Group related variables
-
Use external files for environments
-
Use system facts when possible
See Also¶
- Actions - Using variables in actions
- Control Flow - Using variables in conditions
- Examples - Variable examples
- Commands - View system facts