I am writing an ansible script to shutdown several VM's when they are not needed. I am able to do that when I know where the VM lives. The problem is that the VM could move around to different folders if it vmotions to a different host. According to the article below I need to know the folder of the VM which again could change. Not sure how to get the folder automatically. Is there a way to do this with Ansible and or Python then feed it into the script?
https://docs.ansible.com/ansible/latest/modules/vmware_guest_powerstate_module.html
- name: Set the state of a virtual machine to poweroff
vmware_guest_powerstate:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
folder: "/{{ datacenter_name }}/vm/my_folder"
name: "{{ guest_name }}"
state: powered-off
delegate_to: localhost
register: deploy
First get information about the VM using vmware_guest_info module and then pass the folder in the next task like so,
- name: Gather info about the vmware guest vm
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ datacenter_name }}"
validate_certs: no
name: "{{ guest_name }}"
delegate_to: localhost
register: vm_info
- name: Set the state of a virtual machine to poweroff
vmware_guest_powerstate:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
folder: "{{ vm_info['hw_folder']}}"
name: "{{ guest_name }}"
state: powered-off
delegate_to: localhost
register: deploy
Related
I am trying to be able to deploy multiple machines using a GOLD vm snapshot through ansible. I need it to be like this:
- name: Creating Virtual Machine as requested.
azure_rm_virtualmachine:
resource_group: "{{ virtualMachineRG }}"
name: "{{ virtualMachineName }}"
vm_size: "{{ virtualMachineSize }}"
location: "{{ location }}"
managed_disk_type: "{{ managed_Disk_Type }}"
storage_account: "{{ storageAccount }}"
os_type: "{{ os_type }}"
image: "{{image}}"
os_disk_size_gb: "{{ os_disk_size_gb }}"
admin_username: "{{ adminUsername }}"
admin_password: "{{ adminPassword }}"
network_interfaces: "{{ virtualMachineName }}-nic"
I need the IMAGE or the entire disk to work similarly to creating a snapshot then creating a VM off the snapshot OR Create a clone of a managed disk and using that instead of the basic IMAGE of windows 10. This would be like having a snapshot that needs the same thing for 10 different VMs based on the request so its not the image that I would need but the GOLD Snapshot in place of the image which has operating system and everything installed. Is this doable? I have tried everything I can find through just searches and ansible documentation. This will deploy a new VM from the snapshot of the GOLD managed disk and this gets updated regularly and is set to the machine that controls the GOLD snapshot.
We have a Playbook to create a Linux VM in Mincrosoft azure following a role to do post install things like installing some applications packages. Our playbook is running fine and able to deploy the VM in azure, However the second role which is to configure the VM after deployment is not running on the VM as, we are not able to pass the vm (IP/Hostname) to the second role.
What we wan to achieve is to deploy VM using ansible playbook/role, Run the roles after the machine is deployed to configure the business specific tasks.
Path:
Below is the path where all ansible plays and roles are coming. here roles folders contains all the post install tasks, i believe there will be a better way there Keeping the test-creatVM-sur.yml there itself within role but as a learner i'm bit struggling..
$ ls -l /home/azure1/ansible_Dir
-rw-r-----. 1 azure1 hal 1770 Sep 17 17:03 test-creatVM-sur.yml
-rw-r-----. 1 azure1 hal 320 Sep 17 22:30 licence-test.yml
drwxr-x---. 6 azure1 hal 4096 Sep 17 21:46 roles
My main Play file:
$ cat licence-test.yml
---
- name: create vm
hosts: localhost
connection: local
become: yes
become_method: sudo
become_user: root
vars:
Res_Group: "some_value"
LOCATION: "some_value"
VNET: "some_value"
IMAGE_ID: "some_value"
SUBNET: "some_value"
KEYDATA: "some_value"
DISK_SIZE: 100
DISK_TYPE: Premium_LRS
tasks:
- name: include task
include_tasks:
file: creattest_VM.yml <-- This portion works fine
- hosts: "{{ VM_NAME }}" <-- this portion does not work as it's not able to fetch the newly created VM name.
become: yes
become_method: sudo
become_user: root
roles:
- azure_license
...
Play (test-creatVM-sur.yml) which created VM in azure is below:
---
- name: Create Network Security Group that allows SSH
azure_rm_securitygroup:
resource_group: "{{ Res_Group }}"
location: "{{ LOCATION }}"
name: "{{ VM_NAME }}-nsg"
rules:
- name: SSH
protocol: Tcp
destination_port_range: 22
access: Allow
priority: 100
direction: Inbound
- name: Create virtual network interface card
azure_rm_networkinterface:
resource_group: "{{ Res_Group }}"
location: "{{ LOCATION }}"
name: "{{ VM_NAME }}-nic1"
subnet: "{{ SUBNET }}"
virtual_network: "{{ VNET }}"
security_group: "{{ VM_NAME }}-nsg"
enable_accelerated_networking: True
public_ip: no
state: present
- name: Create VM
azure_rm_virtualmachine:
resource_group: "{{ Res_Group }}"
location: "{{ LOCATION }}"
name: "{{ VM_NAME }}"
vm_size: Standard_D4s_v3
admin_username: automation
ssh_password_enabled: false
ssh_public_keys:
- path: /home/automation/.ssh/authorized_keys
key_data: "{{ KEYDATA }}"
network_interfaces: "{{ VM_NAME }}-nic1"
os_disk_name: "{{ VM_NAME }}-osdisk"
managed_disk_type: "{{ DISK_TYPE }}"
os_disk_caching: ReadWrite
os_type: Linux
image:
id: "{{ IMAGE_ID }}"
publisher: redhat
plan:
name: rhel-lvm78
product: rhel-byos
publisher: redhat
- name: Add disk to VM
azure_rm_manageddisk:
name: "{{ VM_NAME }}-datadisk01"
location: "{{ LOCATION }}"
resource_group: "{{ Res_Group }}"
disk_size_gb: "{{ DISK_SIZE }}"
managed_by: "{{ VM_NAME }}"
- name: "wait for 3 Min"
pause:
minutes: 3
...
Edit:
I managed to define the vars into a separated name_vars under include_vars.
---
- name: create vm
hosts: localhost
connection: local
become: yes
become_method: sudo
become_user: root
tasks:
- include_vars: name_vars.yml
- include_tasks: creattest_VM.yml
- name: Apply license hardening stuff
hosts: "{{ VM_NAME }}"
become: yes
become_method: sudo
become_user: root
roles:
- azure_license
...
It works after doing some dirty hack but that doesn't looks proper as i am creating an invetory test to putting there VM_NAME as well as an extra variable with -e below.
$ ansible-playbook -i test -e VM_NAME=mylabhost01.hal.com licence-test.yml -k -u my_user_id
Any help will be much appreciated.
I created an Ansible-Playbook to install AKS on Ubuntu .
Flowing microsoft tutorial
https://learn.microsoft.com/en-us/azure/ansible/ansible-create-configure-aks
Yml file:
- name: Create Azure Kubernetes Service
hosts: localhost
connection: local
vars:
resource_group: myResourceGroup
location: eastus
aks_name: myAKSCluster
username: azureuser
ssh_key: "your_ssh_key"
client_id: "your_client_id"
client_secret: "your_client_secret"
tasks:
- name: Create resource group
azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
- name: Create a managed Azure Container Services (AKS) cluster
azure_rm_aks:
name: "{{ aks_name }}"
location: "{{ location }}"
resource_group: "{{ resource_group }}"
dns_prefix: "{{ aks_name }}"
linux_profile:
admin_username: "{{ username }}"
ssh_key: "{{ ssh_key }}"
service_principal:
client_id: "{{ client_id }}"
client_secret: "{{ client_secret }}"
agent_pool_profiles:
- name: default
count: 2
vm_size: Standard_D2_v2
tags:
Environment: Production
But it given error:
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Unsupported
kubernetes version. Expected one of [u'1.11.9', u'1.11.8', u'1.10.12',
u'1.10.13', u'1.12. 8', u'1.13.5', u'1.12.7'] but got None"}
Then i switched to another Kubernetes Service which its version is 1.12.8
But it still given this error.
How can i fix it? Or how can i change the version of kubernetes service ?
you need to specify kubernetes_version according to the module wiki. this is also what the error text is telling you
- name: Create a managed Azure Container Services (AKS) cluster
azure_rm_aks:
name: "{{ aks_name }}"
location: "{{ location }}"
resource_group: "{{ resource_group }}"
dns_prefix: "{{ aks_name }}"
kubernetes_version: 1.13.5
xxx
How can you get the private IP for a VM in am Azure scale set in Ansible?
None of these seem to have the info:
azure_rm_virtualmachinescaleset_facts
azure_rm_virtualmachinescalesetinstance_facts
azure_rm_virtualmachine_facts
azure_rm_subnet_facts
azure_rm_networkinterface_facts
in order to get the IPs of my ScaleSet instances, I take the little detour via the PrivateDNS of Azure with auto-registration. As soon as the machines are available, they will be updated in the DNS.
Code Snippet:
- name: Fetch IPs from ScaleSet instances
hosts: localhost
connection: local
vars:
resource_group: "test-lbs1"
vmss_name: "vmss"
zone_name: "my.private.dns.zone"
tasks:
#############################################
# Fetch all Instances from Scaleset
#############################################
- name: List all of the instances
azure.azcollection.azure_rm_virtualmachinescalesetinstance_info:
resource_group: "{{ resource_group }}"
vmss_name: "{{ vmss_name }}"
register: __instances
#############################################
# Fetch IP from PrivateDNS Record
#############################################
- name: Get network interfaces
azure.azcollection.azure_rm_privatednsrecordset_info:
resource_group: "{{ resource_group }}"
zone_name: "{{ zone_name }}"
relative_name: "{{ item.computer_name }}"
record_type: A
with_items: "{{ __instances.instances }}"
register: __network_ips
- debug:
var: __network_ips
I use gitlab-ci for the automated tests. Now i extended it to allow for review apps deployed on digitalocean droplets via an ansible playbook.
This is working very well, but i need to get a variable from ansible to the .gitlab-ci - i can't find a way todo it.
.gitlab-ci.yml
Deploy for Review:
before_script: []
stage: review
script: 'cd /home/playbooks/oewm/deployment && ansible-playbook -i inventories/review --extra-vars "do_name=$CI_PIPELINE_ID api_git_branch=$CI_BUILD_REF_NAME" digitalocean.yml'
environment:
name: review/$CI_BUILD_REF_NAME
url: http://$IP_FROM_ANSIBLE
on_stop: "Stop Review"
only:
- branches
when: manual
tags:
- deploy
the relevant parts from the playbook:
- name: Create DO Droplet
delegate_to: localhost
local_action:
module: digital_ocean
state=present
command=droplet
name=review-{{ do_name }}
api_token={{ do_token }}
region_id={{ do_region }}
image_id={{ do_image }}
size_id={{ do_size }}
ssh_key_ids={{ do_ssh }}
wait_timeout=500
register: my_droplet
- name: print info about droplet
delegate_to: localhost
local_action:
module: debug
msg="ID is {{ my_droplet.droplet.id }} IP is {{ my_droplet.droplet.ip_address }}"
So how can i get the droplet ID and IP to gitlab-ci?
(The ID is needed for the later Stop action, the IP to be viewed to the developer)
Ansible is a YAML-configured scripting tool itself and probably nearly turing complete automation scripting environment itself. Why not have it write a file called "./ip_address.sh" somewhere, and then dot-include that .sh into your gitlab CI?
The very top level of all this, in .gitlab-ci.yml would have this:
script:
- ./run_ansible.sh ./out/run_file_generated_from_ansible.sh
- . ./out/run_file_generated_from_ansible.sh
- echo $IP_FROM_ANSIBLE
environment:
name: review/$CI_BUILD_REF_NAME
url: http://$IP_FROM_ANSIBLE
on_stop: "Stop Review"
Writing the two shell scripts above is left as an exercise to the reader. The magic happens inside the Ansible "playbook" which is really just a script, where YOU "export a variable to disk" with filename "./out/run_file_generate_from_ansible.sh".
What you didn't make clear is what you need to do in Gitlab-CI with that variable and where it ends up, and what happens next. So above, I'm just showing a way you could "export" via a temporary on-disk-file, an IP address.
You could save that exported value as an artifact and capture it in other stages as well, so such "artifact-exports" can be passed among stages, if you put them all in a directory called ./out and then declare an artifacts statement in gitlab-ci.yml.
I finally got the setup to run. My solution uses AWS Route53 for dynamic hostname generation. (A problem i ignored to long - i needed hostnames for the different review apps)
Step 1:
Build the hostname dynamicly. For that i used $CI_PIPELINE_ID I created a subdomain on Route53 for this example we call it review.mydomain.com. The Ansible Playbook takes the IP from the create_droplet and creates a record on Route53 with the Pipeline id. 1234.review.mydomain.com.
Now my .gitlab-ci.yml knows this hostname (because it can build it anytime) - no more need to get the Digitalocean droplet IP out of the ansible skript.
Step 2:
After review - the user should be able to stop/destroy the droplet. For this i need the droplet id i get when this droplet is created.
But the destroy is a different playbook, which will run later - invoked by a developer.
So i need a way to store variables somewhere.
But wait, now that i know which host it is, i can just create a facts file on this host, storing the ID for me. when i need to destroy the host, ansible provides me with the facts, and i know the ID.
in the playbook it looks like this:
Role: digitalocean
---
- name: Create DO Droplet
delegate_to: localhost
local_action:
module: digital_ocean
state=present
command=droplet
name=oewm-review-{{ do_name }}
api_token={{ do_token }}
region_id={{ do_region }}
image_id={{ do_image }}
size_id={{ do_size }}
ssh_key_ids={{ do_ssh }}
wait_timeout=500
register: my_droplet
- name: print info about droplet
delegate_to: localhost
local_action:
module: debug
msg="DO-ID:{{ my_droplet.droplet.id }}"
- name: print info about droplet
delegate_to: localhost
local_action:
module: debug
msg="DO-IP:{{ my_droplet.droplet.ip_address }}"
# DNS
- name: Get existing host information
route53:
command: get
zone: "{{ r53_zone }}"
record: "{{ do_name }}.review.mydomain.com"
type: A
aws_access_key: "{{ r53_access_key }}"
aws_secret_key: "{{ r53_secret_key }}"
register: currentip
- name: Add DNS Record for Web-Application
route53:
command: create
zone: "{{ r53_zone }}"
record: "{{ do_name }}.review.mydomain.com"
type: A
ttl: 600
value: "{{ my_droplet.droplet.ip_address }}"
aws_access_key: "{{ r53_access_key }}"
aws_secret_key: "{{ r53_secret_key }}"
when: currentip.set.value is not defined
- name: Add DNS Record for API
route53:
command: create
zone: "{{ r53_zone }}"
record: "api.{{ do_name }}.review.mydomain.com"
type: A
ttl: 600
value: "{{ my_droplet.droplet.ip_address }}"
aws_access_key: "{{ r53_access_key }}"
aws_secret_key: "{{ r53_secret_key }}"
when: currentip.set.value is not defined
- name: Add new droplet to host group
add_host:
hostname: "{{ my_droplet.droplet.ip_address }}"
groupname: api,web-application
ansible_user: root
api_domain: "api.{{ do_name }}.review.mydomain.com"
app_domain: "{{ do_name }}.review.mydomain.com"
- name: Wait until SSH is available on {{ my_droplet.droplet.ip_address }}
local_action:
module: wait_for
host: "{{ my_droplet.droplet.ip_address }}"
port: 22
delay: 5
timeout: 320
state: started
Playbook digitalocean.yml:
---
- name: Launch DO Droplet
hosts: all
run_once: true
gather_facts: false
roles:
- digitalocean
- name: Store Facts
hosts: api
tasks:
- name: Ensure facts directory exists
file:
path: "/etc/ansible/facts.d"
state: directory
- name: store variables on host for later fact gathering
template:
src={{ playbook_dir }}/roles/digitalocean/templates/digitalocean.fact.js2
dest="/etc/ansible/facts.d/digitalocean.fact"
mode=0644
- name: Deploy
hosts: api
roles:
- deployroles
Playbook digitalocean_destroy.yml:
- name: Add Host to Inventory
hosts: all
vars:
r53_zone: review.mydomain.com
r53_access_key: "xxxx"
r53_secret_key: "xxxx"
tasks:
- name: Get existing DNS host information
route53:
command: get
zone: "{{ r53_zone }}"
record: "{{ do_name }}.review.mydomain.com"
type: A
aws_access_key: "{{ r53_access_key }}"
aws_secret_key: "{{ r53_secret_key }}"
register: currentip
- name: Remove DNS Record for Web-Application
route53:
command: delete
zone: "{{ r53_zone }}"
record: "{{ do_name }}.review.mydomain.com"
type: A
ttl: 600
value: "{{ my_droplet.droplet.ip_address }}"
aws_access_key: "{{ r53_access_key }}"
aws_secret_key: "{{ r53_secret_key }}"
when: currentip.set.value is defined
- name: Remove DNS Record for API
route53:
command: delete
zone: "{{ r53_zone }}"
record: "api.{{ do_name }}.review.mydomain.com"
type: A
ttl: 600
value: "{{ my_droplet.droplet.ip_address }}"
aws_access_key: "{{ r53_access_key }}"
aws_secret_key: "{{ r53_secret_key }}"
when: currentip.set.value is defined
- name: Add droplet to host group
add_host:
hostname: "{{ do_name }}.review.mydomain.com"
groupname: api,web-application
ansible_user: root
- name: Digitalocean
hosts: api
vars:
do_token: xxxxx
tasks:
- name: Delete Droplet
delegate_to: localhost
local_action:
module: digital_ocean
state=deleted
command=droplet
api_token={{ do_token }}
id="{{ ansible_local.digitalocean.DO_ID }}"
relevant parts from .gitlab-ci.yml:
Deploy for Review:
before_script: []
stage: review
script:
- 'cd /home/playbooks/myname/deployment && ansible-playbook -i inventories/review --extra-vars "do_name=$CI_PIPELINE_ID api_git_branch=$CI_BUILD_REF_NAME" digitalocean.yml'
environment:
name: review/$CI_BUILD_REF_NAME
url: http://$CI_PIPELINE_ID.review.mydomain.com
on_stop: "Stop Review"
only:
- branches
when: manual
tags:
- deploy
Stop Review:
before_script: []
stage: review
variables:
GIT_STRATEGY: none
script:
- 'cd /home/playbooks/myname/deployment && ansible-playbook -i inventories/review --extra-vars "do_name=$CI_PIPELINE_ID" digitalocean_destroy.yml'
when: manual
environment:
name: review/$CI_BUILD_REF_NAME
action: stop
only:
- branches
tags:
- deploy
# STAGING
Deploy to Staging:
before_script: []
stage: staging
script:
- 'cd /home/playbooks/myname/deployment && ansible-playbook -i inventories/staging --extra-vars "api_git_branch=$CI_BUILD_REF_NAME" deploy.yml'
environment:
name: staging
url: https://staging.mydomain.com
when: manual
tags:
- deploy