简体   繁体   English

可以使用 ansible 变量在剧本中声明主机吗?

[英]Can ansible variables be used to declare hosts in a playbook?

I have a playbook in the format below:我有以下格式的剧本:

---
- hosts: myIP
  tasks:
  - name: Install a yum package in Ansible example
    yum:
      name: ThePackageIWantToInstall
      state: present

where myIP and ThePackageIWantToInstall are variables.其中myIPThePackageIWantToInstall是变量。

When the job template runs, I would like the user in the extra variables popup to be able to go with:当作业模板运行时,我希望额外变量弹出窗口中的用户能够使用:

myIP = 192.168.1.1
ThePackageIWantToInstall = nano

As the documentation doesn't provide an example of supplying a variable via a job template, is this possible?由于文档没有提供通过作业模板提供变量的示例,这可能吗?

Yes.是的。

- name: Do The Thing
  hosts: "{{ foo }}"
  roles:
   - "{{ role }}"

Need mustaches and quotes.需要胡子和引号。


to run from popup从弹出窗口运行

(I don't use this, but it was suggested as an edit, thanks...) (我不使用它,但有人建议将其作为编辑,谢谢...)

foo: value foo: 值

I have achieved similar thing with add_hosts.我用 add_hosts 实现了类似的事情。 Here iam not installing package but creating file with name passed from command line.这里我不是安装包,而是创建名称从命令行传递的文件。 Any number of hosts (separated by commas can be passed from command line).任意数量的主机(可以从命令行传递以逗号分隔)。

# cat addhost2.yml
- hosts: localhost
  gather_facts: no
  tasks:
    - add_host:
        name: "{{ item }}"
        groups: hosts_from_commandline
      with_items: "{{ new_hosts_passed.split(',') }}"


- hosts: hosts_from_commandline
  tasks:
    - name: Ansible create file with name passed from commandline
      file:
        path: "/tmp/{{ filename_from_commandline }}"
        state: touch
# ansible-playbook -i hosts addhost2.yml --extra-vars='new_hosts_passed=192.168.3.104,192.168.3.113 filename_from_commandline=lathamdkv'

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM