Repository: ansible/ansible

Issue:
Terraform module targeting
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
terraform
##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.5.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
  
```
Running latest devel branch for testing terraform in a separate virtual environment
```

/var/lib/awx/venv/devel_branch/bin/pip install git+https://github.com/ansible/ansible.git@devel -U

```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->
No output was displayed from this command
##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
N/A
##### SUMMARY
<!--- Explain the problem briefly -->
Targeting a specific module seems to still load the entire plan
##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

<!--- Paste example playbooks or commands between quotes below -->
```yaml

- name: run terraform - aws base
  terraform:
    project_path : '../terraform/plans/awx'
    force_init: true
    variables:
      account_id: "{{ cloud_account }}"
      access_key: "{{ access_key }}"
      secret_key: "{{ secret_key }}"
      token: "{{ token }}"
      key_name: "{{ cloud_key }}"
      cidr_bock: "{{ cidr_block }}"
      region: "{{ cloud_region }}"
      repository_uri: "{{ repository_uri }}"
      rds_master_username: 'awxmaster'
      rds_master_password: "{{ rds_master_password }}"
      awx_db_username: 'awxdb'
      awx_db_password: "{{ awx_db_password }}"
    targets: module.aws_base

```

Terraform plan setup

```

module "aws_base" {
  source             = "../../modules/aws_base"
  name               = "ras-vpc"
  region             = "${var.region}"
  cidr_block         = "${var.cidr_block}"
  availability_zones = "${lookup(var.availability_zones, "${var.region}")}"
  environment        = "${var.environment}"
  account_id         = "${var.account_id}"
  dns_support        = true
  dns_hostnames      = true
}
...

module "next_module"
{
....
}
```
<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
Only run the specified targeted module from the terraform plan.
Instead of running only `module.aws_base` it attempted to run `module.next_module` as well
##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->
The entire plan was run.
<!--- Paste verbatim command output between quotes below -->
```

```

I have to run the plan in stages 
* aws_base
* rds
* postgres

Due to limitations in Terraform


Discussion:
Files identified in the description:
* [lib/ansible/modules/cloud/misc/terraform.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/misc/terraform.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @ryansb
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/modules/cloud/misc/terraform.py b/lib/ansible/modules/cloud/misc/terraform.py
--- a/lib/ansible/modules/cloud/misc/terraform.py
+++ b/lib/ansible/modules/cloud/misc/terraform.py
@@ -165,11 +165,15 @@ def init_plugins(bin_path, project_path):
         module.fail_json(msg="Failed to initialize Terraform modules:\r\n{0}".format(err))
 
 
-def build_plan(bin_path, project_path, variables_args, state_file, plan_path=None):
+def build_plan(bin_path, project_path, variables_args, state_file, targets, plan_path=None):
     if plan_path is None:
         f, plan_path = tempfile.mkstemp(suffix='.tfplan')
 
     command = [bin_path, 'plan', '-input=false', '-no-color', '-detailed-exitcode', '-out', plan_path]
+
+    for t in (module.params.get('targets') or []):
+        command.extend(['-target', t])
+
     command.extend(_state_args(state_file))
 
     rc, out, err = module.run_command(command + variables_args, cwd=project_path)
@@ -255,7 +259,7 @@ def main():
     needs_application, changed = True, True
 
     if state == 'planned':
-        plan_file, needs_application = build_plan(command[0], project_path, variables_args, state_file, plan_file)
+        plan_file, needs_application = build_plan(command[0], project_path, variables_args, state_file, module.params.get('targets'), plan_file)
     if state == 'absent':
         # deleting cannot use a statefile
         needs_application = True
@@ -266,7 +270,7 @@ def main():
     elif plan_file and not os.path.exists(plan_file):
         module.fail_json(msg='Could not find plan_file "{0}", check the path and try again.'.format(plan_file))
     else:
-        plan_file, needs_application = build_plan(command[0], project_path, variables_args, state_file, plan_file)
+        plan_file, needs_application = build_plan(command[0], project_path, variables_args, state_file, module.params.get('targets'), plan_file)
         command.append(plan_file)
 
     if needs_application and not module.check_mode and not state == 'planned':


Test patch: