Undefined variable

Can anyone shed some light into this?

  1. I’m using the aws_ec2 plugin
  2. I can launch an ec2 instance successfully and run commands post launch

My issue comes in when I reference the {{ tags[‘Name’] }} to pull from AWS tag Name from the newly created instance. I can see all the tag key/value info from the when I add the new instance to the host group; however, for some reason it fails as soon as it hits the new play/task to configure the hostname based on the aws ec2 tag Name. I’m guessing Ansible is not carrying over the variables in the add_host to host group.

fatal: FAILED! => {“msg”: “The task includes an option with an undefined variable. The error was: ‘tags’ is undefined\n\nThe error appears to be in ‘/etc/ansible/roles/component_baselines/hostname/tasks/main.yml’: line 12, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: ‘Update system name’\n ^ here\n”}

Here’s a snippet of the tail end of the ec2 create playbook:

register: new_ec2

  • name: ‘Add new instance to host group’
    add_host:
    hostname: “{{ item.private_ip_address }}”
    groupname: ‘launched’
    loop: “{{ new_ec2.instances }}”

  • name: ‘Wait for SSH to come up’
    delegate_to: “{{ item.private_ip_address }}”
    wait_for_connection:
    delay: 120
    timeout: 480
    loop: “{{ new_ec2.instances }}”

  • name: ‘Run post-launch baseline configuration on instance’
    hosts: ‘launched’
    gather_facts: no
    become: yes

roles:

  • ‘component_baselines/hostname’

Details of the hostname role being called:

  • name: ‘Gather current system name’
    ansible.builtin.setup:

  • name: ‘Update system name’
    shell: >
    hostnamectl set-hostname
    {{ tags[‘Name’] }}.{{ domain[‘fqdn’] }} --static --transient &&
    hostnamectl set-hostname {{ tags[‘Name’] }}.{{ domain[‘fqdn’] }} --pretty
    when: “tags[‘Name’] != ansible_facts[‘hostname’]”

  • name: ‘Update sysconfig File’
    template:
    src: ‘network.j2’
    dest: ‘/etc/sysconfig/network’
    owner: ‘root’
    group: ‘root’
    mode: ‘0644’
    register: taskresult
    notify: ‘Restart systemd-hostnamed’
    when: “tags[‘Name’] != ansible_facts[‘hostname’]”

You say, “I can see all the tag key/value info from the when I add the new instance to the host group;” Okay, but we can’t. Can you show us?

Or perhaps more briefly, at what line in your code do you expect Ansible to become aware of a variable called “tags”?

Do you need to reference the tags inside new_ec2.instances ?

Walter

Hi Walter,

Thanks for the reply! Yes, that’s correct. How can I reference the tags inside the new_ec2_instances?
Specifically, I want to pull the tag called Name to use in this next set of play once the new instance is launched and up and running. Below is where i expect to use the name tag to set the hostname on the server:

  • name: ‘Run post-launch baseline configuration on instance’
    hosts: ‘launched’
    gather_facts: no
    become: yes

tasks:

  • name: ‘Update system name’
    shell: >
    hostnamectl set-hostname
    {{ tags.Name }}.{{ domain[‘fqdn’] }} --static --transient &&
    hostnamectl set-hostname {{ tags.Name }}.{{ domain[‘fqdn’] }} --pretty

Here’s more of the output results, if needed:

TASK [Launch instance] ******************************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:96
redirecting (type: modules) ansible.builtin.ec2_instance to community.aws.ec2_instance
redirecting (type: modules) community.aws.ec2_instance to amazon.aws.ec2_instance
[DEPRECATION WARNING]: The purge_tags parameter currently defaults to False. For consistency across the collection, this default value will change to True in release 5.0.0. This
feature will be removed from amazon.aws in version 5.0.0. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
changed: [127.0.0.1] => {“changed”: true, “instance_ids”: [“i-005f7ce”], “instances”: [{“ami_launch_index”: 0, “architecture”: “x86_64”, “block_device_mappings”: [{“device_name”: “/dev/sda1”, “ebs”: {“attach_time”: “2022-08-22T16:44:38+00:00”, “delete_on_termination”: false, “status”: “attaching”, “volume_id”: “vol-0488a0”}}], “capacity_reservation_specification”: {“capacity_reservation_preference”: “open”}, “client_token”: “64c1d4b064f”, “cpu_options”: {“core_count”: 1, “threads_per_core”: 2}, “ebs_optimized”: true, “ena_support”: true, “enclave_options”: {“enabled”: false}, “hibernation_options”: {“configured”: false}, “hypervisor”: “xen”, “iam_instance_profile”: {“arn”: “arn:aws-us:iam::23489:instance-profile/Ansible”, “id”: “AIPAXKK”}, “image_id”: “ami-0beac6”, “instance_id”: “i-005f7ce”, “instance_type”: “t3a.medium”, “key_name”: “test”, “launch_time”: “2022-08-22T16:44:37+00:00”, “maintenance_options”: {“auto_recovery”: “default”}, “metadata_options”: {“http_endpoint”: “enabled”, “http_protocol_ipv6”: “disabled”, “http_put_response_hop_limit”: 1, “http_tokens”: “optional”, “instance_metadata_tags”: “disabled”, “state”: “pending”}, “monitoring”: {“state”: “disabled”}, “network_interfaces”: [{“attachment”: {“attach_time”: “2022-08-22T16:44:37+00:00”, “attachment_id”: “eni-attach-03c0fe9”, “delete_on_termination”: true, “device_index”: 0, “network_card_index”: 0, “status”: “attaching”}, “description”: “”, “groups”: [{“group_id”: “sg-34”, “group_name”: “INT User Data”}], “interface_type”: “interface”, “ipv6_addresses”: , “mac_address”: “06”, “network_interface_id”: “eni-0cac24c”, “owner_id”: “23489”, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_ip_address”: “10.1.4.3”, “private_ip_addresses”: [{“primary”: true, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_ip_address”: “10.1.4.3”}], “source_dest_check”: true, “status”: “in-use”, “subnet_id”: “subnet-f5b”, “vpc_id”: “vpc-dbc”}], “placement”: {“availability_zone”: “us-west-1a”, “group_name”: “”, “tenancy”: “default”}, “platform_details”: “Red Hat Enterprise Linux”, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_dns_name_options”: {“enable_resource_name_dns_a_record”: false, “enable_resource_name_dns_aaaa_record”: false, “hostname_type”: “ip-name”}, “private_ip_address”: “10.1.4.3”, “product_codes”: , “public_dns_name”: “”, “root_device_name”: “/dev/sda1”, “root_device_type”: “ebs”, “security_groups”: [{“group_id”: “sg-34”, “group_name”: “INT User Data”}], “source_dest_check”: true, “state”: {“code”: 0, “name”: “pending”}, “state_transition_reason”: “”, “subnet_id”: “subnet-f5b”, “tags”: {“Application Group”: “CORE”, “Application System”: “Development Team”, “Backupset”: “true”, “CST Start/Stop Schedule”: “0700;1900;Weekdays”, “CostCenter”: “Dev”, “Description”: “Evaluation Server”, “Environment”: “DEV”, “Name”: “test8”, “OS”: “RHEL”, “OS Version”: “8”, “Owner”: “Development Center”, “Patch Group”: “Normal”, “Sub Environment”: “Development”: “hvm”, “vpc_id”: “vpc-dbc”}], “spec”: {“BlockDeviceMappings”: , “ClientToken”: “64c1d4b”, “DisableApiTermination”: true, “EbsOptimized”: true, “IamInstanceProfile”: {“Arn”: “arn:aws-us:iam::23489:instance-profile/Ansible”}, “ImageId”: “ami-0beac”, “InstanceType”: “t3a.medium”, “KeyName”: “test”, “MaxCount”: 1, “MinCount”: 1, “NetworkInterfaces”: [{“AssociatePublicIpAddress”: false, “DeviceIndex”: 0, “Groups”: [“sg-34”], “SubnetId”: “subnet-f5b”}], “TagSpecifications”: [{“ResourceType”: “volume”, “Tags”: [{“Key”: “Application Group”, “Value”: “CORE”}, {“Key”: “Application System”, “Value”: “Development Team”}, {“Key”: “Backupset”, “Value”: “true”}, {“Key”: “CST Start/Stop Schedule”, “Value”: “0700;1900;Weekdays”}, {“Key”: “Description”, “Value”: “Evaluation Server”}, {“Key”: “CostCenter”, “Value”: “Dev”}, {“Key”: “Environment”, “Value”: “DEV”}, {“Key”: “Name”, “Value”: “test8”}, {“Key”: “OS”, “Value”: “RHEL”}, {“Key”: “OS Version”, “Value”: “8”}, {“Key”: “Owner”, “Value”: “Develoment Center”}, {“Key”: “Patch Group”, “Value”: “Normal”}, {“Key”: “Sub Environment”, “Value”: “Development”}, {“Key”: “Type”, “Value”: “Eval”}]}, {“ResourceType”: “instance”, “Tags”: [{“Key”: “Application Group”, “Value”: “CORE”}, {“Key”: “Application System”, “Value”: “Development Team”}, {“Key”: “Backupset”, “Value”: “true”}, {“Key”: “CST Start/Stop Schedule”, “Value”: “0700;1900;Weekdays”}, {“Key”: “Description”, “Value”: “A1 Operations Evaluation Server”}, {“Key”: “CostCenter”, “Value”: “Dev”}, {“Key”: “Environment”, “Value”: “DEV”}, {“Key”: “Name”, “Value”: “test8”}, {“Key”: “OS”, “Value”: “RHEL”}, {“Key”: “OS Version”, “Value”: “8”}, {“Key”: “Owner”, “Value”: “Development Center”}, {“Key”: “Patch Group”, “Value”: “Normal”}, {“Key”: “Sub Environment”, “Value”: “Development”}, {“Key”: “Type”, “Value”: “Eval”}]}]}}

TASK [Add new instance to host group] ***************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:209
creating host via ‘add_host’: hostname=test8
ok: [127.0.0.1] => (item={‘ami_launch_index’: 0, ‘image_id’: ‘ami-0beac6b6’, ‘instance_id’: ‘06-005sd3sfs’, ‘instance_type’: ‘t3a.medium’, ‘key_name’: ‘test’, ‘launch_time’: ‘2022-08-22T16:44:37+00:00’, ‘monitoring’: {‘state’: ‘disabled’}, ‘placement’: {‘availability_zone’: ‘us-west-1a’, ‘group_name’: ‘’, ‘tenancy’: ‘default’}, ‘private_dns_name’: ‘ip-10-1-4-1x.us-west-1.compute.internal’, ‘private_ip_address’: ‘10.1.4.1x’, ‘product_codes’: , ‘public_dns_name’: ‘’, ‘state’: {‘code’: 0, ‘name’: ‘pending’}, ‘state_transition_reason’: ‘’, ‘subnet_id’: ‘subnet-f5b’, ‘vpc_id’: ‘vpc-dbc5’, ‘architecture’: ‘x86_64’, ‘block_device_mappings’: [{‘device_name’: ‘/dev/sda1’, ‘ebs’: {‘attach_time’: ‘2022-08-22T16:44:38+00:00’, ‘delete_on_termination’: False, ‘status’: ‘attaching’, ‘volume_id’: ‘vol-0488sdfec’}}], ‘client_token’: ‘64c1d49a1d’, ‘ebs_optimized’: True, ‘ena_support’: True, ‘hypervisor’: ‘xen’, ‘iam_instance_profile’: {‘arn’: ‘arn:aws-usv:iam::23489:instance-profile/Ansible’, ‘id’: ‘AI’}, ‘network_interfaces’: [{‘attachment’: {‘attach_time’: ‘2022-08-22T16:44:37+00:00’, ‘attachment_id’: ‘eni-attach-03c0fe’, ‘delete_on_termination’: True, ‘device_index’: 0, ‘status’: ‘attaching’, ‘network_card_index’: 0}, ‘description’: ‘’, ‘groups’: [{‘group_name’: ‘User group’, ‘group_id’: ‘sg-34’}], ‘ipv6_addresses’: , ‘mac_address’: ‘06’, ‘network_interface_id’: ‘eni-0cac24cf’, ‘owner_id’: ‘23489’, ‘private_dns_name’: ‘ip-10-1-4-3.us-west-1.compute.internal’, ‘private_ip_address’: ‘10.1.4.3’, ‘private_ip_addresses’: [{‘primary’: True, ‘private_dns_name’: ‘ip-10-1-4-3.us-west-1.compute.internal’, ‘private_ip_address’: ‘10.1.4.3’}], ‘source_dest_check’: True, ‘status’: ‘in-use’, ‘subnet_id’: ‘subnet-f5bsdfs’, ‘vpc_id’: ‘vpc-dbc5’, ‘interface_type’: ‘interface’}], ‘root_device_name’: ‘/dev/sda1’, ‘root_device_type’: ‘ebs’, ‘security_groups’: [{‘group_name’: ‘User group’, ‘group_id’: ‘sg-34’}], ‘source_dest_check’: True, ‘tags’: {‘OS’: ‘RHEL’, ‘Owner’: ‘Development Center’, ‘Environment’: ‘DEV’, ‘Sub Environment’: ‘Development’, ‘CostCenter’: ‘Dev’, ‘Backupset’: ‘true’, ‘Application System’: ‘Development Team’, ‘OS Version’: ‘8’, ‘Application Group’: ‘CORE’, ‘Patch Group’: ‘Normal’, ‘Description’: ‘Evaluation Server’, ‘Name’: ‘test8’, ‘CST Start/Stop Schedule’: ‘0700;1900;Weekdays’, ‘Type’: ‘Eval’}, ‘virtualization_type’: ‘hvm’, ‘cpu_options’: {‘core_count’: 1, ‘threads_per_core’: 2}, ‘capacity_reservation_specification’: {‘capacity_reservation_preference’: ‘open’}, ‘hibernation_options’: {‘configured’: False}, ‘metadata_options’: {‘state’: ‘pending’, ‘http_tokens’: ‘optional’, ‘http_put_response_hop_limit’: 1, ‘http_endpoint’: ‘enabled’, ‘http_protocol_ipv6’: ‘disabled’, ‘instance_metadata_tags’: ‘disabled’}, ‘enclave_options’: {‘enabled’: False}, ‘platform_details’: ‘Red Hat Enterprise Linux’, ‘usage_operation’: ‘RunInstances:0010’, ‘usage_operation_update_time’: ‘2022-08-22T16:44:37+00:00’, ‘private_dns_name_options’: {‘hostname_type’: ‘ip-name’, ‘enable_resource_name_dns_a_record’: False, ‘enable_resource_name_dns_aaaa_record’: False}, ‘maintenance_options’: {‘auto_recovery’: ‘default’}}) => {“add_host”: {“groups”: [“launched”], “host_name”: “test8”, “host_vars”: {}}, “ansible_loop_var”: “item”, “changed”: false, “item”: {“ami_launch_index”: 0, “architecture”: “x86_64”, “block_device_mappings”: [{“device_name”: “/dev/sda1”, “ebs”: {“attach_time”: “2022-08-22T16:44:38+00:00”, “delete_on_termination”: false, “status”: “attaching”, “volume_id”: “vol-0488sdfec2f4e9e6”}}], “capacity_reservation_specification”: {“capacity_reservation_preference”: “open”}, “client_token”: “64c1d4b064fa418d99eeca4aa44c7a1d”, “cpu_options”: {“core_count”: 1, “threads_per_core”: 2}, “ebs_optimized”: true, “ena_support”: true, “enclave_options”: {“enabled”: false}, “hibernation_options”: {“configured”: false}, “hypervisor”: “xen”, “iam_instance_profile”: {“arn”: “arn:aws-us-:iam::23489:instance-profile/Ansible”, “id”: “AIPAXKKA2BWLPEG6LE23X”}, “image_id”: “ami-0beac6b6ed4da44ce”, “instance_id”: “06-005sd3sfs0a0d9”, “instance_type”: “t3a.medium”, “key_name”: “test”, “launch_time”: “2022-08-22T16:44:37+00:00”, “maintenance_options”: {“auto_recovery”: “default”}, “metadata_options”: {“http_endpoint”: “enabled”, “http_protocol_ipv6”: “disabled”, “http_put_response_hop_limit”: 1, “http_tokens”: “optional”, “instance_metadata_tags”: “disabled”, “state”: “pending”}, “monitoring”: {“state”: “disabled”}, “network_interfaces”: [{“attachment”: {“attach_time”: “2022-08-22T16:44:37+00:00”, “attachment_id”: “eni-attach-03c0fe95d6d45e0a2”, “delete_on_termination”: true, “device_index”: 0, “network_card_index”: 0, “status”: “attaching”}, “description”: “”, “groups”: [{“group_id”: “sg-347”, “group_name”: “User Data”}], “interface_type”: “interface”, “ipv6_addresses”: , “mac_address”: “06”, “network_interface_id”: “eni-0cac24c770”, “owner_id”: “23489”, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_ip_address”: “10.1.4.3”, “private_ip_addresses”: [{“primary”: true, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_ip_address”: “10.1.4.3”}], “source_dest_check”: true, “status”: “in-use”, “subnet_id”: “subnet-f5sdfws”, “vpc_id”: “vpc-dbc5”}], “placement”: {“availability_zone”: “us-west-1a”, “group_name”: “”, “tenancy”: “default”}, “platform_details”: “Red Hat Enterprise Linux”, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_dns_name_options”: {“enable_resource_name_dns_a_record”: false, “enable_resource_name_dns_aaaa_record”: false, “hostname_type”: “ip-name”}, “private_ip_address”: “10.1.4.3”, “product_codes”: , “public_dns_name”: “”, “root_device_name”: “/dev/sda1”, “root_device_type”: “ebs”, “security_groups”: [{“group_id”: “sg-34”, “group_name”: “User group”}], “source_dest_check”: true, “state”: {“code”: 0, “name”: “pending”}, “state_transition_reason”: “”, “subnet_id”: “subnet-f5sdfws”, “tags”: {“Application Group”: “CORE”, “Application System”: “Development Team”, “Backupset”: “true”, “CST Start/Stop Schedule”: “0700;1900;Weekdays”, “CostCenter”: “Dev”, “Description”: “Evaluation Server”, “Environment”: “DEV”, “Name”: “test8”, “OS”: “RHEL”, “OS Version”: “8”, “Owner”: “Development Center”, “Patch Group”: “Normal”, “Sub Environment”: “Development”, “Type”: “Eval”}, “usage_operation”: “RunInstances:0010”, “usage_operation_update_time”: “2022-08-22T16:44:37+00:00”, “virtualization_type”: “hvm”, “vpc_id”: “vpc-db”}}

TASK [Wait for SSH to come up] **********************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:231
[WARNING]: Reset is not implemented for this connection
ok: [127.0.0.1 → 10.1.4.3] => (item={‘ami_launch_index’: 0, ‘image_id’: ‘ami-0beac6b6ed4da44ce’, ‘instance_id’: ‘06-005sd3sfs0a0d9’, ‘instance_type’: ‘t3a.medium’, ‘key_name’: ‘test’, ‘launch_time’: ‘2022-08-22T16:44:37+00:00’, ‘monitoring’: {‘state’: ‘disabled’}, ‘placement’: {‘availability_zone’: ‘us-west-1a’, ‘group_name’: ‘’, ‘tenancy’: ‘default’}, ‘private_dns_name’: ‘ip-10-1-4-3.us-west-1.compute.internal’, ‘private_ip_address’: ‘10.1.4.3’, ‘product_codes’: , ‘public_dns_name’: ‘’, ‘state’: {‘code’: 0, ‘name’: ‘pending’}, ‘state_transition_reason’: ‘’, ‘subnet_id’: ‘subnet-f5bsdfs’, ‘vpc_id’: ‘vpc-dbc5’, ‘architecture’: ‘x86_64’, ‘block_device_mappings’: [{‘device_name’: ‘/dev/sda1’, ‘ebs’: {‘attach_time’: ‘2022-08-22T16:44:38+00:00’, ‘delete_on_termination’: False, ‘status’: ‘attaching’, ‘volume_id’: ‘vol-0488sdfec2f4e9e6’}}], ‘client_token’: ‘64c1d4b064fa418d99eeca4aa44c7a1d’, ‘ebs_optimized’: True, ‘ena_support’: True, ‘hypervisor’: ‘xen’, ‘iam_instance_profile’: {‘arn’: ‘arn:aws-us-:iam::23489:instance-profile/Ansible’, ‘id’: ‘AIPAXKK’}, ‘network_interfaces’: [{‘attachment’: {‘attach_time’: ‘2022-08-22T16:44:37+00:00’, ‘attachment_id’: ‘eni-attach-03c0fe’, ‘delete_on_termination’: True, ‘device_index’: 0, ‘status’: ‘attaching’, ‘network_card_index’: 0}, ‘description’: ‘’, ‘groups’: [{‘group_name’: ‘User group’, ‘group_id’: ‘sg-34’}], ‘ipv6_addresses’: , ‘mac_address’: ‘06’, ‘network_interface_id’: ‘eni-0cac24cf’, ‘owner_id’: ‘23489’, ‘private_dns_name’: ‘ip-10-1-4-3.us-west-1.compute.internal’, ‘private_ip_address’: ‘10.1.4.3’, ‘private_ip_addresses’: [{‘primary’: True, ‘private_dns_name’: ‘ip-10-1-4-3.us-west-1.compute.internal’, ‘private_ip_address’: ‘10.1.4.3’}], ‘source_dest_check’: True, ‘status’: ‘in-use’, ‘subnet_id’: ‘subnet-f5bsdfs’, ‘vpc_id’: ‘vpc-dbc5’, ‘interface_type’: ‘interface’}], ‘root_device_name’: ‘/dev/sda1’, ‘root_device_type’: ‘ebs’, ‘security_groups’: [{‘group_name’: ‘User group’, ‘group_id’: ‘sg-34’}], ‘source_dest_check’: True, ‘tags’: {‘OS’: ‘RHEL’, ‘Owner’: ‘Development Center’, ‘Environment’: DEV’, ‘Sub Environment’: ‘Evaluation’', ‘CostCenter’: ‘Eval2’, ‘Backupset’: ‘true’, ‘Application System’: ‘Development Team’, ‘OS Version’: ‘8’, ‘Application Group’: ‘CORE’, ‘Patch Group’: ‘Normal’, ‘Description’: ‘Evaluation Server’, ‘Name’: ‘test8’, ‘CST Start/Stop Schedule’: ‘0700;1900;Weekdays’, ‘Type’: ‘Eval’}, ‘virtualization_type’: ‘hvm’, ‘cpu_options’: {‘core_count’: 1, ‘threads_per_core’: 2}, ‘capacity_reservation_specification’: {‘capacity_reservation_preference’: ‘open’}, ‘hibernation_options’: {‘configured’: False}, ‘metadata_options’: {‘state’: ‘pending’, ‘http_tokens’: ‘optional’, ‘http_put_response_hop_limit’: 1, ‘http_endpoint’: ‘enabled’, ‘http_protocol_ipv6’: ‘disabled’, ‘instance_metadata_tags’: ‘disabled’}, ‘enclave_options’: {‘enabled’: False}, ‘platform_details’: ‘Red Hat Enterprise Linux’, ‘usage_operation’: ‘RunInstances:0010’, ‘usage_operation_update_time’: ‘2022-08-22T16:44:37+00:00’, ‘private_dns_name_options’: {‘hostname_type’: ‘ip-name’, ‘enable_resource_name_dns_a_record’: False, ‘enable_resource_name_dns_aaaa_record’: False}, ‘maintenance_options’: {‘auto_recovery’: ‘default’}}) => {“ansible_loop_var”: “item”, “changed”: false, “elapsed”: 120, “item”: {“ami_launch_index”: 0, “architecture”: “x86_64”, “block_device_mappings”: [{“device_name”: “/dev/sda1”, “ebs”: {“attach_time”: “2022-08-22T16:44:38+00:00”, “delete_on_termination”: false, “status”: “attaching”, “volume_id”: “vol-0488sdfe”}}], “capacity_reservation_specification”: {“capacity_reservation_preference”: “open”}, “client_token”: “64c1d”, “cpu_options”: {“core_count”: 1, “threads_per_core”: 2}, “ebs_optimized”: true, “ena_support”: true, “enclave_options”: {“enabled”: false}, “hibernation_options”: {“configured”: false}, “hypervisor”: “xen”, “iam_instance_profile”: {“arn”: “arn:aws-us-:iam::23489:instance-profile/Ansible”, “id”: “AIPAX”}, “image_id”: “ami-0bea”, “instance_id”: “i-005”, “instance_type”: “t3a.medium”, “key_name”: “test”, “launch_time”: “2022-08-22T16:44:37+00:00”, “maintenance_options”: {“auto_recovery”: “default”}, “metadata_options”: {“http_endpoint”: “enabled”, “http_protocol_ipv6”: “disabled”, “http_put_response_hop_limit”: 1, “http_tokens”: “optional”, “instance_metadata_tags”: “disabled”, “state”: “pending”}, “monitoring”: {“state”: “disabled”}, “network_interfaces”: [{“attachment”: {“attach_time”: “2022-08-22T16:44:37+00:00”, “attachment_id”: “eni-attach-03c0fe95d6d45e0a2”, “delete_on_termination”: true, “device_index”: 0, “network_card_index”: 0, “status”: “attaching”}, “description”: “”, “groups”: [{“group_id”: “sg-34”, “group_name”: “User group”}], “interface_type”: “interface”, “ipv6_addresses”: , “mac_address”: “06”, “network_interface_id”: “eni-0cac”, “owner_id”: “23489”, “private_dns_name”: “ip-10-1-4-1x-1.us-west-1.compute.internal”, “private_ip_address”: “10.1.4.1x.1”, “private_ip_addresses”: [{“primary”: true, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_ip_address”: “10.1.4.3”}], “source_dest_check”: true, “status”: “in-use”, “subnet_id”: “subnet-f5sd”, “vpc_id”: “vpc-dbc5”}], “placement”: {“availability_zone”: “us-west-1a”, “group_name”: “”, “tenancy”: “default”}, “platform_details”: “Red Hat Enterprise Linux”, “private_dns_name”: “ip-10-1-4-3.us-west-1.compute.internal”, “private_dns_name_options”: {“enable_resource_name_dns_a_record”: false, “enable_resource_name_dns_aaaa_record”: false, “hostname_type”: “ip-name”}, “private_ip_address”: “10.1.4.3”, “product_codes”: , “public_dns_name”: “”, “root_device_name”: “/dev/sda1”, “root_device_type”: “ebs”, “security_groups”: [{“group_id”: “sg-34”, “group_name”: “User group”}], “source_dest_check”: true, “state”: {“code”: 0, “name”: “pending”}, “state_transition_reason”: “”, “subnet_id”: “subnet-f5sdfws”, “tags”: {“Application Group”: “CORE”, “Application System”: “Development Team”, “Backupset”: “true”, “CST Start/Stop Schedule”: “0700;1900;Weekdays”, “CostCenter”: Dev", “Description”: “Evaluation Server”, “Environment”: “DEV”, “Name”: “test8”, “OS”: “RHEL”, “OS Version”: “8”, “Owner”: “Development Center”, “Patch Group”: “Normal”, “Sub Environment”: “Evaluation”, “Type”: “Eval”}, “usage_operation”: “RunInstances:0010”, “usage_operation_update_time”: “2022-08-22T16:44:37+00:00”, “virtualization_type”: “hvm”, “vpc_id”: “vpc-dbc”}}
META: ran handlers
META: ran handlers

PLAY [Run post-launch baseline configuration on instance] *******************************************************************************************************************************
META: ran handlers

TASK [Update system name] ***************************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:265
fatal: [test8]: FAILED! => {“msg”: “The task includes an option with an undefined variable. The error was: ‘tags’ is undefined\n\nThe error appears to be in ‘/etc/ansible/playbooks/rhel-8-build.yml’: line 265, column 8, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: ‘Update system name’\n ^ here\n”}

PLAY RECAP ******************************************************************************************************************************************************************************
127.0.0.1 : ok=14 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
test8 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

Going from localhost to ‘launched’ host, it seems to drop the variables from the new_ec2_instances. I’m not sure how to pull those tags going from localhost to executing tasks on the newly launched host.

The registered new_ec2.instances has a tags dictionary key so item.tags.Name should reference it in a loop on new_ec2.instances. I assume domain[fqdn] is some other dictionary set somewhere else.

“tags”: {“Application Group”: “CORE”, “Application System”: “Development Team”, “Backupset”: “true”, “CST Start/Stop Schedule”: “0700;1900;Weekdays”, “CostCenter”: “Dev”, “Description”: “Evaluation Server”, “Environment”: “DEV”, “Name”: “test8”, “OS”: “RHEL”, “OS Version”: “8”, “Owner”: “Development Center”, “Patch Group”: “Normal”, “Sub Environment”: “Development”, “Type”: “Eval”}

  • name: ‘Update system name’
    shell: >
    hostnamectl set-hostname
    {{ item.tags.Name }}.{{ domain[‘fqdn’] }} --static --transient &&
    hostnamectl set-hostname {{ tags.Name }}.{{ domain[‘fqdn’] }} --pretty

loop: “{{ new_ec2.instances }}”

Walter

Correct, I’m getting the domain[‘fqdn’] in my global environment variables yml file.

I updated the hostname task, but it’s still failing on an undefined variable 'new_ec2" when it reaches that point

  • name: ‘Update system name’
    shell: >
    hostnamectl set-hostname
    {{ item.tags.Name }}.{{ domain[‘fqdn’] }} --static --transient &&
    hostnamectl set-hostname {{ item.tags.Name }}.{{ domain[‘fqdn’] }} --pretty
    loop: “{{ new_ec2.instances }}”

PLAY [Run post-launch baseline configuration on instance] *******************************************************************************************************************************
META: ran handlers

TASK [Update system name] ***************************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:265
fatal: [test8]: FAILED! => {“msg”: “‘new_ec2’ is undefined”}

PLAY RECAP ******************************************************************************************************************************************************************************
127.0.0.1 : ok=14 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
test8 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

So there are 2 different hosts with specific tasks ran from each. The start of this playbook has localhost set to create a new RHEL ec2 instance from an ami. I also prompt for specific vars at the beginning prior to creating a new ec2 instance. See below…I didn’t include all the prompts to keep this ansible post so it’s not so long but let me know if you need it. Does Ansible clear its memory of variables/facts from tasks from localhost to the new hosts? I want to be able to launch a new ec2 instance, connect to it, and then run post configuration tasks (without having to run 2 different ansible-playbook commands). The only issue has been trying to grab the tag Name from a newly launched ec2 instance. Maybe there’s a better way to do this than the approach I’m taking.

  • name: ‘Build a RHEL 8 server from AMI’
    hosts: ‘127.0.0.1’
    connection: ‘local’
    gather_facts: no

pre_tasks:

  • pause:
    prompt: >-
    What is the name of this system? ( ex: DB-09 )
    register: prompt_name_tag

  • pause:
    prompt: >-
    Instance Type? ( press Enter for default: t3a.medium )
    register: prompt_ec2_type

  • pause:
    prompt: >-
    Provide an AMI ID:
    ( press Enter for default: Vanilla RHEL 8 Base AMI )
    register: prompt_ami_id

tasks:

  • name: ‘Launch instance’
    ec2_instance:
    image_id: >-
    {{
    prompt_ami_id.user_input if prompt_ami_id.user_input
    else build[‘aws’][‘defaults’][‘ami’]
    }}
    instance_type: >-
    {{
    prompt_ec2_type.user_input if prompt_ec2_type.user_input
    else ‘t3a.medium’
    }}

register: new_ec2

  • name: ‘Run post-launch baseline configuration on instance’
    hosts: ‘launched’
    gather_facts: no
    become: yes

roles:

  • ‘component_baselines/hostname’

Details of the hostname role being called:

  • name: ‘Update system name’
    shell: >
    hostnamectl set-hostname
    {{ item.tags.Name }}.{{ domain[‘fqdn’] }} --static --transient &&
    hostnamectl set-hostname {{ item.tags.Name }}.{{ domain[‘fqdn’] }} --pretty
    loop: “{{ new_ec2.instances }}”

I was able to reference new_ec2 using the hostvars magic variable as follows
:

  • name: ‘Run post-launch baseline configuration on instance’
    hosts: ‘launched’
    gather_facts: no
    become: yes

tasks:

  • debug: var=hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’]
    when: hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’] is defined

The output shows the following:

TASK [debug] ****************************************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:255
ok: [test8] => {
“hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’]”: [
{
“ami_launch_index”: 0,
“architecture”: “x86_64”,
“block_device_mappings”: [
{
“device_name”: “/dev/sda1”,
“ebs”: {
“attach_time”: “2022-08-23T14:32:05+00:00”,
“delete_on_termination”: false,
“status”: “attaching”,
“volume_id”: “vol-0”
}
}
],
“capacity_reservation_specification”: {
“capacity_reservation_preference”: “open”
},
“client_token”: “”,
“cpu_options”: {
“core_count”: 1,
“threads_per_core”: 2
},
“ebs_optimized”: true,
“ena_support”: true,
“enclave_options”: {
“enabled”: false
},
“hibernation_options”: {
“configured”: false
},
“hypervisor”: “xen”,
“iam_instance_profile”: {
“arn”: “arn:aws-us:iam::xxxxxxxxxxxxxxxx:instance-profile/xxxxxxxxxxx”,
“id”: “xxxxxxxxxxxx”
},
“image_id”: “ami-0xxxxxxxxxxxxxx”,
“instance_id”: “i-0xxxxxxxxxxxx”,
“instance_type”: “t3a.medium”,
“key_name”: “xxxx”,
“launch_time”: “2022-08-23T14:32:05+00:00”,
“maintenance_options”: {
“auto_recovery”: “default”
},
“metadata_options”: {
“http_endpoint”: “enabled”,
“http_protocol_ipv6”: “disabled”,
“http_put_response_hop_limit”: 1,
“http_tokens”: “optional”,
“instance_metadata_tags”: “disabled”,
“state”: “pending”
},
“monitoring”: {
“state”: “disabled”
},
“network_interfaces”: [
{
“attachment”: {
“attach_time”: “2022-08-23T14:32:05+00:00”,
“attachment_id”: “eni-attach-06xxxxx7”,
“delete_on_termination”: true,
“device_index”: 0,
“network_card_index”: 0,
“status”: “attaching”
},
“description”: “”,
“groups”: [
{
“group_id”: “sg-34758e50”,
“group_name”: “xxxxxx”
}
],
“interface_type”: “interface”,
“ipv6_addresses”: ,
“mac_address”: “0xxxxxxx”,
“network_interface_id”: “eni-xxxxxxxx”,
“owner_id”: “xxxxxxxxxxxx”,
“private_dns_name”: “ip-xxx-xx-xx-xx.us-west-1.compute.internal”,
“private_ip_address”: “xxx.xx.xx.24”,
“private_ip_addresses”: [
{
“primary”: true,
“private_dns_name”: “ip-xxx-xx-xx-24.us-west-1.compute.internal”,
“private_ip_address”: “xxx.xx.xx.24”
}
],
“source_dest_check”: true,
“status”: “in-use”,
“subnet_id”: “subnet-xxx”,
“vpc_id”: “vpc-xxx”
}
],
“placement”: {
“availability_zone”: “us-west-1a”,
“group_name”: “”,
“tenancy”: “default”
},
“platform_details”: “Red Hat Enterprise Linux”,
“private_dns_name”: “ip-xxx-xx-xx-24.us-west-1.compute.internal”,
“private_dns_name_options”: {
“enable_resource_name_dns_a_record”: false,
“enable_resource_name_dns_aaaa_record”: false,
“hostname_type”: “ip-name”
},
“private_ip_address”: “xxx.xx.xx.24”,
“product_codes”: ,
“public_dns_name”: “”,
“root_device_name”: “/dev/sda1”,
“root_device_type”: “ebs”,
“security_groups”: [
{
“group_id”: “sg-xxxxx”,
“group_name”: “xxxxx”
}
],
“source_dest_check”: true,
“state”: {
“code”: 0,
“name”: “pending”
},
“state_transition_reason”: “”,
“subnet_id”: “subnet-xxxxx”,
“tags”: {
“Application Group”: “CO”,
“Application System”: “xxx”,
“Backupset”: “true”,
“CST Start/Stop Schedule”: “0700;1900;Weekdays”,
“CostCenter”: “xxx”,
“Description”: “Evaluation Server”,
“Environment”: “xxxxx”,
“Name”: “test8”,
“OS”: “RHEL”,
“OS Version”: “8”,
“Owner”: “CO”,
“Patch Group”: “Normal”,
“Sub Environment”: “xxxxxxxx”,
“Type”: “Eval”
},
“usage_operation”: “RunInstances:0010”,
“usage_operation_update_time”: “2022-08-23T14:32:05+00:00”,
“virtualization_type”: “hvm”,
“vpc_id”: “vpc-dxxxxx”
}
]
}

My next question is, how can I grab the Name tags and use it in my update system name command below? I tried this but it errors out:

  • name: ‘Update system name’
    shell: >

hostnamectl set-hostname
{{ hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’][‘tags’][‘Name’] }}.{{ domain[‘fqdn’] }} --static --transient &&
hostnamectl set-hostname {{ hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’] ‘tags]’['‘Name’] }}.{{ domain[‘fqdn’] }} --pretty

TASK [Update system name] ***************************************************************************************************************************************************************
task path: /etc/ansible/playbooks/rhel-8-build.yml:278
fatal: [test8]: FAILED! => {“msg”: “The task includes an option with an undefined variable. The error was: ‘list object’ has no attribute ‘tags’\n\nThe error appears to be in ‘/etc/ansible/playbooks/rhel-8-build.yml’: line 278, column 8, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: ‘Update system name’\n ^ here\n”}

hostnamectl set-hostname {{ hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’] ‘tags]’['‘Name’] }}.{{ domain[‘fqdn’] }} --pretty

this line is missing a “[” before ‘tags’ and has a “]” before the ’ after tags.

hostnamectl set-hostname {{ hostvars[‘127.0.0.1’][‘new_ec2’][‘instances’] [ ‘tags]’ ['‘Name’] }}.{{ domain[‘fqdn’] }} --pretty

Thanks Walter! I better grab my reading glasses. I made the changes:

image.png

That should be correct, right?

It still fails even after making that correction

Ahh, made a slight change to finally get it working! Thanks for all your replies, Walter.

Screenshot 2022-08-23 152347.png

That would do it. Congrats and good luck.

Walter