FreeKB - ansible-playbook command - creating and using variables
ansible-playbook command - creating and using variables

Home > Search


This assumes you have installed Ansible Tower and are familiar with the ansible-playbook command. In this example, a variable named "foo" is created in the playbook.yml file.

---
- hosts: linux
  remote_user: root
  vars:
    foo: "Hello World"
  tasks:
    - debug: msg="{{ foo }}"

 

Which will produce output like this.

TASK [debug]
ok: [server1.example.com] => {
    "msg": "Hello World"
}

 

Or, variables can be created on the command line and passed into the playbook, like this.

ansible-playbook playbook.yml -i inventory.yml --extra-vars "foo=Hello bar=World"

 

In this scenario, you would not define the variable in your playbook.yml file, but you would use the variable in your playbook.yml file.

---
- hosts: linux
  remote_user: root
  tasks:
    - debug: msg="{{ foo }}"

 

Or, variables can contain the values from other variables.

target_servers: "{{play_hosts}}"

 


Global variables

By default, variables are isolated to only be accessible within a hosts. Here is now to create a variable that can be used in multiple hosts.

- hosts: all
  tasks:
    - set_fact: foo='bar'

- hosts: all
  tasks:
    -debug: msg="{{foo}}"

- hosts: web
  tasks:
    - debug: msg="{{foo}}"

 

Or, you can start like this, if you know the variable only needs to be used in certain hosts.

- hosts: web:db

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 39fe6 in the box below so that we can be sure you are a human.




Comments