How to get a value from hostvars in Ansible? - amazon-web-services

I can run EC2 instances using the following code. The Public DNSs (IPs) will be in demogroup .
- hosts: localhost
gather_facts: no
vars_files:
- variables/vars.yml
- variables/encrypt-iam-account.yml
tasks:
- name: provision CentOS VM (EC2)
.
.
.
- name: add hosts to inventory **********
add_host:
hostname: '{{ item.public_ip }}'
groupname: demogroup
ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
ansible_ssh_private_key_file: keypair-for-ansible.pem
loop: '{{ ec2.instances }}'
- hosts: demogroup
gather_facts: no
remote_user: centos
tasks:
- name: wait for SSH
.
.
.
- name: generate the key, x509 *******
expect:
command: openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
responses:
'Enter pass phrase for ca-key.pem': "12345"
'Country Name': "th"
'State or Province Name': "Bangkok"
'Locality Name': "Sukhumwit"
'Organization Name': "Kixxxx"
'Organizational Unit Name': "DevTeam"
'Common Name': "{{ hostvars[groups['demogroup']['xxxxx']] }}"
'Email Address': "sample#kixxxx.com"
no_log: false
register: mycmd
- debug:
var: mycmd
In the same YAML file, I want to get each Public DNS in order to assign to 'Common Name'
At this line 'Common Name': "{{ hostvars[groups['demogroup']['xxxxx']] }}". How to get each Public DNS (IP) from demogroup ?
Thank you in advance.

Related

Use of module "sts_assume_role" under community.aws or amazon.aws collection

Getting below error while running a playbook by making use of module "sts_assume_role" under community.aws or amazon.aws collection which is already installed on ansible server.
# Note: These examples do not set authentication details, see the AWS Guide for details.
name: testing assume role
user: ec2-user
hosts: localhost
gather_facts: true
collections:
community.aws.sts_assume_role
tasks:enter code here
Name: assume role
local_action:
sts_assume_role:
role_arn: "arn:aws:iam::123456789:role/test_iam_role"
role_session_name: "MySession"
register: assumed_role
run_once: True
Use the assumed role above to tag an instance in account 123456789
- name: sts token
local_action:
sts_assume_role:
aws_access_key: "{{ assumed_role.sts_creds.access_key }}"
aws_secret_key: "{{ assumed_role.sts_creds.secret_key }}"
security_token: "{{ assumed_role.sts_creds.session_token }}"
run_once: True
- Name: check current assume role
shell: aws sts get-caller-identity
PLease find attached picture for error.
Additional info:
Ansible version: 2.9.10
Boto3 version: 1.16.0
botocore version: 1.19.63
python version: 3.6.8

Ansible regex to replace the DNS address in Ubuntu netplan file

I would like to change DNS IP address from 192.168.86.14 to 192.168.86.16 in Ubuntu netplan yaml file:
link: ens3
addresses: [192.168.86.12/24]
gateway4: 192.168.86.1
nameservers:
addresses: [192.168.86.14,8.8.8.8,8.8.4.4]
Here is my ansible playbook:
- name: test
ansible.builtin.replace:
path: /etc/netplan/00-installer-config.yaml
regexp: '(addresses: \[)+192.168.86.14,'
replace: '\1192.168.86.16,'
My playbook doesn't change anything in the file. Tried to escape comma but doesn't match anything as well.
For some reason I need to make sure the IP address is between "addresses [" and "," so I can't just use the syntax like this :
- name: test
ansible.builtin.replace:
path: /etc/netplan/00-installer-config.yaml
regexp: '192.168.86.14'
replace: '192.168.86.16'
I am very new to Ansible, any help is appreciated!
The dictionaries are immutable in YAML. But, you can update dictionaries in Jinja2. Let's take a complete example of a netplan configuration file, e.g.
shell> cat 00-installer-config.yaml
network:
version: 2
renderer: networkd
ethernets:
ens3:
mtu: 9000
enp3s0:
link: ens3
addresses: [192.168.86.12/24]
gateway4: 192.168.86.1
nameservers:
addresses: [192.168.86.14,8.8.8.8,8.8.4.4]
Read the dictionary into a variable
- include_vars:
file: 00-installer-config.yaml
name: netplan_conf
gives
netplan_conf:
network:
ethernets:
enp3s0:
addresses:
- 192.168.86.12/24
gateway4: 192.168.86.1
link: ens3
nameservers:
addresses:
- 192.168.86.14
- 8.8.8.8
- 8.8.4.4
ens3:
mtu: 9000
renderer: networkd
version: 2
Create a template that updates the nameservers
shell> cat 00-installer-config.yaml.j2
{% set _dummy = netplan_conf.network.ethernets.enp3s0.nameservers.update({'addresses': _addresses}) %}
{{ netplan_conf|to_nice_yaml }}
The task below
- template:
src: 00-installer-config.yaml.j2
dest: 00-installer-config.yaml
vars:
_addresses: "{{ netplan_conf.network.ethernets.enp3s0.nameservers.addresses|
regex_replace('192.168.86.14', '192.168.86.16') }}"
will update the configuration file
shell> cat 00-installer-config.yaml
network:
ethernets:
enp3s0:
addresses:
- 192.168.86.12/24
gateway4: 192.168.86.1
link: ens3
nameservers:
addresses:
- 192.168.86.16
- 8.8.8.8
- 8.8.4.4
ens3:
mtu: 9000
renderer: networkd
version: 2

Access yaml list of dictionaries file with ansible

So I am trying take values from file, let's call it "test.yaml"
file looks like this (sorry for long output, but it is the shortest cut containing all patterns and structure):
---
results:
- failed: false
item: XXX.XX.XX.XX
invocation:
module_args:
validate_certs: false
vm_type: vm
show_tag: false
username: DOMAIN\domain-user
proxy_host:
proxy_port:
show_attribute: false
password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
port: XXX
folder:
hostname: XXX.XX.XX.XX
changed: false
virtual_machines:
- ip_address: XXX.XX.XX.XX
mac_address:
- XX:XX:XX:aa:XX:XX
uuid: XXXX-XX-XX-XXXX-XXXXX
guest_fullname: Red Hat Enterprise Linux X (XX-bit)
moid: vm-XXX
folder: "/DOMAIN-INTERXION/vm"
cluster:
attributes: {}
power_state: poweredOn
esxi_hostname: esx.hostname
tags: []
guest_name: VMnameXX
vm_network:
XX:XX:XX:aa:XX:XX:
ipv6:
- XX::XXX:XX:XXXX
ipv4:
- XXX.XX.XX.XX
I would like, for example to have something like:
results.invocation.virtual_machines.ip_address
results.invocation.module_args.user_name
I tried all kind of stuff but it doesn't work :)
last attempt is this:
---
- name: demo how register works
hosts: localhost
tasks:
- name: Include all .json and .jsn files in vars/all and all nested directories (2.3)
include_vars:
file: test.yml
name: vm
- name: debug
debug:
msg: "{{ item.0.item }}"
with_subelements:
- "{{ vm.results }}"
- virtual_machines
register: subelement
following your structure and after fixing some errors:
results.invocation.virtual_machines.ip_address is results[0].virtual_machines[0].ip_address
and
results.invocation.module_args.user_name is results[0].invocation.module_args.username
(results and virtual_machines are arrays, write results[0] or results.0 is same)
so a sample of playbook doing job:
- name: vartest
hosts: localhost
tasks:
- name: Include all .json and .jsn files in vars/all and all nested directories (2.3)
include_vars:
file: test.yml
name: vm
- name: ip
set_fact:
ipadress: "{{ vm.results[0].virtual_machines[0].ip_address }}"
- name: username
set_fact:
username: "{{ vm.results[0].invocation.module_args.username }}"
- name: display
debug:
msg: "ip: {{ ipadress }} and username: {{ username }}"
result:
ok: [localhost] =>
msg: 'ip: XXX.XX.XX.XX and username: DOMAIN\domain-user'

vmware_tag_manager, list to string trouble

Playbook below seems to be having trouble running thru the list of VM names..
error is as follows:
(type string). If this does not look like what you expect, quote the entire
value to ensure it does not change.
fatal: [127.0.0.1]: FAILED! => {"changed": false, "msg": "Failed to find the managed object for [
then spits out the list separated with \name\
what am I doing wrong here?
- hosts: localhost
vars_prompt:
- name: vcenter_hostname
prompt: Please provide the vcenter server hostname.
private: no
- name: vcenter_username
prompt: Please provide the vcenter server username.
private: no
- name: vcenter_password
prompt: Please provide the password for the username.
unsafe: yes
private: yes
vars:
vm_name: "{{lookup('file', '/etc/ansible/lists/lab_common_backup.txt')}}"
tasks:
- name: vm_tag_add
vmware_tag_manager:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: no
tag_names:
- 'Labs: Common Backup'
object_name: "{{ vm_name }}"
object_type: VirtualMachine
state: remove
I was able to get this working by using .split(), the default delimiter for split is a space..
object_name: "{{ vm_name.split() }}"

Using aws_secret in ansible

I'm trying to retrieve password from aws secret manager using ansible 2.8 using lookup.
Below things are not working for me:
In .bashrc, I have exported region
Ansible Environment Variables in task
Setting up ansible variables in pre_tasks
- hosts: StagingApps
remote_user: staging
gather_facts: false
tasks:
- debug:
var: "{{ lookup('aws_secret', 'staging_mongodb_pass', region='us-east-1') }}"
msg: "{{ query('aws_secret', 'staging_mongodb_pass', region='us-east-1') }}"
environment:
region: 'us-east-1'
Error Message:
FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'aws_secret'. Error was a , original message: 'Requested entry (plugin_type: lookup plugin: aws_secret setting: region ) was not defined in configuration.'"}
below playbook has worked for me
- name: "register mongodb from secretsmanager"
shell: "aws secretsmanager get-secret-value --secret-id staging_mongodb"
register: mongodb_pass
delegate_to: 127.0.0.1
- set_fact:
mongodb_pass_dict: "{{ mongodb_pass.stdout | from_json | json_query('SecretString') }}"
- set_fact:
mongodb_pass_list: "{{ ['staging_mongodb'] | map('extract', mongodb_pass_dict) | list }}"
- set_fact:
mongodb_pass: "{{ mongodb_pass_list[0] }}"
- template:
src: application.properties.j2
dest: application.properties
mode: 0644
backup: yes
It looks like Ansible released this lookup plugin in a broken state. They have an issue and a PR open to fix it:
https://github.com/ansible/ansible/issues/54790
https://github.com/ansible/ansible/pull/54792
Very disappointing, as I've been waiting for this plugin for many months.