Ansible |部署虚拟机,然后针对新主机运行其他行动手册



我是Ansible的新手。我创建了一个Ansible角色,其中包含以下任务,这些任务将从模板部署vm,然后使用自定义操作系统设置配置vm:

  • create-vm.yml
  • 配置-vm.yml

我可以通过";创建vm";任务但在那之后完整,我想继续使用";配置vm";任务由于playbooks/role-vm-deploy.yml文件包含";localhost";如图所示。。。

- hosts: localhost
roles: 
- vm-deploy
gather_facts: no
connection: local

下一个任务没有成功运行,因为它正试图针对";localhost";而不是新的VM主机名。此后,我在";创建vm";任务

- name: Add host to group 'just_created'
add_host:
name: '{{ hostname }}.{{ domain }}'
groups: just_created

但我不太确定该怎么办;配置vm";task而不是localhost。

我正在通过CLI 执行剧本

# ansible-playbook playbooks/role-vm-deploy.yml

我看到了这篇帖子,很有帮助我也看到了动态库存文档,但在这个时候我有点不知所措。如有任何帮助,我们将不胜感激。非常感谢。

以下是行动手册和任务的内容

### playbooks -> role-vm-deploy.yml
- hosts: localhost
roles:
- vm-deploy
gather_facts: no
connection: local
### roles -> vm-deploy -> tasks -> main.yml
- name: Deploy VM
include: create-vm.yml
tags:
- create-vm
- name: Configure VM
include: configure-vm.yml
tags:
- configure-vm

### roles -> vm-deploy -> tasks -> create-vm.yml    
- name: Clone the template
vmware_guest:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_pwd }}'
validate_certs: False
name: '{{ hostname }}'
template: '{{ template_name }}'
datacenter: '{{ datacenter }}'
folder: '/'
hardware:
memory_mb: '{{ memory }}'
num_cpus: '{{ num_cpu }}'

networks:
- label: "Network adapter 1"
state: present
connected: True
name: '{{ vlan }}'
state: poweredon
wait_for_ip_address: yes

### roles -> vm-deploy -> tasks -> configure-vm.yml
### This task is what I need to execute on the new hostname, but it attempts to execute on "localhost" ###
# Configure Networking
- name: Configure IP Address
lineinfile:
path: '{{ network_conf_file }}'
regexp: '^IPADDR='
line: 'IPADDR={{ ip_address }}'
- name: Configure Gateway Address
lineinfile:
path: '{{ network_conf_file }}'
regexp: '^GATEWAY='
line: 'GATEWAY={{ gw_address }}'

### roles -> vm-deploy -> defaults -> main.yml
- All of the variables reside here including "{{ hostname }}.{{ domain }}"

你离得太近了!诀窍是观察到剧本实际上是一个list的剧本(即{"hosts": "...", "tasks": []}的yaml对象(,当剧本开始时,后续剧本的目标不必存在——大概正是因为这个原因。因此:

- hosts: localhost
roles: 
- vm-deploy
gather_facts: no
connection: local
# or wherever you were executing this -- it wasn't obvious from your question
post_tasks:
- name: Add host to group 'just_created'
add_host:
name: '{{ hostname }}.{{ domain }}'
groups: just_created
- hosts: just_created
tasks:
- debug:
msg: hello from the newly created {{ inventory_hostname }}

相关内容

最新更新