How to define variables in Ansible?

QuestionsQuestions4 SkillsProAnsible Playbook BasicsOct, 15 2025
0152

In Ansible, you can define variables in several ways. Here are the most common methods:

  1. In the Playbook: You can define variables directly within your playbook using the vars section.

    - hosts: all
      vars:
        http_port: 80
        db_port: 3306
      tasks:
        - name: Print HTTP port
          debug:
            msg: "HTTP port is {{ http_port }}"
    
  2. In Inventory Files: You can define host or group variables in your inventory file.

    [web]
    localhost http_port=80
    
    [db]
    localhost db_port=3306
    
  3. In Variable Files: You can create separate YAML files to store variables and include them in your playbook. For example, create a file named vars.yml:

    http_port: 80
    db_port: 3306
    

    Then include it in your playbook:

    - hosts: all
      vars_files:
        - vars.yml
      tasks:
        - name: Print HTTP port
          debug:
            msg: "HTTP port is {{ http_port }}"
    
  4. As Facts: Ansible automatically gathers facts about the managed nodes, which can be used as variables. You can access these facts using the ansible_facts variable.

    - hosts: all
      tasks:
        - name: Print OS version
          debug:
            msg: "Operating System is {{ ansible_facts['os'] }}"
    
  5. Using Command Line: You can also pass variables at runtime using the -e option with the ansible-playbook command.

    ansible-playbook my-playbook.yml -e "http_port=80 db_port=3306"
    

These methods allow you to define and manage variables effectively in your Ansible automation tasks.

0 Comments

no data
Be the first to share your comment!