How can I write variables inside the tasks file in

2019-03-09 11:01发布

问题:

I have this play.yml

---
- hosts: 127.0.0.1
  connection: local
  sudo: false

  tasks:
     - include: apache.yml

My Apache look like this:

vars:
    url: czxcxz

- name: Download apache
  shell: wget {{url}} 

This is giving me error.

If I remove vars then it works. But I want to include the vars inside tasks so that I can keep different vars for different tasks separate.

回答1:

NOTE: Using set_fact as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.

Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.


ORIGINAL ANSWER

Use set_fact before your task to set facts which seem interchangeable with variables:

- name: Set Apache URL
  set_fact:
    apache_url: 'http://example.com/apache'

- name: Download Apache
  shell: wget {{ apache_url }}

See http://docs.ansible.com/set_fact_module.html for the official word.



回答2:

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.



回答3:

I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.

Just move the var inside the "name" block:

- name: Download apache
  vars:
    url: czxcxz
  shell: wget {{url}} 


回答4:

Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:

- name: some example
  command: {{ myapp }} -a foo

The default here is to parse the first part of {{ myapp }} -a foo as a dictionary instead of a string and you will get an error.

So you must quote the argument like so:

- name: some example
  command: "{{ myapp }} -a foo"


回答5:

You need to quote the variable when it is in playbooks,

shell: wget "{{url}}"

Otherwise Ansible thinks you are declaring a dictionary. More details here, under "Gotchas": https://docs.ansible.com/ansible/YAMLSyntax.html

https://docs.ansible.com/ansible/playbooks_variables.html#hey-wait-a-yaml-gotcha