ansible playbook,将库存作为变量传递?

ansible playbook,将库存作为变量传递?

我想将 target_host 变量从 tower 覆盖到 playbook 中。覆盖任何其他 playbook 变量都很容易,但我似乎无法让 hosts 值起作用;总是抱怨没有指定主机。

---
- hosts: "{{ target_host }}"
  gather_facts: no
  vars:
    target_host: "10.80.100.163,"
  remote_user: root

  tasks:
  - name: Add users | create users, shell, home dirs
    user:
      name: bubba
      shell: /bin/bash
      createhome: yes
      password: $6$pGO4DKLQ$Eu97vmle/Zvb53gVCXGecfZzvYVd4twj8/EOMwmbYgCUkRAxsWQVXtFrxdZGal6hSLnY..5b/4x1MweH5ierz.
      comment: "Created with Ansible"

希望不必(学习如何)为一个 IP 创建动态库存,有没有办法做到这一点?

谢谢!

答案1

您可以使用 ansible 模块:add_host https://docs.ansible.com/ansible/latest/modules/add_host_module.html

---
- hosts: "localhost"
  gather_facts: no
  tasks:
  - name: Add host
    add_host:
      hostname: "{{ your_new_hostname }}"
      groups: "group_for_new_hostname"
      ansible_user: "{{ ssh_user }}"
      ansible_ssh_pass: "{{ ssh_pass }}"

- hosts: "group_for_new_hostname"
  tasks:
  - name: Add users | create users, shell, home dirs
    user:
      name: bubba
      shell: /bin/bash
      createhome: yes
      password: $6$pGO4DKLQ$Eu97vmle/Zvb53gVCXGecfZzvYVd4twj8/EOMwmbYgCUkRAxsWQVXtFrxdZGal6hSLnY..5b/4x1MweH5ierz.
      comment: "Created with Ansible"

答案2

假设你的剧本文件是 pb.yaml,它看起来像:

---
- name: A playbook name
  #  by default all belonging to tomcat childs go affected
  #  use -e varmcat=someinvhost to override target host explicitly
  hosts: "{{ vartomcat | default('tomcat') }}"
  roles:
    - role: role1
    - role: role2

  tasks:
    - name: task
      ....... 

库存 inv.yaml 文件示例如下:

---
all:
  hosts:
    hostA: &hostA
      ansible_host: serverA.domain.com
    hostX1: &hostX1
      ansible_host: serverX1.domain.com
    hostX2: &hostX2
      ansible_host: serverX2.domain.com
    hostB: &hostB
      ansible_host: serverB.domain.com
    hostY1: &hostY1
      ansible_host: serverY1.domain.com
    hostY2: &hostY2
      ansible_host: serverY2.domain.com

  children:
    tomcat:
      hosts:
        hostA:
        hifsB:
    groupX:
      hosts:
        hostX1:
        hifsX2:
    groupY:
      hosts:
        hostY1:
        hifsY2:

所以你可以覆盖瓦托姆卡特到特定宿主或其他群体

ansible-playbook -i inv.yaml pb.yaml -e vartomcat=hostA

ansible-playbook -i inv.yaml pb.yaml -e vartomcat=hostX1

ansible-playbook -i inv.yaml pb.yaml -e vartomcat=groupY

如果不覆盖:

ansible-playbook -i inv.yaml pb.yaml 

雄猫默认使用 group

相关内容