Home > OS >  Terraform import : ignore specific resource from public module
Terraform import : ignore specific resource from public module

Time:02-19

I trying to import the state of a (private ) s3 bucket which was created via the console. Im using the public s3 module. I was able to create a module block and import the state of the bucket. However terraform plan also tries to create a aws_s3_bucket_public_access_block . How do I ignore or stop terraform from creating that specific resource from the module ?

main.tf


locals {
  region = "dev"
}

module "s3_bucket" {
  source = "terraform-aws-modules/s3-bucket/aws"

  bucket = "my-${region}-bucket"
  acl    = "private"

  block_public_acls = true
  block_public_policy = true

  lifecycle_rule = [
    {
      id      = "weekly_expiration_rule"
      enabled = true
      expiration = {
        days = 7
      }
    }
  ]
}

Import command for bucket - terraform import module.s3_bucket.aws_s3_bucket.this my-dev-bucket

Meanwhile when I try importing the public access block resource I run into the error ` Error: Cannot import non-existent remote object, even when I have the settings configured on the bucket.

CodePudding user response:

Looking into the source code more carefully , specifically this section

resource "aws_s3_bucket_public_access_block" "this" {
  count = var.create_bucket && var.attach_public_policy ? 1 : 0

setting attach_public_policy to false got me what I needed

CodePudding user response:

You should run terraform plan to see the real output and read the source code in github (resource "aws_s3_bucket" "this"). You can see count at line 6.

  # module.s3_bucket.aws_s3_bucket.this[0] will be created   
  ...
  # module.s3_bucket.aws_s3_bucket_public_access_block.this[0] will be created   
  ...

You can import with these commands:

t import module.s3_bucket.aws_s3_bucket.this[0] my-test-bucket-823567823576023
t import module.s3_bucket.aws_s3_bucket_public_access_block.this[0] my-test-bucket-823567823576023

My test main.tf, after I import it, t plan show 0 to add

terraform {
  required_version = ">= 0.13.1"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.69"
    }
    random = {
      source  = "hashicorp/random"
      version = ">= 2.0"
    }
  }
}

provider "aws" {
  region = "ap-southeast-1"
}

module "s3_bucket" {
  source = "terraform-aws-modules/s3-bucket/aws"

  bucket = "my-test-bucket-823567823576023"
  acl    = "private"
}
  • Related